0% found this document useful (0 votes)
35 views55 pages

CPL - Bpops103

Uploaded by

pranavarun26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views55 pages

CPL - Bpops103

Uploaded by

pranavarun26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

KSSEM Dept.

Of CS & BS BPOPS103/203

VIVESVARAYA TECHNOLOGICAL UNIVERSITY

BELAGAVI – 590018

PRINCIPLES OF PROGRAMMING USING C

[ BPOPS103/203 ]

DEPARTMENT OF COMPUTER SCIENCE & BUSINESS SYSTEMS

Kammavari Sangham ® 1952

K. S. GROUP OF INSTITUTIONS

K. S. SCHOOL OF ENGINEERING & MANAGEMENT

( Approved by AICTE, New Delhi ; Affiliated to VTU, Belagavi, Karnataka ; Accredited by NAAC )

www.kssem.edu.in

Mrs. Jayashree. L. K Mr. Prasant Koparde

( Associate Professor ) ( Assistant Professor )

1
KSSEM Dept. Of CS & BS BPOPS103/203

LAB MANUAL (2023 – 24 )


C Programming Laboratory manual
BPOP103/203

Program 1

Simulation of simple calculator.

Problem Description

The problem is to simulate a commercial calculator with arithmetic operations such as addition,
subtraction, multiplication and division of two floating point numbers.

While performing division if the denominator is 0 then division cannot be performed.

Algorithm : Simple calculator

Step 1: Start

Step 2: Read 2 numbers as a and b

Step 3: Read operator (+ or – or * or /) as operator

Step 4: If operator is + then display a + b goto step 9

Step 5: If operator is - then display a – b goto step 9

Step 6: If operator is * then display a * b goto step 9

Step 7 : If operator is / then

I. check if b is not equal to zero then display a / b


II. Otherwise display “Can Can not divide by 0”

goto step

Step 9: else display “Wrong operation” 10

Step 9: Stop

2
KSSEM Dept. Of CS & BS BPOPS103/203

Flowchart

3
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to simulate calculator
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
char op;
float a,b,c;
printf("Enter two numbers \n");
scanf("%f%f",&a,&b);
printf("Enter the operator :");
scanf(" %c",&op);
switch(op)
{
case '+' : c = a + b; /* compute addition */
printf("%f + %f = %f\n", a, b,c);
break;
case '-' : c = a - b; /* compute addition */
printf("%f - %f = %f\n", a, b,c);
break;
case '*' : c = a * b; /* compute addition */
printf("%f * %f = %f\n", a, b,c);
break;

case '/' : if(b!=0)


{
c = a / b; /* compute addition */
printf("%f / %f = %f\n", a, b,c);
}

4
KSSEM Dept. Of CS & BS BPOPS103/203

else
{
printf("Expression is not valid\n");
}
break;
default : printf("Enter valid operator\n");

}
}
Run 1

./a.out

Enter two numbers

3.0 4.0

Enter the operator ( + or – or * or /) : +

3.000000 + 4.000000 = 7.000000

Run 2

./a.out

Enter two numbers

5.0 2.0

Enter the operator ( + or – or * or /) : -

5.000000 - 2.000000 = 3.000000

Run 3

./a.out

Enter two numbers

-5.0 9.0

5
KSSEM Dept. Of CS & BS BPOPS103/203

Enter the operator ( + or – or * or /) : *

-5.000000 * 9.000000 = -45.000000

Run 4

./a.out

Enter two numbers

4.0 6.0

Enter the operator ( + or – or * or /) : /

4.000000 / 6.000000 = 0.666667

Run 5

./a.out

Enter two numbers

4.0 0.0

Enter the operator ( + or – or * or /) : /

Division by 0 is not valid

Run 6

./a.out

Enter two numbers

5.0 6.0

Enter the operator ( + or – or * or /) : >

Enter valid operator.

Conclusion

Program for simple calculator is implemented and tested.

6
KSSEM Dept. Of CS & BS BPOPS103/203

Program 2

Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate
messages.

Problem Description

The problem is to find roots of a quadratic equation for given co-efficient.

Quadratic equation is equation of degree 2. The standard form of quadratic equation is

𝑎𝑥 2 + 𝑏𝑥 + 𝑐 where a, b and c are co-efficient, a cannot be 0, 𝐷 = 𝑏2 − 4𝑎𝑐 is known as


discriminant of a quadratic equation.

−𝑏
• If D = 0 then roots are real and equal𝑥 = 𝑎
.
−𝑏±√𝐷
• If D > 0 then roots are real and distinct. 𝑥 = 2𝑎

• If D < 0 then roots are imaginary 𝑥 = −𝑏 ± 𝑖 √𝐷∨


2𝑎

Algorithm: [Roots of A Quadratic Equation]

Step 1: Start the program

Step 2: Declare the required variables

(The variables named as a, b, c, r, disc, x1, and x2)

Step 3: Read the co-efficient as a, b, c

Step 4: If a, b, c is equal to 0 goto stop 9 otherwise goto next step

Step 5: Compute the discriminant

(disc=(b*b)-(4*a*c) and r=sqrt(fabs(disc)))

Step 6: If discriminant is equal to zero, Display the Roots are Real and

7
KSSEM Dept. Of CS & BS BPOPS103/203

Equal. Compute the roots of quadratic equation and display, otherwise goto next step
(x1=x2= -b/(a*2.0))

Step 7: If discriminant is greater than zero. Display the Roots are Real and Distinct

and Compute the roots of quadratic equation and display, otherwise goto next step

(x1=(-b+r)/(a*2.0)) and x2= (-b-r)/(a*2.0))

Step 8: If discriminant is lesser than zero, Display the Roots are Imaginary. Compute

the roots of quadratic equation and display, otherwise goto next step

(x1=(-b)/(a*2.0)+ir/(a*2.0) and x2= (-b)/(a*2.0)-ir/(a*2.0))

Step 9: Stop

Flowchart

8
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to find roots of quadratic equation
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

9
KSSEM Dept. Of CS & BS BPOPS103/203

void main()
{
float a,b,c,x1,x2,disc,rp,ip;
printf("Enter the co-efficients\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0||b==0||c==0)
{
printf("Quadratic equation is not possible\n");
exit(0);
}
disc = b*b - 4*a*c;
if(disc == 0)
{
x1 = x2 = -b/(2*a);
printf("The roots are equal\n");
printf("x1=%f\nx2=%f\n",x1,x2);
}
else if(disc > 0)
{
x1 = (-b+sqrt(disc))/(2*a);
x2 = (-b-sqrt(disc))/(2*a);
printf("The roots are real and distinct\n");
printf("x1=%f\n x2= %f\n",x1,x2);
}
else
{
rp = -b/(2*a);
ip = sqrt(fabs(disc))/(2*a);
printf("The roots are complex\n");
printf("First root = %f + i %f\n",rp,ip);
printf("Second root = %f - i %f\n",rp,ip);

10
KSSEM Dept. Of CS & BS BPOPS103/203

}
}

Compilation

gcc quadratic.c –lm

Execution

Run1 :

./a.out

Enter the co-efficient a, b, c

121

The roots are equal

x1 = -1.000000

x2 = -1.000000

Run2 :

./a.out

Enter the co-efficient a, b, c

142

The roots are real and distinct

x1 = -0.585786

x2 = -3.414214

Run3 :

./a.out

Enter the co-efficient a, b, c

11
KSSEM Dept. Of CS & BS BPOPS103/203

123

The roots are complex

First root = -1.000000 + i 1.414214

Second root = -1.000000 - i 1.414214

Run4 :

./a.out

Enter the co-efficient a, b, c

034

a can not be 0

Conclusion

Program to compute roots of a quadratic equation is implemented and tested.

Program 3

An electricity board charges the following rates for the use of electricity: for the first 200 units 80
paisa per unit: for the next 100 units 90 paisa 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 than Rs 400, then

12
KSSEM Dept. Of CS & BS BPOPS103/203

an additional surcharge of 15% of total amount is charged. Write a program to read the name of
the user, number of units consumed and print out the charges.

Problem description – As stated in problem a program is to be written to accept name of user,


number of units consumed. Depending on number of units consumed the electricity charges need
to be calculated.

Algorithm: [Electricity Bill]

Step 1: Start
Step 2: Declare the required variables
Step 3: Read customer name, units consumed as units
Step 4: metercharge = 100, charge = metercharge
Step 5: if units is less than or equal to 100 then compute charge and goto step 8 otherwise
goto next step
charge = charge + units * 0.8
Step 6: If units is greater than 200 and less than or equal to 300 then compute charge
and goto step 8 otherwise goto next step
charge = charge + 200 * 0.8 +(units – 200) * 0.9
Step 7: charge = charge + 200 * 0.8 + 100 * 0.9 + (units – 300) * 1
Step 8: If charge is greater than 400 add 15% of charge otherwise goto next step
charge = charge + (0.15*charge)
Step 9: Display Customer name, units, charge
Step 10: Stop
Flowchart

13
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to calculate electricity charges based on number of units consumed.
*/

#include<stdio.h>
void main()
{
int units;
float charges;
char name[20];
printf("Enter the name of customer\n");
scanf("%s",name);
printf("Enter the number of units consumed\n");
scanf("%d",&units);
charges = 100;
if(units > 0 && units <= 200)

14
KSSEM Dept. Of CS & BS BPOPS103/203

charges = charges + 0.8 * units;


else if(units > 200 && units <= 300)
charges += (units - 200)*0.9 + 0.8 * 200 ;
else
charges += (units - 300)*1 + 0.9 * 100 + 0.8 * 200 ;
if(charges > 400)
charges = charges + charges * 0.15;
printf("Name of the customer: %s\n",name);
printf("Number of units consumed: %d\n",units);
printf("Total charge to be paid: %f\n",charges);

Compilation

cc electricity_bill.c

Execution

Run1 :

./a.out

Enter the name of customer

Veena

Enter the number of units consumed

156

Name of the customer: Veena

Number of units consumed: 156

Total charge to be paid: 224.800003

Run2 :

./a.out

Enter the name of customer

Vindya

15
KSSEM Dept. Of CS & BS BPOPS103/203

Enter the number of units consumed

256

Name of the customer: Vindya

Number of units consumed: 256

Total charge to be paid: 310.399994

Run3 :

./a.out

Enter the name of customer

Yeshas

Enter the number of units consumed

301

Name of the customer: Yeshas

Number of units consumed: 310

Total charge to be paid: 351.000000

Run4 :

./a.out

Enter the name of customer

Gopal

Enter the number of units consumed

399

Name of the customer: Gopal

Number of units consumed: 399

Total charge to be paid: 516.349976

16
KSSEM Dept. Of CS & BS BPOPS103/203

Observation and Discussion

Incrementing a variable c by 100 can be done as, c = c + 100 or c+=100

Conclusion

Program to calculate electricity charges based on units consumed is implemented and tested.

Program 5

Implement Binary search on integers.

Problem description:

Problem is to search for an element from a sorted list. Binary Search algorithm requires elements
to be arranged in either ascending or descending order.

Algorithm: [ Binary Search ]

Step 1: Start
Step 2: Declare the required variables
Step 3: Read number of elements as n
Step 4: Read n elements arranged in ascending order as a[0]..a[n-1]
Step 5: Read element to be searched as k
Step 6: Initialize variables ]
low = 0, high = n - 1
Step 7: while low is less than high repeat step 8 to 11 else goto step 12
Step 8: Compute mid
mid = (low + high)/2
Step 9: If element at a[mid] = k then goto step 13 else goto next step
Step 10: If element at a[mid] > k then compute high else goto next step
high = mid – 1
Step 11: If element at a[mid] < k then compute low
low = mid + 1
Step 12: Display Unsuccessful search goto step 14

17
KSSEM Dept. Of CS & BS BPOPS103/203

Step 13: Display Successful Search


Step 14: Stop

Flowchart

Program

/*
Program to implement Binary Search

18
KSSEM Dept. Of CS & BS BPOPS103/203

*/
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[20],low,mid,high,i,n,k;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("Enter the element to be searched\n");
scanf("%d",&k);
low = 0;
high = n - 1;
while(low <= high)
{
mid = (low + high)/2;
if(a[mid] == k)
{
printf("Successful search, element %d found at %d\n",k,mid+1);
exit(0);
}
else if(a[mid] > k)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
printf("Unsuucessful search\n");

Compilation

cc binarysearch.c

Execution

Run 1 :

./a.out

19
KSSEM Dept. Of CS & BS BPOPS103/203

Enter the number of elements

Enter the elements in ascending order

10 20 30 40 45

Enter the element to be searched

10

Successful search, element 10 found at 1

Run 2 :

./a.out

Enter the number of elements

Enter the elements in ascending order

234

Enter the element to be searched

Unsuccessful search

Observation and Discussion

Binary search works only if the elements are sorted.

Conclusion

Binary search program is implemented and tested.

Program 6

Implement matrix multiplication and validate the rules of multiplication

20
KSSEM Dept. Of CS & BS BPOPS103/203

Problem Description

Problem is to multiply matrices which are stored as 2D array.

An array of arrays is known as 2D array. It is also known as matrix which can be represented as
a table of rows and columns.

Matrix multiplication

1. Check if number of columns in the first matrix is equal to number of rows in the second
matrix.
2. Multiply the elements of each row of the first matrix by the elements of each column in
the second matrix.
3. Add the products.

Algorithm: [Solution For Multiplying Two Matrices]

Step 1: Start

Step 2: Declare the required variables

Step 3: Read order of A matrix (M x N) and order of B Matrix (P x Q)

Step 4: Compare is first matrix columns equal to second matrix rows if equal goto next step

otherwise exit from the program

Step 5: Read the A matrix (MxN) elements

Step 6: Read the B matrix (PxQ) elements

Step 7: Compute multiplication

for i 0 to m-1 in steps of 1 do

for j 0 through q-1 in steps of 1 do

c[i][j] = 0

for k 0 through n-1 in steps of 1 do

21
KSSEM Dept. Of CS & BS BPOPS103/203

c[i][j] = c[i][j] + a[i][k]*b[k][j]

end kth loop

end jth loop

end ith loop

Step 8: Display matrix a, b, c

Step 9: Stop

Flowchart

Program

22
KSSEM Dept. Of CS & BS BPOPS103/203

/*
Multiply two matricies
*/
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf("Enter the order of matrix A\n");
scanf("%d%d",&m,&n);
printf("Enter the order of matrix B\n");
scanf("%d%d",&p,&q);

if(n!=p)
{
printf("Matrix multiplication is not possible\n");
exit(0);
}
printf("Enter the elements of matrix A\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < n; j++)
{
scanf("%d",&a[i][j]);
}

}
printf("Enter the elements of matrix B\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++)
{
c[i][j] = 0;
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}

23
KSSEM Dept. Of CS & BS BPOPS103/203

}
printf("Matrix A is\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < n; j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");

}
printf("Matrix B is\n");

for(i = 0 ; i < p; i++)


{
for(j = 0 ; j < q; j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The Product od two Matrix is\n");

for(i = 0 ; i < m; i++)


{
for(j = 0 ; j < q; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}

Compilation

cc matrix.c

Execution

Run 1:

24
KSSEM Dept. Of CS & BS BPOPS103/203

./a.out

Enter the order of matrix A

22

Enter the order of matrix B

34

Matrix multiplication is not possible

Run 2:

./a.out

Enter the order of matrix A

22

Enter the order of matrix B

22

Enter the elements of matrix A

12

34

Enter the elements of matrix B

12

34

Matrix A is

12

34

Matrix B is

12

25
KSSEM Dept. Of CS & BS BPOPS103/203

34

The product of two matrix is

7 10

15 22

Observation and Discussion

If we do not include & symbol in scanf function, then we get segmentation fault (core dumped)
error during execution.

Conclusion

Program for matrix multiplication is implemented and tested.

Program 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 interferences.

Problem description:

The problem is to find the value of Sin(x) function using Taylor series.

Sin(θ) can be defined as follows:

𝑂𝑝𝑝𝑜𝑠𝑖𝑡𝑒
𝑠𝑖𝑛(𝜃) = 𝐻𝑦𝑝𝑜𝑡𝑒𝑛𝑢𝑠𝑒

To convert degree to radian use

𝑑𝑒𝑔𝑟𝑒𝑒∗𝜋
𝑟𝑎𝑑𝑖𝑎𝑛 = 180

Taylor series for Sin x is

26
KSSEM Dept. Of CS & BS BPOPS103/203

𝑥3 𝑥5 𝑥7
𝑠𝑖𝑛𝑥 = 𝑥 − + − ±⋯
3! 5! 7!

Where x is in radians, ! symbol denote factorial of a number.

𝑛! = 𝑛 ∗ (𝑛 − 1) ∗ (𝑛 − 2) ∗ … … ∗ 1

Algorithm: [Sin x]

Step 1: Start
Step 2: Declare the required variables
Step 3: Read the angle as degree
Step 4: Initialize variables
x = (degree * π )/180.0, num = x, den = 1, i = 2, term = num/den
Step 5: while absolute value of term is greater than 0.00001 repeat step 6 else goto step 7
Step 6: Compute the following
term = num/den
num = -num * x *x
den = den * i * (i+1)
sum = sum + term
i=i+2
Step 7: Display sum
Step 8: Stop
Flowchart

27
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to find sine value using Taylor series
*/

#include<stdio.h>
#include<math.h>
void main()
{
float degree,num,den,x,sum=0,term;
int i;

28
KSSEM Dept. Of CS & BS BPOPS103/203

printf("Enter the degree");


scanf("%f",&degree);
x = (degree * 3.14)/180.0;
num = x;
den = 1;
i = 2;
do
{
term = num/den;
num = -num * x * x;
den = den * i * (i + 1);
sum = sum + term;
i = i + 2;
}while(fabs(term) >= 0.00001);
printf("sin(%f)=%f without using built in function\n",degree,sum);
printf("sin(%f)=%f using built in function\n",degree,sin(x));

Compilation

cc taylor.c -lm

Execution

Run1 :

./a.out

Enter the angle in degrees

30

Sin(30.000000) = 0.499770 without using built in function.

Sin(30.000000) = 0.499770 using built in function.

Run2 :

./a.out

Enter the angle in degrees

45

29
KSSEM Dept. Of CS & BS BPOPS103/203

Sin(45.000000) = 0.706825 without using built in function.

Sin(45.000000) = 0. 706825 using built in function.

Observation and Discussion

If function

ns from math library are used in program then compilation process should also include linking
math library files.

Conclusion

Program to calculate sin(x) using Taylor series is implemented and tested.

Program 9

Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques.

Problem description

Problem is to implement string operations such as compare, concatenate and length.

Strings in c is represented as array of characters. The end of a string is recognized by a null (‘\0’)
character.

Counting all characters in a string until a null character gives the length of string.

Concatenation of two strings is appending the second string to the end of first string.

String comparison can be achieved by comparing character of one string with character of other
string.

Algorithm : [ String operations ]

Step 1: Start the program

Step 2: Declare the required variables

Step 3: Read choice 1 – String compare, 2 – String length, 3 – String concatenate, 4 - Exit

Step 4: if choice is equal to 1 goto next step else goto step 7

Step 5: Read two strings as str1 and str2

30
KSSEM Dept. Of CS & BS BPOPS103/203

Step 6: call function to compare two strings, if function returns 0 display identical strings

else display non identical strings and goto step 13

c = compare(str1,str2)

Step 7: if choice is equal to 2 goto next step else goto step 10

Step 8: Read string as str

Step 9: call function to find string length, display string length and goto step 13

len = length(str)

Step 10: if choice is equal to 3 goto next step else goto step 13

Step 11: Read two strings as str1 and str2

Step 12: Call function to concatenate two strings, display concatenated string and goto step 13

str = concatenate(str1,str2)

Step 13: Stop the program

Algorithm : [ String compare ]

Step 1: Compare strings character by character

i=0

while str1[i] == str2[i] do

if str1[i] == ‘\0’ or str2[i] == ‘\0’ break

i=i+1

return str1[i] – str2[i]

Algorithm : [ String length ]

Step 1: Count the characters from starting character till null character

i=0

while str [i] != ‘\0’ do

31
KSSEM Dept. Of CS & BS BPOPS103/203

i=i+1

return i

Algorithm : [ String concatenate ]

Step 1: append characters of str2 to the end of str1

i = 0, j = 0

while str1[i] != ‘\0’ do

i=i+1

while str2[i] != ‘\0’ do

str1[i] = str2[j]

i=i+1

j=j+1

str1[i] = ‘\0’

return str1

Flowchart

32
KSSEM Dept. Of CS & BS BPOPS103/203

33
KSSEM Dept. Of CS & BS BPOPS103/203

Program

#include<stdio.h>
#include<stdlib.h>
int length(char str[]);
int compare(char str1[],char str2[]);
void concatenate(char str1[],char str2[]);
void main()
{
char str1[30],str2[30];
int choice,a;
printf("Enter 1 - String Comparision\n");
printf("Enter 2 - String Length\n");
printf("Enter 3 - String Conctenation\n");
printf("Enter 4 - Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter String 1 :");
scanf("%s",str1);

34
KSSEM Dept. Of CS & BS BPOPS103/203

printf("Enter String 2 :");


scanf("%s",str2);
a = compare(str1,str2);
if(a == 0)
{
printf("%s and %s are equal\n",str1,str2);
}
else
{
printf("%s and %s are not equal\n ",str1,str2);

}
break;
case 2: printf("Enter String :");
scanf("%s",str1);
a = length(str1);
printf("Length of %s = %d\n",str1,a);

break;
case 3: printf("Enter String 1 :");
scanf("%s",str1);
printf("Enter String 2 :");
scanf("%s",str2);
concatenate(str1,str2);
break;

case 4: exit(0);
break;
default : printf("Enter proper choice\n");
exit(0);
}
}
int length(char str[])
{

int i = 0;
while(str[i] !='\0')
{

i++;
}
return i;
}
int compare(char str1[],char str2[])
{
int i = 0;

35
KSSEM Dept. Of CS & BS BPOPS103/203

while(str1[i] == str2[i])
{
if(str1[i] == '\0' || str2[i] == '\0')
break;
i++;
}
return str1[i] - str2[i];
}
void concatenate(char str1[] ,char str2[])
{
int i = 0, j = 0;
while(str1[i] !='\0')
{
i++;
}
while(str2[j] !='\0')
{
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
printf("Concatenated string is %s \n",str1);
}
Compilation

cc string.c

Execution

Run1:

./a.out

Enter 1 – String comparison

Enter 2 – String length

Enter 3 – String concatenation

Enter 4 – Exit

Enter String 1: Veena

36
KSSEM Dept. Of CS & BS BPOPS103/203

Enter String 2: Gopal

Veena and Gopal are not equal

Run2:

./a.out

Enter 1 – String comparison

Enter 2 – String length

Enter 3 – String concatenation

Enter 4 – Exit

Enter String 1: KSSEM

Enter String 2: KSSEM

KSSEM and KSSEM are identical

Run3:

./a.out

Enter 1 – String comparison

Enter 2 – String length

Enter 3 – String concatenation

Enter 4 – Exit

Enter String : Institute

Length of Institute = 9

Run4:

./a.out

37
KSSEM Dept. Of CS & BS BPOPS103/203

Enter 1 – String comparison

Enter 2 – String length

Enter 3 – String concatenation

Enter 4 – Exit

Enter String 1: KSS

Enter String 2: EM

Concatenated string is KSSEM

Run5:

./a.out

Enter 1 – String comparison

Enter 2 – String length

Enter 3 – String concatenation

Enter 4 – Exit

Observation and discussion

In C if a function needs to return an array variable, then pointers or struct can be used, directly
arrays cannot be returned.

Printing a string, if %d is used instead of %s “Segmentation fault core dumped” error occurs.

Conclusion

Program to compare strings, finding length of a string and concatenation of strings are
implemented and tested

Program 08

38
KSSEM Dept. Of CS & BS BPOPS103/203

Sort the given set of N numbers using Bubble sort.

Problem description

Problem is to sort a set of N numbers using Bubble sort.

Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are not in order.

Algorithm: [ Bubble Sort ]

Step 1: Start

Step 2: Declare the required variables

Step 3: Read the n value

Step 4: Read the n number of values in random order

Step 5: Compare the first two numbers, if first no is greater than second number, exchange the

numbers and compare second number and third number, if second number is greater than

third number exchange the numbers, this process continues until the n-1 elements

Step 6: Repeat step 5 until the (n-1) times

Step 7: Display the sorted array elements

Step 8: Stop

Flowchart

39
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to implement bubble sort
*/
#include<stdio.h>

void main()
{
int a[20],i,j,temp,n;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("\nThe array before sorting\n");
for(i = 0 ; i < n ; i++)
printf("%d\t",a[i]);

for(i = 0 ; i < n-1 ; i++)


{
for(j = 0 ; j < n-i-1 ; j++)

40
KSSEM Dept. Of CS & BS BPOPS103/203

{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}

}
printf("\nThe array after sorting\n");
for(i = 0 ; i < n ; i++)
printf("%d\t",a[i]);

Compilation

cc bubble.c

Execution

Run1 :

./a.out

Enter the number of elements

Enter the elements

54321

The array before sorting

54321

The array after sorting

12345

Run2 :

./a.out

41
KSSEM Dept. Of CS & BS BPOPS103/203

Enter the number of elements

Enter the elements

673

The array before sorting

673

The array after sorting

367

Observation and discussion

Semicolon should not be included at the end of for statement if some operations are done in body
of for loop.

Conclusion

Bubble sort program is implemented and tested.

Program 10

Implement structure to read, write and compute average marks and the students scoring above and
below the average marks for a class of N students.

Problem description

Problem is to read, write and compute average marks of students using structures.

A structure is a user defined data type in C/C++. A structure creates a data type that can be used
to group items of possibly different types into a single type.

Algorithm : [ Student average ]

Step 1: Start

Step 2: Declare the required variables

Step 3: Read number of students as n

42
KSSEM Dept. Of CS & BS BPOPS103/203

Step 4: for each student read the name, usn and marks and store it in structure stud

stud.name = name

stud.usn = usn

stud.marks = marks

Step 5: compute the average

for i = 0 through n-1 do

total = total + stud[i].marks

avg = total/n

Step 6: display students and below average

for i = 0 through n-1 do

if(stud[i].marks > avg)

abooveavg[j] = i

j++

else

belowavg[j] = i

j++

Step 7: display students with above average and below average

Step 8:Stop

Flowchart

43
KSSEM Dept. Of CS & BS BPOPS103/203

Program

/*
Program to store student details
*/
#include<stdio.h>
struct student
{
char name[20];
char usn[10];
float marks;

44
KSSEM Dept. Of CS & BS BPOPS103/203

};
main()
{
int i,j,k,m,n,aboveavg[10],belowavg[10];
float N,T=0,AVG=0;
struct student s[10];
printf("Enter number of students.\n");
scanf("%d",&n);
N=(float)n;
printf("Enter the details of students.\n");
for (i=0;i<n;i++)
{
printf("Enter the details of student %d \n",i+1);
printf("Enter name \n");
scanf("%s",s[i].name);
printf("Enter USN \n");
scanf("%s",s[i].usn);
printf("Enter marks \n");
scanf("%f",&s[i].marks);
T = T + s[i].marks;
}
printf("Details of Students.\n");
printf("Name\t\t USN\t\t Marks\n");
for (i=0;i<n;i++)
printf("%s\t\t%s\t\t%f\n",s[i].name,s[i].usn,s[i].marks);
AVG=T/N;
printf("AVG = %f \n",AVG);
j=0;
k=0;
for (i=0;i<n;i++)
{

45
KSSEM Dept. Of CS & BS BPOPS103/203

if (s[i].marks > AVG)


{
aboveavg[j]=i;
j++;
}
else
{
belowavg[k]=i;
k++;
}
}
printf("Students scoring above avg. \n");
for (i=0;i<j;i++)
{
printf("%s %f\n",s[aboveavg[i]].name,s[aboveavg[i]].marks);
}
printf("Students scoring below avg. \n");
for (i=0;i<k;i++)
{
printf("%s %f\n",s[belowavg[i]].name,s[belowavg[i]].marks);
}
}

Compilation

cc student.c

Execuation

Run1:

./a.out

46
KSSEM Dept. Of CS & BS BPOPS103/203

Enter number of students:

Enter the student details

Enter the details of student 1

Enter name

Veena

Enter usn

1VI14CS01

Enter Marks

14

Enter the details of Student 2

Enter name

Vinay

Enter usn

1VI14CS05

Enter marks

16

Enter the details of Student 3

Enter name

Naveen

Enter usn

1VI14CS06

Enter marks

47
KSSEM Dept. Of CS & BS BPOPS103/203

16

Details of students

Name USN Marks

Veena 1VI14CS01 14

Vinay 1VI14CS05 16

Naveen 1VI14CS06 16

Students scoring above average.

Vinay 16.000000

Naveen 16.000000

Students scoring below average.

Veena 14.000000

Observation and discussion

Derived data types like structures can be used to store heterogeneous data.

Conclusion

Program for displaying student details is implemented and executed.

Program 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.

Problem description

Problem is to compute sum, mean and standard deviation of all elements in an array.

A pointer is an address. It is a derived data type that stores the memory address. A pointer can also
be used to refer another pointer, function. A pointer can be incremented/ decremented, i.e., to point
to the next/ previous memory location.

The formula for standard deviation is

48
KSSEM Dept. Of CS & BS BPOPS103/203

Where µ is mean value of all N elements.

Algorithm : [ Standard deviation ]

Step 1: Start the program

Step 2: Declare the required variables

Step 3: Read number of elements as n

Step 4: Read array elements

For i = 0 to n

Read a[i]

Step 5: Compute sum

For i = 0 to n

sum = sum + *ptr

increment ptr by 1

Step 6: Compute mean

mean = sum/n

Step 7: Compute standard deviation

ptr = a

sumstd=sumstd + pow((*ptr - mean),2);

increment ptr by 1

std = sqrt(sumstd/n)

Step 8: Display sum, mean, standard deviation

49
KSSEM Dept. Of CS & BS BPOPS103/203

Step 9: Stop the program

Flowchart

Program

#include <stdio.h>
#include <math.h>

void main()
{
float a[10], *ptr, mean, sum=0, std,sumstd=0;
int n,i;

50
KSSEM Dept. Of CS & BS BPOPS103/203

printf("Enter the number of elements : ");


scanf("%d",&n);
printf("Enter the array elements :\n");
for( i=0; i<n; i++)
scanf("%f",&a[i]);
//assigning address of a to pointer ptr
ptr = a;
//compute the sum
for(i=0;i<n;i++)
{
sum += *ptr;
ptr++;
}
//compute the mean
mean = sum/n;
//compute standard deviation
ptr = a;
for(i=0; i<n; i++)
{
sumstd = sumstd + pow((*ptr-mean),2);
ptr++;
}
std = sqrt(sumstd/n);
//print sum, mean, & standard deviation
printf("Sum = %f\n",sum);
printf("Mean = %f\n",mean);
printf("Standard Deviation : %f\n",std);
}

Compilation

51
KSSEM Dept. Of CS & BS BPOPS103/203

cc stddeviation.c -lm

Execution

Run1:

./a.out

Enter the number of elements: 5

Enter the array elements:

12345

Sum = 15.000000

Mean = 3.000000

Standard deviation = 1.414214

Enter the number of elements: 7

Enter the array elements:

6 4 2 8 10 12 14

Sum = 56.000000

Mean = 8.000000

Standard deviation = 4.000000

52
KSSEM Dept. Of CS & BS BPOPS103/203

Program 04 :

Write a C program to display the following by reading the number of rows as input :

1 2 1

1 2 3 2 1

Code :

53
KSSEM Dept. Of CS & BS BPOPS103/203

Program 12 :

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

54
KSSEM Dept. Of CS & BS BPOPS103/203

Code :

55

You might also like