0% found this document useful (0 votes)
600 views

2022schemeupadated CPL Manual

This document describes the process of compiling and running a C program. It explains that C programs must be saved with a .c file extension. The cc command is used to compile programs, generating an a.out executable file if there are no errors. This file can then be run using ./a.out. The compilation process involves four phases - preprocessing, compilation, assembly, and linking. Preprocessing removes comments and expands macros and includes. The output of each phase is stored in intermediate files with extensions .i, .s, and .o. The linker combines these files and adds code to setup command line arguments in the final executable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
600 views

2022schemeupadated CPL Manual

This document describes the process of compiling and running a C program. It explains that C programs must be saved with a .c file extension. The cc command is used to compile programs, generating an a.out executable file if there are no errors. This file can then be run using ./a.out. The compilation process involves four phases - preprocessing, compilation, assembly, and linking. Preprocessing removes comments and expands macros and includes. The output of each phase is stored in intermediate files with extensions .i, .s, and .o. The linker combines these files and adds code to setup command line arguments in the final executable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

SAMBHRAM INSTITUTE OF TECHNOLOGY

(Affiliated to Visvesvaraya Technological University, Belgaum)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING
BANGALORE

LABORATORY MANUAL

C Programming Laboratory
(Effective from the academic year 2018 -2019)
for
BE: II Semester

Dept. of CSE, SaIT


Dept. of CSE, SaIT
SAMBHRAM INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University, Belgaum)

Department of Computer Science and Engineering


BANGALORE

LAB MANUAL
C Programming Laboratory

For
II - SEMESTER LAB

PREPARED BY:

FACULTY NAME:

(1) …………………………………………………………………….

(2) …………………………………………………………………….

BRANCH: …………………………………..

Dept. of CSE, SaIT


Dept. of CSE, SaIT
Department of Computer Science and Engineering
Vision of the Department:
To professionally drive and train the young minds by placing them in forefront of technological,
scientific and engineering discipline to glorify the future of sambhram institute of technology as a
shining star in the world of computer technology

Mission of the Department:


M1. To act as the nurturing ground for young professionals who seek to make a difference and
create a talent pool for various industries so that there may be synergistic growth for both.
M2. To establish state-of-the-art facilities meeting the requirements of specified curriculum to
inculcate learning process of the students.
M3. To provide exposure of latest tools and technologies in the area of engineering and
technologies
M4. To produce successful graduates with personal and professional responsibilities and
commitment to lifelong learning.

Program Educational Objectives


PEO-1: To produce graduates having a strong background of basic science, Mathematics &
Engineering and ability to use these tools.
PEO-2: To produce graduates who can demonstrate technical competence in the field of
computer science and engineering and develop solutions to the complex problems.
PEO-3: To produce graduates having professional competence through life-long learning such as
advanced degrees, professional skills and other professional activities related globally to
engineering & society.
PEO- 4: To produce graduates who function effectively in a multi-disciplinary environment and
individually, within a societal and environmental context.
PEO-5: To produce graduates who would be able to take individual responsibility and work as a
part of a team towards the fulfillment of both individual and organizational goals

Program Specific Outcomes


PSO 1: should be able to understand the concepts computer science and engineering and their
applications in the field of emerging technologies and other relevant areas.
PSO 2: Should have an ability to apply technical knowledge and usage of modern hardware &
software tools related to computer science and engineering for solving real world problems.
PSO 3: Should have the capability to analyze, comprehend, design & develop subsystems/
systems for a variety of engineering applications and thus demonstrating professional ethics &
concern for societal well being.

Dept. of CSE, SaIT


Dept. of CSE, SaIT
COMPUTER PROGRAMMING LAB (21CPL17/27)

Program Outcomes
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,and an engineering specialization
to the solution of complex engineering problems.

2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences,and engineering sciences.

3. Design / development of solutions: Design solutions for complex engineering problems and design system components or processes
that meet the specified needs with appropriate consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including
prediction and modeling to complex engineering activities with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural
issues and the consequent responsibilities relevant to the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms ofthe engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or leader indiverse teams, and in
multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the engineering community and with society at
large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
Department of CSE, SAIT 1
COMPUTER PROGRAMMING LAB (21CPL17/27)

11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management principles and
apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage inindependent and life-long
learning in the broadest context of technological change.

FAMILIARIZATION WITH COMPUTER HARDWARE AND PROGRAMMING ENVIRONMENT,


CONCEPT OF NAMING THE PROGRAM FILES, STORING, COMPILATION, EXECUTION
AND DEBUGGING..

C is a high level language and it needs a compiler to convert it into an executable code so that the program
can be run on our machine.

How to compile and run a C program?

To compile and run a C program we need to first type the C program using an editor. We will be using the
editor gedit to edit C programs.

We first create a C program using an editor gedit and save the file as <filename>.c. All C program files must be given
the extension .c (dot followed by lower case c). Example, palin.c, sqroot.c, binsrch.c, matmul.c etc.

To edit the file, open the terminal window either by typing <ctrl>+<Alt>+t or by double clicking on the Terminal icon
in the Task Bar. At the command prompt $ (dollar) type gedit <filename>.c’ as shown below.
Department of CSE, SAIT 2
COMPUTER PROGRAMMING LAB (21CPL17/27)

$ gedit hello.c

Department of CSE, SAIT 3


COMPUTER PROGRAMMING LAB (21CPL17/27)

Opens the editor gedit with the filename as hello.c. Now, type / edit the code for the program. After completion of
typing, save the program. To save use the short cut key ‘<ctrl> + s’.

Now, in the terminal window, at the prompt, type the command to compile the program as shown below

$ cc hello.c

An output file (executable file) with name a.out is generated if there are no errors in the program. In case there are
errors, cc will display the errors.

Executable file -a.out, is generated and we can run the executable file. To run the program type ./a.out at the prompt
as shown below

$./a.out

Department of CSE, SAIT 4


COMPUTER PROGRAMMING LAB (21CPL17/27)

What happens during the compilation process?

Compiler converts a C program into an executable. There are four phases for a C program to become an
executable:

1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, we get the all intermediate files in the current directory along with the
executable.

The pre-processing phase includes

 Removal of Comments
 Expansion of Macros
 Expansion of the included files.
The preprocessed output is stored in the filename.i.

$gedit filename.i

Department of CSE, SAIT 5


COMPUTER PROGRAMMING LAB (21CPL17/27)

We can see the contents of the intermediate file using the above command. The comments are removed are macros are
replaced with corresponding code. Header file has been expanded and included in source file.

$gedit filename.s

This file contains code written in assembly language. This file is taken as input by the assembler and it converts into
filename.o output file. This will contain code in machine language.

During the linking phase, the function calls are linked with their definitions. The linker adds additional code to setup
the environment for command line arguments. As a result, there will be a significant increase in the size of the file.

QUESTIONS FOR VIVA:

1. What is a compiler? What is the function of a compiler?


2. Explain intermediate code.
3. Which are the four steps followed to convert a C program to executable code?
4. What is the difference between assembly and machine language?
5. What are the steps followed in preprocessing phase?
6. What happens during the linking phase?
7. Why does the size of the file increase after linking phase?

Department of CSE, SAIT 6


COMPUTER PROGRAMMING LAB (21CPL17/27)

1. SIMULATION OF A SIMPLE CALCULATOR.

ALGORITHM:
Input: Two integers (operands) and operators
Output: Result of the operation
1. Start
2. Read two operands and operator to perform the calculation
3. Check if operator equals addition then goto step 4 else goto step 5
4. Compute addition operation:
Res=num1+num2
5. Check if operator equals subtraction then goto step 6 else step 7
6. Compute subtraction operation
Res=num1-num2
7. Check if operator equals multiplication then goto step 8 else step 9
8. Compute multiplication
operation Res=num1*num2
9. Check if operator equals division goto step 10 else step14
10. Check the value of num2 equals Zero or not, if num2==0 then goto step 12 else goto step
11. Compute division operation
Res=num1/num2 and goto step 13
12. Enter a value of num2 greater than zero.
13. Display the result
14. Read the two operands which are valid
15. Stop

Department of CSE, SAIT 7


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
int main()
{
int choice, operand1, operand2;
char operator;
for(;;)
{
printf("\n ENTER THE ARITHMETIC EXPRESSION\n");
scanf("%d %c %d", &operand1, &operator, &operand2);
switch(operator)
{
case '+':printf("\n RESULT=%d\n",operand1+operand2);
break;
case '-':printf("\nRESULT=%d\n",operand1-operand2);
break;
case '*':printf("\nRESULT=%d\n",operand1*operand2);
break;
case '/':printf("\n RESULT=%g\n",(float)operand1/operand2);
break;
case '%':printf("\n RESULT=%d\n",operand1%operand2);
break;
}

Department of CSE, SAIT 8


COMPUTER PROGRAMMING LAB (21CPL17/27)

printf("\n press 1 to continue and 0 to quit:");


scanf("%d", &choice);
if(0==choice)
{
break;
}
}
return 0;
}

OUTPUT:

[root@localhost cpl]# cc arithmetic.c


[root@localhost cpl]# ./a.out

ENTER THE ARITHMETIC EXPRESSION


1+2
RESULT=3
PRESS 1 TO CONTINUE AND 0 TO QUIT:1

ENTER THE ARITHMETIC EXPRESSION


5-2
RESULT=3
PRESS 1 TO CONTINUE AND 0 TO QUIT:1

Department of CSE, SAIT 9


COMPUTER PROGRAMMING LAB (21CPL17/27)

ENTER THE ARITHMETIC EXPRESSION


2*3
RESULT=6
PRESS 1 TO CONTINUE AND 0 TO QUIT:1

ENTER THE ARITHMETIC EXPRESSION


5/2
RESULT=2.5
PRESS 1 TO CONTINUE AND 0 TO QUIT:1

ENTER THE ARITHMETIC EXPRESSION


5%2
RESULT=1
PRESS 1 TO CONTINUE AND 0 TO QUIT:0

QUESTIONS FOR VIVA:

1. Why do we need to include stdio.h file in a C program?


2. What are the different types of arithmetic operators?
3. What are the different datatypes?
4. What is the difference between / and % operator?
5. Why do we use printf()?
6. Why do we use scanf()?
7. What is a Variable?

Department of CSE, SAIT 10


COMPUTER PROGRAMMING LAB (21CPL17/27)

2. COMPUTE THE ROOTS OF A QUADRATIC EQUATION BY ACCEPTING THE


COEFFICIENTS. PRINT APPROPRIATE MESSAGES.

ALGORITHM:
Input: Three non zero coefficients a,b and c of a quadratic equation.
Output: To compute roots for the quadratic equation.
1. Start
2. Read three non zero coefficients a,b and c.
3. Check if a is equal to zero. If true, go to step 4 else go to step 5.
4. Display the equation is linear and go to step 11.
5. Calculate the discriminant as follows:
D= b*b - 4* a*c
6. Check if discriminant is 0. If true, go to step 7, else go to step 8.
7. Compute roots as follows:
Root1 = -b/2*a
Root2 = root 1
Display: Roots are real and equal. Root1. Go to step 11.
8. Check is discriminant is greater than 0. If true, go to step 9 else go to step 10.
9. Compute roots as follows:
root1= (-b + sqrt(D))/(2*a)
Root2 = (+b -sqrt(D))/(2*a)
Display: Roots are real and distinct. Root1 and Root2. Go to step 11.

Department of CSE, SAIT 11


COMPUTER PROGRAMMING LAB (21CPL17/27)

10. Calculate

Department of CSE, SAIT 12


COMPUTER PROGRAMMING LAB (21CPL17/27)

Rpart = -b/2*a
Ipart = sqrt(-d)/(2*a)
Display. Roots are imaginary. Rpart and ipart. Go to step 11.
11. Stop

PROGRAM

#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,desc,r1,r2,realpart,imgpart;
printf("ENTER THE COEFFICIENTS OF a, bAND c :");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("COEFFICIENT OF A CANNOT BE ZERO....\n");
printf("PLEASE TRY AGAIN....\n");
return 1;
}
desc=(b*b)-(4.0*a*c);
if(desc==0)
{

Department of CSE, SAIT 13


COMPUTER PROGRAMMING LAB (21CPL17/27)

printf("THE ROOTS ARE REAL AND EQUAL\n");


r1=r2=(-b)/(2.0*a);
printf("THE TWO ROOTS ARE r1=r2=%f\n",r1);
}
else if(desc>0)
{
printf("THE ROOTS ARE REAL AND DISTINCT\n");
r1=(-b+sqrt(desc))/(2.0*a);
r2=(-b-sqrt(desc))/(2.0*a);
printf("THE ROOTS ARE r1=%f AND r2=%f\n",r1,r2);
}
else
{
printf("THE ROOTS ARE REAL AND IMAGINARY\n");
realpart=(-b)/(2.0*a);
imgpart=sqrt(-desc)/(2.0*a);
printf("THE ROOTS ARE r1=%f + i %f\n",realpart,imgpart);
printf("r2=%f - i %f\n",realpart,imgpart);
}
return 0;
}

Department of CSE, SAIT 14


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT:

[root@localhost cpl]# cc quadratic.c -lm


[root@localhost cpl]# ./a.out

ENTER THE CO-EFFICIENTS OF a, b, c


0 1 2
COEFFICIENT OF A CANNOT BE ZERO....
PLEASE TRY AGAIN....
*************************************************************
ENTER THE CO-EFFICIENTS OF a, b, c
1 4 4
THE ROOTS ARE REAL AND EQUAL
THE TWO ROOTS ARE r1=r2=-2
********************************************************
ENTER THE CO-EFFICIENTS OF a, b, c
1 5 3
ROOTS ARE REAL AND DISTINCT
THE ROOTS ARE r1==-0.697224 AND r2=-4.30278
*************************************************************
PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION
ENTER THE CO-EFFICIENTS OF a, b, c
3 2 1

Department of CSE, SAIT 15


COMPUTER PROGRAMMING LAB (21CPL17/27)

THE ROOTS ARE REAL AND IMAGINARY


r1=-0.333333+i0.471405
r2=-0.333333-i0.471405

QUESTIONS FOR VIVA:

1. What are library files? How are they called in a C program?


2. What are format strings? Explain with example.
3. What is a preprocessor? Which preprocessor is used in this program?
4. Why do we use \n ?
5. What is the return type of main function? Can we use void()? If yes, explain
what changes need to be made to the program.

Department of CSE, SAIT 16


COMPUTER PROGRAMMING LAB (21CPL17/27)

3. AN ELECTRICITY BOARD CHARGES THE FOLLOWING RATES FOR THE USE OF


ELECTRICITY: FOR THE FIRST 200 UNITS80 PAISE PER UNIT: FOR THE NEXT 100 UNITS
90 PAISE PER UNIT: BEYOND 300 UNITS RS 1 PER UNIT.ALL USERS ARE CHARGED A
MINIMUM OF RS. 100 AS METER CHARGE. IF THE TOTAL AMOUNT IS MORE THANRS
400, THEN AN ADDITIONAL SURCHARGE OF 15% OF TOTAL AMOUNT IS CHARGED.
WRITE A PROGRAM TOREAD THE NAME OF THE USER, NUMBER OF UNITS CONSUMED
AND PRINT OUT THE CHARGES.

ALGORITHM:
Input: Customer name and unit consumed
Output: Customer name, units consumed and total amount to be paid
1. Start
2. Read the name of customer and the unit consumed by the customer
3. Check if the unit consumed is greater than 1 and less than 200,if true goto step 4
else goto step 5
4. Compute: Charge=0.8*unit consumed
5. Check if unit is greater than or equal 201 and less than 300,if true goto step 6
else goto step 7
6. Compute:Charge=0.8*(200)+0.9*(unit 200)
7. Compute:Charge=0.8*200+0.9*(100)+1*(unit-300)
8. After calculating charge,find
total: Total=charge+100

Department of CSE, SAIT 17


COMPUTER PROGRAMMING LAB (21CPL17/27)

9. Check if total is greater than 400,if true goto step 10 else goto step 11
10. Compute total(after surcharge)=total *115/100 and proceed to step 11
11. Display the customer name,Units Consumed and total charge per unit
12. Stop

PROGRAM

#include <stdio.h>
int main()
{
float unit,total,charge;
char name[20];
printf("Enter the name : "); // Accept Customer's name
gets(name);
printf("Enter the units : "); // Accept No. of units consumed
scanf("%f",&unit);
charge=0;
if(unit>=1&&unit<=200) // Charge 80 paise per unit for the first 200 units
{
charge=0.8 * unit;
}
else if(unit>=201&&unit<=300) // Charge 80 paise per unit for the first 200 units and
{ // 90 paise per unit for the next 100 units

Department of CSE, SAIT 18


COMPUTER PROGRAMMING LAB (21CPL17/27)

charge = 0.8*(200) + 0.9*(unit-200);


}
else if (unit > 300) //Charge 80 paise per unit for the first 200 units,
{ // 90 paise per unit for the next 100 units and one rupee per unit for all units above 300
charge = 0.8*(200) + 0.9*(100) + 1*(unit-300);
}
total=charge+100; // Add Meter charge of Rs. 100
if(total>400)
{
total = total + (0.15*total); // Add additional surcharge of 15 percent of total
amount
}
printf("\n\nELECTRICITY BILL\n");// Display the electricity bill
printf(" \n");
printf("\nName : %s\n",name);
printf("No. of units: %0.2f\n",unit);
printf("Total Bill Amount: Rs. %0.2f\n",total);
printf(" \n");
return 0;
}

Department of CSE, SAIT 19


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT:

[root@localhost cpl]# cc electricity.c


[root@localhost cpl]# ./a.out

1. Enter the name : Anitha


Enter the units : 0
ELECTRICITY BILL

Name : Anitha
No. of units: 0.00
Total Bill Amount: Rs. 100.00

2. $ ./a.out
Enter the name : Harish
Enter the units : 167
ELECTRICITY BILL

Name : Harish
No. of units: 167.00
Total Bill Amount: Rs. 233.60

3.$ ./a.out

Department of CSE, SAIT 20


COMPUTER PROGRAMMING LAB (21CPL17/27)

Enter the name : Anuradha


Enter the units : 598
ELECTRICITY BILL

Name : Anuradha
No. of units: 598.00
Total Bill Amount: Rs. 745.20

4.$ ./a.out
Enter the name : Rajeev Gupta
Enter the units : 876
ELECTRICITY BILL

Name : Rajeev Gupta


No. of units: 876.00
Total Bill Amount: Rs. 1064.90

QUESTIONS FOR VIVA:


1. What is the difference between getc(), getch() and gets()?
2. What is the difference between printf() and scanf()?
3. What are looping structures in C? Which looping structure have you used in your
C program? Justify.
4. What are control structures in C? Give some examples.

Department of CSE, SAIT 21


COMPUTER PROGRAMMING LAB (21CPL17/27)

4. Write a C Program to display the following by reading the number of rows as input,
1
1 2 1
12 3 21
12 3 4 3 2 1

nth row

PROGRAM

#include <stdio.h>

void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0; i<=n; i++)
{
for(j=1; j<=n-i; j++) // print blank spaces
printf(" ");

for(j=1;j<=i; j++) // Display number in ascending order upto middle


printf("%d", j);

Department of CSE, SAIT 22


COMPUTER PROGRAMMING LAB (21CPL17/27)

for(j=i-1;j>=1;j--) // Display number in reverse order after middle


printf("%d",j);

printf("\n");
}
}

OUTPUT :

Input number of rows : 4

1
1 2 1
12 3 21
12 3 4 3 2 1

Department of CSE, SAIT 23


COMPUTER PROGRAMMING LAB (21CPL17/27)

5. IMPLEMENT BINARY SEARCH ON INTEGERS/NAMES

ALGORITHM:
Input: List of unsorted elements and element to be searched.
Output: Sorted list and element is present or not.
1. Start
2. Read size of the array and list of elements which are not sorted.
3. Use swap function in a loop to sort the given array.
4. Display the sorted list of elements.
5. Read the element to be searched. key.
6. Check if first is not equal to last. If true, find the middle element.
7. A. Check if the key is equal to the middle element. If true, element is found at
n/2 index and exit loop. Go to step 8.
B. Else, check if the key is greater than middle element. If true, change first to mid.
Go to step 6.
C. Else, check if the key is smaller than middle element. If true, change last to mid.
Go to step 6.
8. Stop.

Department of CSE, SAIT 24


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[100], num, i, mid, low, high, found, key;
printf("\n ENTER THE NUMBER OF ELEMENTS \n");
scanf("%d", &num);
printf("\n ENTER THE ELEMENTS IN ASCENDING ORDER \n");
for(i=0;i<num;i++)
scanf("%d", &a[i]);
printf("\n ENTER THE KEY ELEMENT \n");
scanf("%d",&key);
found=0;
low=0;
high=num-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
found=1;

Department of CSE, SAIT 25


COMPUTER PROGRAMMING LAB (21CPL17/27)

break;
}
else
if(key<a[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
if(found)
printf("\n KEY ELEMENT %d FOUND AT POSTION %d \n", key, mid+1);
else
printf("\n KEY ELEMENT NOT FOUND \n");
return 0;
}

Department of CSE, SAIT 26


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT:

[root@localhost cpl]# cc binarysearch.c


[root@localhost cpl]# ./a.out

ENTER THE NUMBER OF ELEMENTS


5

ENTER THE ELEMENTS IN ASCENDING ORDER


1 2 3 4 5
ENTER THE KEY ELEMENT
4
KEY ELEMENT 4 FOUND AT POSTION 4

**********************************************

ENTER THE NUMBER OF ELEMENTS


5
ENETR THE ELEMENTS IN ASCENDING ORDER
1 2 3 4 5
ENTER THE KEY ELEMENT
6
KEY ELEMENT NOT FOUND

Department of CSE, SAIT 27


COMPUTER PROGRAMMING LAB (21CPL17/27)

BINARY SEARCH ON NAMES

PROGRAM
#include <stdio.h>
#include <string.h>
void main()
{
int i,n,low,high,mid;
char a[50][50],key[20];
printf("enter the number of names \n");
scanf("%d",&n);
printf("enter the name in ascending order\n");
for(i=0;i<=n-1;i++)
{
scanf("%s",&a[i]);
}
printf("\n");
printf("enter the name to be searched\n");
scanf("%s",&key);
low=0;
high=n-1;
while(low<=high)
{

Department of CSE, SAIT 28


COMPUTER PROGRAMMING LAB (21CPL17/27)

mid=(low+high)/2;
if (strcmp(key,a[mid])==0)
{
printf("key found at the position %d\n",mid+1);
exit(0);
}
else if(strcmp(key,a[mid])>0)
{
high=high;
low=mid+1;
}
else
{
low=low;
high=mid-1;
}
}
printf("name not found\n");
}

Department of CSE, SAIT 29


COMPUTER PROGRAMMING LAB (21CPL17/27)

QUESTIONS FOR VIVA:

1. What is binary search?


2. How to declare an array?
3. What is an array? Give example.
4. Can an array store both integer and float
variables? 5.What are the different types of array?

Department of CSE, SAIT 30


COMPUTER PROGRAMMING LAB (21CPL17/27)

6.IMPLEMENT MATRIX MULTIPLICATION AND VALIDATE THE RULES OF MULTIPLICATION.

ALGORITHM:
Input: Two matrices A and B.
Output: Result of A x B.
1. Start
2. Input 2 matrices A and B and store them in 2D arrays. Display A and B.
3. Check multiplication condition where the number of columns in A is equal to the
number of rows in B. If true, go to step 4. If false, display that matrix multiplication
is not possible.
4. Perform matrix multiplication. Display resultant matrix.
5. Stop

Department of CSE, SAIT 31


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
#include<stdlib.h>
int main()
{
int m, n, p, q, i, j, k, a[10][10], b[10][10];
int c[10][10]={0};
printf("PROGRAM TO IMPLEMENT MATRIX MULTIPLICATION \n");
printf("\n Enter the Order of Matrix 1\
n"); scanf("%d %d", &m, &n); printf("\
nEnter the Order of Matrix 2\n");
scanf("%d %d", &p, &q);
if(n!=p)
{
printf("Matrix Multiplication is not possible\n");
exit(0);
}
printf("Enter the elements of Matrix 1\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
printf("Enter the elements of Matrix 2\n");

Department of CSE, SAIT 32


COMPUTER PROGRAMMING LAB (21CPL17/27)

for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d", &b[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("\n Matrix 1\
n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d \t", a[i][j]);
}
printf("\n");

}
printf("\n");

Department of CSE, SAIT 33


COMPUTER PROGRAMMING LAB (21CPL17/27)

printf("\n Matrix 2\
n"); for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d \t", b[i][j]);
}
printf("\n");
}
printf("\n");
printf("\nThe product of the Matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d \t", c[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}

Department of CSE, SAIT 34


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT:

[root@localhost cpl]# cc matrix.c


[root@localhost ~]# ./a.out

PROGRAM TO IMPLEMENT MATRIX MULIPLICATION

Enter the order of matrix1


23
Enter the order of matrix2
45
matrix multiplication is not possible

*********************************************************
PROGRAM TO IMPLEMENT MATRIX MULIPLICATION

Enter the order of matrix1


23
Enter the order of matrix2
32
Enter the elements of matrix 1
123
456

Department of CSE, SAIT 35


COMPUTER PROGRAMMING LAB (21CPL17/27)

Enter the elements of matrix 2


12
34
56
Matrix 1
123
456
Matrix 2
12
34
56
MATRIX MULTIPLICATION
THE PRODUCT MATRIX IS
22 28
49 64

*********************************************************
PROGRAM TO IMPLEMENT MATRIX MULIPLICATION

Enter the order of matrix1

22
Enter the order of matrix2
22
Enter the elements of matrix 1

Department of CSE, SAIT 36


COMPUTER PROGRAMMING LAB (21CPL17/27)

12
34
Enter the elements of matrix 2
10
01
Matrix 1
12
34
Matrix 2
10
01
The product matrix is
12
34

QUESTIONS FOR VIVA:

1. What is a array? What are the different types of arrays?


2. Consider a 5 x 5 matrix. What will be the index to fetch the element at the 3rd row and 3rd column?
3. What is increment operator?
4. What is decrement operator?
5. What is right to left associativity?

Department of CSE, SAIT 37


COMPUTER PROGRAMMING LAB (21CPL17/27)

7. COMPUTE SIN(X)/COS(X) USING TAYLOR SERIES APPROXIMATION. COMPARE YOUR


RESULT WITH THE BUILT- IN LIBRARY FUNCTION. PRINT BOTH THE RESULTS WITH
APPROPRIATE INFERENCES.

ALGORITHM :
Input: The value of x in degree
Output: To compute Sin(x) using Taylor Series.
1. Start
2. Read the value of Xin defree
3. Compute the value of x in radians: x = (3.1412/180.0) * degree
4. Initialise:
a. Term = x
b. Sum = term
c. i=3
5. Check if the absolute value term is greater than 0.0001. If true goto Step 6 else
goto Step 7.
6. Compute:
Term = ( - term * x * x ) / ( i * (i - 1 ) )
a. Sum = sum + term
b. I = i + 2
7. Display sine using iteration : sum
8. Display sine using library function: sin(x)
9. Stop

Department of CSE, SAIT 38


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
#include<math.h>
#define PI 3.142857
int main()
{
float x,degree,nume,deno,sum,term;
int i;
printf("Enter degree:");
scanf("%f",&degree);
x=degree*(PI/180.0);
sum=0;
nume=x;
deno=1.0;
i=1;
do
{
term=nume/deno;
sum=sum+term;
i=i+2;
nume=-nume*x*x;
deno=deno*i*(i-1);
} while (fabs(term) >= 0.00001);
Department of CSE, SAIT 39
COMPUTER PROGRAMMING LAB (21CPL17/27)

printf ("Computed value of Sin(%f)=%f\n",degree,sum);


printf ("Value from library function is sin(%f) = %f\n",degree,sin(x));
return 0;
}

OUTPUT:

[root@localhost cpl]# cc sin.c -lm


[root@localhost ~]# ./a.out
Enter degree: 60
Computed value of Sin(60.000000)=0.866236
Value from library function is sin (60.000000) = 0.866236

[root@localhost ~]# ./a.out


Enter degree: 30
Computed value of Sin (30.000000)=0.500182
Value from library function is sin (30.000000) = 0.500182

QUESTIONS FOR VIVA:

1. What is # define?
2. What is the syntax of do while?
3. What is fabs?

Department of CSE, SAIT 40


COMPUTER PROGRAMMING LAB (21CPL17/27)

8. SORT THE GIVEN SET OF N NUMBERS USING BUBBLE SORT.


ALGORITHM:
Input: Size of the array and elements to be sorted
Output: List of elements in sorted order
1. Start
2. Read the size of array:a[n]
3. Read the elements of array:n
4. Sort the elements in array using bubble sort
5. Display the elements of array in sorted order:a[n]
6. Read the key to be searched:search_key
7. Initialize:
First=0
Last=n-1
8. Check while first is less than or equal to last.If true goto step 9 else goto step 15
9. Compute:
mid= (first+last)/2
res=cmp (a [mid], search_key)
10. Check if res is equal to zero.If true goto step 11 else goto step 12
11. Display element found at position:mid and goto step 16
12. Check if res is greater than zero.If true goto step 13 else goto step 14
13. Compute:Last=mid-1 goto step 8
14. Compute:First=mid+1 goto step 8
15. Display key not found
16. Stop

Department of CSE, SAIT 41


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
#include<stdlib.h>
int main()
{
int num, i, j, arr[10], temp;
printf("\n Program to implement Bubble Sort\n");
printf("\n Enter number of elements\n");
scanf("%d", &num);
printf("\n Enter the elements\n");
for(i=0;i<num;i++)
scanf("%d", &arr[i]);
for(i=0;i<num;i++)
{
for(j=0;j<num-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
Department of CSE, SAIT 42
COMPUTER PROGRAMMING LAB (21CPL17/27)

}
}
printf("\n The sorted array is\n");
for(i=0;i<num;i++)
printf("%d \t", arr[i]);
printf("\n");
return 0;
}

OUTPUT:

[root@localhost cpl]# cc bubblesort.c


[root@localhost ~]# ./a.out

PROGRAM TO IMPLEMENT BUBBLE SORT


ENTER NO OF ELEMENTS
7
ENTER THE ELEMENTS
2 1 6 5 7
THE SORTED ARRAY IS
1 2 5 6 7

*************************************************

Department of CSE, SAIT 43


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM TO IMPLEMENT BUBBLE SORT


ENTER NO OF ELEMENTS
6
ENTER THE ELEMENTS
9 7 5 3 1 0
THE SORTED ARRAY IS
0 1 3 5 7 9

QUESTIONS FOR VIVA:

1. What is Sorting?

2. What is return ?

3. What is the importance of variable temp?

Department of CSE, SAIT 44


COMPUTER PROGRAMMING LAB (21CPL17/27)

9. WRITE FUNCTIONS TO IMPLEMENT STRING OPERATIONS SUCH AS COMPARE,


CONCATENATE, STRING LENGTH. CONVINCE THE PARAMETER PASSING TECHNIQUES.
ALGORITHM:
a.String length:
1. Start
2. Read the string given by the user
3. To find the length of string, call the function str_length (str)
4. In str_length (str): count the characters in the string one by one until it encounters
null character then goto step 5
5. Display the length of string.
b String Compare:
1. Start
2. Read two strings str1 and str2 given by the user
3. To find comparison between two strings goto step 4
4. Call the function str_compare(str1,str2)
a. Compare ASCII value of a character in string1 with string2,if both value
equals then
goto step 5
b. Check if ASCII value of character in string1 is greater than string2 character
then goto step 6
c. Check if ASCII value of character in string1 is lesser than string2 character
then goto
step 7

Department of CSE, SAIT 45


COMPUTER PROGRAMMING LAB (21CPL17/27)

5. Display both strings are same


6. Display String1 is greater than String2
7. Display String1 is lesser than String2
8. Stop
c. String Concatenation
1. Start
2. Read two strings str1, str2 from user
3. Call the concatenation function str_concat (str1, str2)
a. Find the last character in string1 by checking the null character,then copy each
character in string2 to string1
b. After concatenation of string2 to string1, append null character at the end of

Department of CSE, SAIT 46


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include <stdio.h>
int str_length(char []);
int str_compare(char [], char []);
void str_concat(char [], char []);
int main()
{
char str[50];
char str1[50], str2[50];
char str_des[100], str_src[50];
int length, comp_res; printf("\
nEnter a string :");
scanf("%s",str);
length = str_length(str);
printf("The length of %s is %d\n",str,length);
printf("\nEnter two strings for string compare :");
scanf("%s%s",str1,str2);
comp_res=str_compare(str1,str2);
if (comp_res < 0)
{
printf("String \"%s\" is less than string \"%s\"\n",str1,str2);
}
else if (comp_res == 0)

Department of CSE, SAIT 47


COMPUTER PROGRAMMING LAB (21CPL17/27)

{
printf("String \"%s\" is same as string \"%s\"\n",str1,str2);
}
else
{
printf("String \"%s\" is greater than string \"%s\"\n", str1,str2);
}
printf("\nEnter two strings for string concatenation :");
scanf("%s%s",str_des,str_src);
str_concat(str_des,str_src);
printf("The string after concatenation is \"%s\"\n", str_des);
return 1;
}
int str_length(char s[])
{
int i; for(i=0;s[i]!='\0';i+
+); return i;
}
int str_compare(char s1[], char s2[])
{
int i,j;
for(i=0,j=0;(s1[i] != '\0' && s2[j] != '\0');i++,j++)
{

Department of CSE, SAIT 48


COMPUTER PROGRAMMING LAB (21CPL17/27)

if (s1[i] != s2[j])
{
return (s1[i] - s2[j]);
}
}
if (s1[i] == '\0' && s2[j] == '\0')
{
return 0;
}
else if(s1[i] == '\0' || s2[i] == '\0')
{
return (s1[i] - s2[i]);
}
}
void str_concat(char s1[], char s2[])
{
int i,j;
for(i=0;s1[i] != '\0';i++);
for(j=0;s2[j] != '\0';i++,j++)
{
s1[i] = s2[j];
}
s1[i] = '\0';
}

Department of CSE, SAIT 49


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT
[root@localhost cpl]# cc string.c
[root@localhost ~]# ./a.out
Enter a string: rainbow
The length of rainbow is 7
Enter two strings for string compare:
rain
rainbow
String "rain" is less than string "rainbow"
Enter two strings for string concatenation:
rain
bow
The string after concatenation is rainbow

QUESTIONS FOR VIVA

1. What is string concatenation?


2. How does string compare take place?
3. What is the terminating character while counting string length?
4. What is the length of a string?

Department of CSE, SAIT 50


COMPUTER PROGRAMMING LAB (21CPL17/27)

10. IMPLEMENT STRUCTURES TO READ, WRITE AND COMPUTE AVERAGE MARKS AND
THE STUDENTS SCORING ABOVE AND BELOW THE AVERAGE MARKS FOR A CLASS
OF N STUDENTS.

ALGORITHM :
Input: Student details such as student id, name and marks
Output: To print the details of those students scoring above and below average
1. Start
2. Read the number of students
3. For each student, read the student id, name and marks for all subjects.
4. Calculate the average of the marks and store in the avg field.
5. Print results.
6. Initialise loop
7. Read the average of each student
8. Check if avg>35.00
9. If yes print result else go to next iteration
10. Initialise loop
11. Read average of each student
12. Check if avg<35.00
13. If yes print result else go to next iteration
14. Stop

Department of CSE, SAIT 51


COMPUTER PROGRAMMING LAB (21CPL17/27)

PROGRAM

#include<stdio.h>
int main()
{
struct student
{
int stu_id;
char name[20];
float lang1_marks;
float lang2_marks;
float sc_marks;
float mat_marks;
float sst_marks;
float comp_marks;
float avg;
};
struct student s[20];
int i,n;
printf("Enter the number of records :");
scanf("%d",&n);
printf("Enter %d student details...\n",n);
for(i=0;i<n;i++)
Department of CSE, SAIT 52
COMPUTER PROGRAMMING LAB (21CPL17/27)

{
printf("\n\nEnter student ID :"); // Student ID
scanf("%d",&s[i].stu_id);
printf("Enter student name :"); // Studet Name
scanf("%s",s[i].name);
printf("Enter lang1 Marks:"); // Language 1 marks
scanf("%f",&s[i].lang1_marks);
printf("Enter lang2 Marks :"); // Language 2 Marks
scanf("%f",&s[i].lang2_marks);
printf("Enter science Marks :"); // Science Marks
scanf("%f",&s[i].sc_marks);
printf("Enter Maths Marks :"); // Maths Marks
scanf("%f",&s[i].mat_marks);
printf("Enter SST Marks :"); // SST Marks
scanf("%f",&s[i].sst_marks);
printf("Enter Computer Marks :"); // Computer Marks
scanf("%f",&s[i].comp_marks);
}
for(i=0;i<n;i++)
{
s[i].avg=(s[i].lang1_marks + s[i].lang2_marks + s[i].sc_marks + s[i].mat_marks +
s[i].sst_marks + s[i].comp_marks)/6.0;
}
printf("Students scoring above the average marks....\n");

Department of CSE, SAIT 53


COMPUTER PROGRAMMING LAB (21CPL17/27)

printf("\n\nID\tName\tAverage\n\n");
for(i=0;i<n;i++)
{
if(s[i].avg>=35.0) printf("%d\t%s\t%f\
n",s[i].stu_id,s[i].name,s[i].avg);
}
printf("\n\nStudents scoring below the average marks....\n");
printf("\n\nID\tName\tAverage\n\n");
for(i=0;i<n;i++)
{
if(s[i].avg<35.0) printf("%d\t%s\t%f\
n",s[i].stu_id,s[i].name,s[i].avg);
}
return 0;
}

Department of CSE, SAIT 54


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT
[root@localhost cpl]# cc student.c
[root@localhost ~]# ./a.out

Enter the number of records: 5


Enter 5 student details...
Enter student ID: 101
Enter student name: manjula
Enter lang1 Marks:56
Enter lang2 Marks :54
Enter science Marks :34
Enter Maths Marks :32
Enter SST Marks :45
Enter Computer Marks :67

Enter student ID :102


Enter student name :kavitha
Enter lang1 Marks:90
Enter lang2 Marks :99
Enter science Marks :98
Enter Maths Marks :97
Enter SST Marks :96
Enter Computer Marks :100

Department of CSE, SAIT 55


COMPUTER PROGRAMMING LAB (21CPL17/27)

Enter student ID :103


Enter student name :banu
Enter lang1 Marks:54
Enter lang2 Marks :22
Enter science Marks :1
Enter Maths Marks :12
Enter SST Marks :12
Enter Computer Marks :3
Enter student ID :104
Enter student name :pallavi
Enter lang1 Marks:3
Enter lang2 Marks :44
Enter science Marks :5
Enter Maths Marks :55
Enter SST Marks :53
Enter Computer Marks :21

Enter student ID :105


Enter student name :lalitha
Enter lang1 Marks:54
Enter lang2 Marks :2
Enter science Marks :34
Enter Maths Marks :56

Department of CSE, SAIT 56


COMPUTER PROGRAMMING LAB (21CPL17/27)

Enter SST Marks :78


Enter Computer Marks :9

Students scoring above the average marks....


ID Name Average
101 manjula 48.000000
102 kavitha 96.666664
105 lalitha 38.833332

Students scoring below the average marks....


ID Name Average
103 banu 17.333334
104 pallavi 30.166666

QUESTIONS FOR VIVA

1. What is the size of a structure?


2. What is the difference between array

3. What is the syntax for creating a structure?


4. What is a structure?
5. How do you declare a structure variable?
6. How to access a structure variable?
7. What is typedef?

Department of CSE, SAIT 57


COMPUTER PROGRAMMING LAB (21CPL17/27)

11. DEVELOP A PROGRAM USING POINTERS TO COMPUTE THE SUM, MEAN AND
STANDARD DEVIATION OF ALL ELEMENTS STORED IN AN ARRAY OF N REAL
NUMBERS.

ALGORITHM :
Input:An array of numbers
Output: To compute sum, mean and standard deviation
1. Start
2. Read the value of n
3. Read the numbers into the array ‘a’ using the pointer ‘p’.
4. Initialise: i=0 and sum=0
5. Iterate the loop and perform the following
a. Sum = sum + *p
b. Increment i
6. Display the sum
7. Calculate the mean using the formula mean = sum/n
8. Display mean
9. Initialise i=0 and var=0
10. Iterate the loop and perform the following
var=var+pow((*p-mean),2);
a. Increment i
11. Display the variance
12. Compute. var = var/n
a. Sd = sqrt(var)

Department of CSE, SAIT 58


COMPUTER PROGRAMMING LAB (21CPL17/27)

13. Display sd
14. Stop

PROGRAM

#include<stdio.h>
#include<math.h>
int main(void)
{
int i, num;
float mean=0.0, variance=0.0, sd=0.0, arr[100], sum=0.0;
float *ptr;
ptr=arr;
printf("ENTER THE NUMBER OF VALUES:");
scanf("%d", &num);
printf("ENTER %d VALUE\n", num);
for(i=0;i<num;i++)
{
scanf("%f", ptr+i);
sum+=*(ptr+i);
}
mean=sum/num;

Department of CSE, SAIT 59


COMPUTER PROGRAMMING LAB (21CPL17/27)

for(i=0;i<num;i++)
{

variance+=(ptr[i]-mean)*(ptr[i]-mean);
}
variance/=num;
sd=sqrt(variance);
printf("\n THE VALUES ENTERED ARE");
for(i=0;i<num;i++)
{
printf("\n \t %g", ptr[i]);
}
printf("\n \t MEAN=\t %g \n \t VARIANCE=\t %g \n \t STANDARD DEVIATION=\t %g \n", mean,
variance, sd);
return 0;
}

Department of CSE, SAIT 60


COMPUTER PROGRAMMING LAB (21CPL17/27)

OUTPUT:

[root@localhost cpl]# cc pointers.c -lm


[root@localhost ~]# ./a.out

ENTER THE NUMBER OF VALUES: 4


ENTER 4 VALUES
1.1 2.2 3.3 4.4
THE VALUES ENTERED ARE
1.1 2.2 3.3 4.4
MEAN = 2.7515
VARIANCE = 1.5125
STANDARD DEVIATION = 1.22984

**************************************

ENTER THE NUMBER OF VALUES: 5


ENTER 5 VALUES:
5.345 6.765 7.234 8.675 9.765
THE VALUES ENTERED ARE
5.345 6.765 7.234 8.675 9.765
MEAN = 7.5568 34
VARIANCE = 2.34995
STANDARD DEVIATION = 1.53295

Department of CSE, SAIT 61


COMPUTER PROGRAMMING LAB (21CPL17/27)

QUESTIONS FOR VIVA

1. What is a pointer?
2. How to declare a pointer variable?
3. What is dangling pointer?
4. What is a pointer to pointer?
5. What is pointer to array?
6. What is pass by reference?

Department of CSE, SAIT 62


COMPUTER PROGRAMMING LAB (21CPL17/27)

12. Write a C program to copy a text file to another, read both the input file name and target file name.

PROGRAM

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
char ch;// source_file[20], target_file[20];
FILE *source, *target;
char source_file[]="x1.txt";
char target_file[]="x2.txt";
source = fopen(source_file, "r");
if (source == NULL)
{
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}
target = fopen(target_file, "w");
if (target == NULL)
{
fclose(source);

Department of CSE, SAIT 63


COMPUTER PROGRAMMING LAB (21CPL17/27)

printf("Press any key to exit..");


exit(EXIT_FAILURE);
}

while ((ch = fgetc(source)) != EOF)


fputc(ch, target);
printf("File copied successfully.");
fclose(source);
fclose(target);
return 0;
}

OUTPUT-

sourcefile = x1.txt
targetfile = x2.txt
Output: File copied successfully.

Department of CSE, SAIT 64


COMPUTER PROGRAMMING LAB (21CPL17/27)

VIVA QUESTIONS:

1. What is Files in C and its Uses?


2. How to Read a File?
3. How to write a File?
4. What is Error Handling in files?

Department of CSE, SAIT 65

You might also like