2022schemeupadated CPL Manual
2022schemeupadated CPL Manual
LABORATORY MANUAL
C Programming Laboratory
(Effective from the academic year 2018 -2019)
for
BE: II Semester
LAB MANUAL
C Programming Laboratory
For
II - SEMESTER LAB
PREPARED BY:
FACULTY NAME:
(1) …………………………………………………………………….
(2) …………………………………………………………………….
BRANCH: …………………………………..
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.
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.
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
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
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.
Removal of Comments
Expansion of Macros
Expansion of the included files.
The preprocessed output is stored in the filename.i.
$gedit filename.i
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.
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
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;
}
OUTPUT:
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.
10. Calculate
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)
{
OUTPUT:
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
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
OUTPUT:
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
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
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(" ");
printf("\n");
}
}
OUTPUT :
1
1 2 1
12 3 21
12 3 4 3 2 1
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.
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;
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;
}
OUTPUT:
**********************************************
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)
{
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");
}
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
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");
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");
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;
}
OUTPUT:
*********************************************************
PROGRAM TO IMPLEMENT MATRIX MULIPLICATION
*********************************************************
PROGRAM TO IMPLEMENT MATRIX MULIPLICATION
22
Enter the order of matrix2
22
Enter the elements of matrix 1
12
34
Enter the elements of matrix 2
10
01
Matrix 1
12
34
Matrix 2
10
01
The product matrix is
12
34
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
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",°ree);
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)
OUTPUT:
1. What is # define?
2. What is the syntax of do while?
3. What is fabs?
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:
*************************************************
1. What is Sorting?
2. What is return ?
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)
{
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++)
{
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';
}
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
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
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");
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;
}
OUTPUT
[root@localhost cpl]# cc student.c
[root@localhost ~]# ./a.out
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)
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;
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;
}
OUTPUT:
**************************************
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?
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>
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);
OUTPUT-
sourcefile = x1.txt
targetfile = x2.txt
Output: File copied successfully.
VIVA QUESTIONS: