You are on page 1of 51

LABORATORY MANUAL

“Principles of Programming using C-BPOPS203”


Semester: II
Scheme: CBCS

Prepared By

Prof. A.Rosline Mary


Prof.A.Menaka
Dept of CSE
Algorithm:

• An algorithm is a basic tool which is used to express the solution for a given problem
systematically in the form of instructions. This solution is called logic. It takes a set of input
values and produces the desired output.

• An algorithm is defined as unambiguous, step by step procedure (instructions) to solve a given


problem in finite number of steps by accepting a set of inputs and producing the desiredoutput.
After producing the result, the algorithm should terminate. Usually, Algorithm are
Written in simple English like statements along with simple mathematical expressions.

Characteristics of an Algorithm:

• Input: It may accept a zero or more inputs.

• Output: It should produce at least one output (result).

• Definiteness: Each instruction must be clear, well defined and precise. There should not be any
ambiguity.

• Finiteness: It should be a sequence of finite instructions. That is, it should end after a fixed
time. It should not enter into an infinite loop.

• Effectiveness: This means that operations must be simple and are carried out in a finite time
at one or more levels of complexity. It should be effective whenever traced manually for the
results.

Algorithmic Notations:

• Name of the Algorithm

• Step number

• Explanatory Comment

• Termination
Flowchart:

• A flow chart is a pictorial representation of an algorithm. That is flowchart consists of


sequence of instructions that are carried out in an algorithm. All the steps are drawn form of
different shapes of boxes, circle and connecting arrows. Flowcharts are mainly used to help
programmer to understand the logic of the program.

• The various types of geometric shapes, arrows and symbols used while drawing the flowchart
are called flowchart symbols. The symbols used and the meaning associated with each symbol
are shown below.

Symbols used Meaning associated with symbols

Start or end of the flowchart (program)

Input or output operation

Decision making and branching

Connector

Predefined computation or process (used with


functions are used)

Repetition or a loop which is normally used to


execute a group of instructions for a specifies
number of times

Flow of control
Familiarization with programming environment, concept of naming the program
files, storing, compilation, execution and debugging. Taking any simple C- code.
Algorithm Flowchart

Step 1. [Initialize] Start

Step 2. [Input the length and breadth] Read l, b

Step 3. [Calculate area] area = l * b

Step 4. [Calculate perimeter] peri= 2(l+b)

Step 5. [Display area and perimeter] Print area,

peri

Step 6. [Finished] Stop.

Program Output
#include<stdio.h> Enter length and breadth
{
2
int l, b, area, peri;
printf(“Enter length and breadth\n”); 4
scanf(“%d%d”, &l, &b);
The area is 8
area = l * b;
peri = 2 * (l + b); The perimeter is 12
printf(“The area is %d\n”, area);
printf(“The perimeter is %d\n”, peri);
}

Linux machine, you have to follow the steps mentioned below:


• Go to the Linux command prompt (# or $).
• Type gcc program1.c
• The gcc editor will open.
• Type the program in the editor.
• To compile a program, At the command prompt type cc filename.c
• Type ./a.out to run the program.
Program 1: simulation of a simple calculator.

Algorithm: SIMPLE CALCULATOR


Step 1: Start
Step 2: Read the values of a and b.
Step 3: Read Ch
Step4: Verify ch value by using switch statement if ch=1 then goto step 5 or if ch=2 then goto step
6 or if read ch is 3 then goto step 7 or if read ch is 4 then goto step 8 or if read ch is 5 then
goto step 9 or otherwise goto step 10.
Step 5: if ch=1 then compute res=a+b and goto step 11.
Step 6: if ch=2 then compute res=a-b and goto step 11.
Step 7: if ch=3 then compute res=a*b and goto step 11.
Step 8: if ch=4 then compute res=a/b and goto step 11.
Step 9: if ch=5 then compute res=a%b and goto step 11.
Step 10: if ch value is other than above options then print wrong choice entered
then goto step 12.
Step 11: Print res and goto step 12
Step 12: stop.
Flowchart

Viva Questions:
a. What is switch statement.
b. What is a case in a switch statement?
c. Is Default necessary in switch case?
d. How many cases can you have in a switch statement?
Program 1
#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 subtraction*/
printf("%f - %f = %f\n", a, b,c);
break;
case '*' : c = a * b; /* compute
multiplication*/
printf("%f * %f = %f\n", a, b,c); break;

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


{
c = a / b; /* compute division */
printf("%f / %f = %f\n", a, b,c);
}
else
{
printf("Expression is not valid\n");

}
break;
default : printf("Enter valid operator\n");

}
}

OUTPUT

Compilation
cc calculator.c
Execution
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
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.
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
𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 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 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
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 the Program]
Flow chart

Program 2

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
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)
{
printf("a can not be 0\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);
}
}

Output
First Run:

Enter the 3 coefficients:


1
2
1
Roots are equal
root1=root2=-1.000000
Second Run:
Enter the 3 coefficients:
2
3
2
Roots are real and equal
root1=-0.500000
root2=-2.000000
Third Run:
Enter the 3 coefficients:
2
2
2
Roots are complex
root1=-0.500000+i 0.866025
root2=-0.500000- i 0.866025

Viva Questions:
a. What is quadratic Equation?
b. What is math.h ? why it is used in C program?
c. What are decision making statements in C language?
d. Write the syntax of “ if ”statement?
e. Difference between if and switch statements?
Program3: An electricity board charges the following rates for the use of electricity:
for the first 200 units 80 paise per unit: for the next 100 units 90 paise per unit:
beyond 300 units rupees 1 per unit. All users are charged a minimum of rupees 100
as meter charge. If the total amount is more than Rs 400, then 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.

Algorithm:
Input: Customer name and unit consumed
Output: Customer name, units consumed and total amount to be paid

Step 1: Start

Step 2: Read the name of customer and the unit consumed by the customer.

Step 3: Check if the unit consumed is greater than 1 and less than 200,if true goto step 4 else gotostep
5.
Step 4: Compute: amt=100+(0.8*units).
Step 5: if unit is greater than 200 and less than 300,if true goto step 6 else goto step 7
Step 6: Compute amt=100+(200*0.8)+((units-200)*0.9)
Step 7:Compute amt=100+(200*0.8)+(100*0.9)+((units-300)*1), then goto step 8
Step 8: Check if the amt is less than or equal to 400, if true goto step 9 otherwise goto step 10.
Step 9: Print the amount charged and goto step 11.
Step 10: compute amt=amt*1.15,and print the amount charged.
Step 11: Stop .
Flow chart

Start

Input name

Input units

amt=100+(0.8*units);
True
If(units<=200)

False

If(units>200 True amt=100+(200*0.8)+((units-200)*0.9);


&&
units<=300)
False

True
amt=100+(200*0.8)+(100*0.9)+(units-300)*1;

If(units>400)

True
amt=amt*1.15

Print name, units, charge

Stop
Program

#include <stdio.h>
void main()
{
char name[10];
float unit, amt;
printf("Enter your name and unit Consumed:");
scanf("%s %f",name,&unit);
if(unit<=200)
amt=unit*0.80+100;
else if((unit>200)&&(unit<=300))
amt=200*0.80+((unit-200)*0.90)+100;
else
amt=200*0.80+100*0.90+((unit-300)*1)+100;
if(amt>400)
amt=1.15*amt;
printf("Name: %s\n Unit=%f \n charge=%f ",name,unit,amt);
}
Output
First Run
Enter your name and unit Consumed: Siri 52
Name: Siri
Unit=52
charge=141.600000
Second Run
Enter your name and unit Consumed: Rajesh 460
Name: Rajesh
Unit=460
charge=586.500000
Program 4
WRITE A C PROGRAM TO DISPLAY THE FOLLOWING BY READING THE NUMBER OF
ROWS AS INPUT,
1
1 2 1
1 2 3 2 1
12 3 4 3 2 1
-----------------------
----
nth row

Problem Description
You need to write a C program that prompts the user to enter the number of rows as input. The
program should then display a pattern of numbers in a triangular shape, where each row consists of
numbers from 1 up to the current row number, followed by the numbers in reverse order until 1.
Each number is separated by a space. The pattern should have the specified number of rows.

Algorithm: [ Read No of Rows ]

Step 1: Start
Step 2: Read the number of rows.
Step 3: Let i=0, if i<=n, go to step 14
Step 4: Initialize j=1 if j<=n-i, Go to step 8
Step 5: Print blank spaces
Step 6: Increment j (ie. j=j+1) Go to step 5
Step 7: Initialize j=1 if j<=i Go to step 11
Step 8: Display number in ascending order up to middle.
Step 9: Increment j (ie. j=j+1) Go to step 8
Step 10: initialize j=i-1 if j>=1 Go to step 14
Step 11: Display number in reverse order after middle
Step 12: Increment j (ie. j=j+1) Go to step 13
Step 13: Increment i (ie. i=i+1) Go to step 3
Step 14: Stop.
FLOWCHART:-
PROGRAM:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n;
clrscr( );
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0; i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf("\t ");
}
for(j=1;j<=i;j++)
{
printf("%d\t",j);
}
for(j=i-1;j>=1;j--)
{
printf("%d\t",j);
}
printf("\n");
}
getch();
}
Output

First Run: Second Run:


Input number of rows: 4 Input number of rows : 6
1
121 1
12321 121
1234321 12321
1234321
123454321
12345654321

VIVA QUESTIONS:-
a. Write syntax of for loop?
b. What is the use of nested for loop?
c. Define Pattern.
Program 5
Implement Binary search on integer.
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 the program ]
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 mid position of a is equal to k then goto step 13 else goto next step ]
Step 10: [ If element at mid position of a is greater than k then compute high else goto next step ]
high = mid – 1
Step 11: [ If element at mid position of a is lesser than k then compute low ]
low = mid + 1
Step 12: [ Display Element not found ]
Step 13: [ Display Element found at mid+1 position ]
Step 14: [ Stop the program ]

Flowchart
Program
#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
Enter the number of elements
5
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
3
Enter the elements in ascending order
234
Enter the element to be searched
5
Unsuccessful search

VIVA QUESTIONS:-
a. What is an array/definition of array.
b. What are the types of array?
c. What is a multidimensional array?
d. How to declare and initialize one dimensional array?
e. What are the advantages of an array?
f. What is the difference between array & string?
g. Write the syntax of declaring an array.
Program 6.
Implement Matrix multiplication and validate the rules of multiplication.
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 the program]

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

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 the program ]


Flowchart

Program
#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];
}
}

}
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:
./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
34
The product of two matrix is
7 10
15 22

VIVA QUESTIONS:-
a. How to initialize two dimensional arrays?
b. How to pass a two dimensional array as function parameter?
c. How the memory is allocated for two dimensional array
d. Write the program to add and subtract two matrices.
e. Program to find the transpose of a matrix.
f. Program to find determinants of a matrix.
g. Program to find the diagonal elements of a matrix.
Program 7
Develop a Program to compute Sin(x) using Taylor series approximation. Compare your
result with the built- in Library function. Print both the results with appropriate
messages.
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
𝑥3 𝑥5 𝑥7
sin 𝑥 = 𝑥 − + − +−⋯
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: [Read the value of x in degree]- Read x
Step 3: [Initialization and Radians Conversion]
Temp = x
x=x*(3.142/180.0)
Term = x
sinx = term
n=1
Step 4: [Computer sin value]
Repeat while (term>FLT_EPSILON)
Fact = 2*n*(2*n+1)
Term = term * x * x /fact Sinx
sinx +term = n + 1n
Step 5: [Output]- Print sin(x) without using library function of Print sin(x) and with using library
function
Step 6: Stop

Flowchart
PROGRAM:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#include<math.h>
int fact(int m)
{
int i,f=1;
for(i=1;i<=m;i++)
{
f=f*i;
}
return 1;
}
void main()
{
int x,n,i;
float rad, res, sum=0;
clrscr();
printf("Enter degree\n");
scanf("%d",&x);
printf("Enter number of terms\n");
scanf("%d",&n);
rad=x*3.14/180;
for(i=1;i<=n;i+=2)
{
if ((i-1)%4==0)
sum=sum+pow(rad,i)/fact(i);
else
sum=sum-pow(rad,i)/fact(i);
}
printf("Calculate sin(%d) = %f", x,sum);
printf("\nLibrary sin(%d) = %f", x,sin(rad));
getch();
}
OUTPUT:-
First Run:
Enter degree
30
Enter number of terms
1
Calculate sin(30) = 0.523333
Library sin(30) = 0.499770
Second Run:
Enter degree
60
Enter number of terms
2
Calculate sin(60) = 1.046667
Library sin(60) = 0.865760

VIVA QUESTIONS:-
a. What is pre-processor directive?
b. What is difference between const and #define.
c. What is use of fabs().
d. What is variable initialization and why is it important?
e. What is the difference between the = symbol and == symbol?
f. Can the curly brackets { } be used to enclose a single line of code?
Program 8
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 the program ]

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 the program ]


Flowchart

Program
#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++)
{
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
5
Enter the elements
54321
The array before sorting
54321
The array after sorting
12345

VIVA QUESTIONS:-

a. Why the name bubble sort?


b. What are the different types of sorting techniques?
c. Explain the logic of bubble sort with an example.
d. What is nested for loop?
Program 09: Write functions to implement string operations such as compare,
concatenate, string length.Use the parameter passing techniques.

Algorithm
Algorithm String_Functions
Step1: start
Step2: read ch
Step3: switch(ch)
Case 1: read str1, str2 and call the function compare(str1,str2)
Case 2: read str1,str2 and call the function concat(str1,str2)
Case 3: read str1 and call the function length(str1)
Case 4 : exit(0)
Step4: stop
Algorithm Compare
Step1: start
Step2: if strcmp(str1,str2) == 0 then print given strings are equal
else print given strings are not equal
Step3: stop

Algorithm concat
Step1:start
Step2:strcat(str1,str2)
Step3:print str1
Step4:stop

Algorithm length
Step1: Start
Step2:strlen(str1)
Step3:print str1
Step4:Stop

Flowchart
Program

#include<stdio.h>
#include<string.h>
void stringlength(char a[100],char b[100]);
void concatenate(char a[100],char b[100]);
void stringcompare(char a[100],char b[100]);
void main()
{
char p[100],q[100],ch[100];
int len1,len2;
printf("Enter the first string:\n");
gets(p);
printf("Enter the second string:\n");
gets(q);
stringlength(p,q);
stringcompare(p,q);
concatenate(p,q);

void stringlength(char a[100], char b[100])


{
int len1,len2;
len1=strlen(a);
len2=strlen(b);
printf("First string length is :%d \n Second string lenght is: %d",len1,len2);

void concatenate(char a[100], char b[100])


{
printf("The concatenated String is :%s ", strcat(a,b));
}

void stringcompare(char a[100], char b[100])


{
if(strcmp(a,b)==0)
printf("\nSTRINGS ARE EQUAL\n");
else
printf("\nSTRINGS ARE NOT EQUAL\n");
}

Output
Enter the first string:RAM
Enter the second string:
RAM
First string length is :3
Second string lenght is: 3
STRINGS ARE EQUAL
VIVA QUESTIONS:-
a. What is string?
b. How to declare string?
c. What are the string manipulation function?
d. What is gets() and puts() function in string?
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 the program ]
Step 2: [ Declare the required variables]
Step 3: [ Read number of students as n ]
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 the program ]
Flowchart

Program
#include<stdio.h>
struct student
{
char name[20];
char usn[10];
float marks;
};
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++)
{
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
Enter number of students:
3
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
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

VIVA QUESTIONS:-
a. What is structure?
b. How to declare a structure?
c. What is structure member?
d. What is difference between array and structure?
e. What is nested structure?
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

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]
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;

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
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
VIVA QUESTIONS:-
a. Define pointer
b. Define array of pointer
c. Define array
Program 12: Write a C program to copy a text file to another, read both the input file
name and target file name.
Problem Description

ALGORITHM:-
Step 1 : Start
Step 2: Read the source file name fname1
Step 3: Open the file fname1 in read mode
Step 4: if fptr1 is equal to NULL
print " File does not found or error in opening.!!”
goto Step 12
Step 5: Read the new file name fname2
Step 6: Open the file fname2 in write mode
Step 7: if fptr2 is equal to NULL
print " File does not found or error in opening.!!"
goto Step 12
Step 8: Repeat while(1)
ch=fgetc(fptr1);
if ch is equal to EOF
break;
else
fputc(ch, fptr2);
Step 9: print “The file fname1 copied successfully in the file fname2”
Step 10: close file pointer fptr1
Step 11: close file pointer fptr2
Step 12: Stop
FLOWCHART
PROGRAM:-
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
clrscr();

printf("\n\n Copy a file in another name :\n");


printf(" \n");

printf(" Input the source file name : ");


scanf("%s",fname1);

fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}

OUTPUT:-

Copy a file in another name :

Input the source file name : test.txt


Input the new file name : test1.txt
The file test.txt copied successfully in the file test1.txt.

VIVA QUESTIONS:-
a. Define file.
b. What is fopen() and fclose() in file?
c. What is fgetc() and fputc() in file?

You might also like