0% found this document useful (0 votes)
61 views58 pages

Pop Lab Manual

The document outlines the laboratory syllabus for the Principles of Programming using 'C' course at Sir M. Visvesvaraya Institute of Technology for the academic year 2022-23. It includes program outcomes, programming assignments, and detailed algorithms and flowcharts for various programming tasks such as simulating a calculator, computing quadratic roots, and calculating electricity charges. The document serves as a guide for students to develop their programming skills through practical assignments.

Uploaded by

jamespj912
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)
61 views58 pages

Pop Lab Manual

The document outlines the laboratory syllabus for the Principles of Programming using 'C' course at Sir M. Visvesvaraya Institute of Technology for the academic year 2022-23. It includes program outcomes, programming assignments, and detailed algorithms and flowcharts for various programming tasks such as simulating a calculator, computing quadratic roots, and calculating electricity charges. The document serves as a guide for students to develop their programming skills through practical assignments.

Uploaded by

jamespj912
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/ 58

SIR M.

VISVESVARAYA INSTITUTE OF TECHNOLOGY


(Affiliated to VTU, Recognized by AICTE and Accredited by NBA, NAAC
and an ISO 9001-2008 Certified Institution) Bengaluru –
562157

Department of Computer Science & Engineering


PRINCIPLES OF PROGRAMMING USING ‘C’

LABORATORY

[BPOPS103]
(CHOICE BASED CREDIT SYSTEM)

(Academic Year 2022-23)


1ST SEMESTER
Prepared By: Shivaranjini C
Asst.Professor.
Under the Guidance of
Dr.Anitha T.N, Prof & Head.

CSE OF DEPT, SIR MVIT 1


CSE OF DEPT, SIR MVIT 2
CSE OF DEPT, SIR MVIT 3
SRI KRISHNADEVARAYA EDUCATIONAL TRUST
SIR M VISVESVARAYA INSTITUTE OF TECHNOLOGY
(Affiliated to VTU, Recognized by AICTE and Accredited by
NBA, NAAC
and an ISO 9001-2008 Certified Institution)
Bengaluru – 562157

PROGRAM OUTCOMES
PO's PO Description
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems
PO3 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.
Conduct investigations of complex problems: Use research-based knowledge and
PO4 research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

Modern tool usage: Create, select, and apply appropriate techniques,


PO5 resources, and modern engineering and IT tools including prediction and modeling
to complex engineering activities with an understanding of the limitations.

The engineer and society: Apply reasoning informed by the contextual knowledge
PO6 to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
PO8
and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or
PO9
leader in diverse teams, and in multidisciplinary settings.

CSE OF DEPT, SIR MVIT 4


Communication: Communicate effectively on complex engineering activities
PO10 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.
Project management and finance: Demonstrate knowledge and
PO11 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.
Life-long learning: Recognize the need for, and have the preparation and ability
PO12 to engage in independent and life-long learning in the broadest context of technological
change.

CSE OF DEPT, SIR MVIT 5


CSE OF DEPT, SIR MVIT 6
Programming Assignments

1. Simulation of a Simple Calculator.

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

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

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

2 3 4 3 2 1--------------------------- nth row

5. Implement Binary Search on Integers.

6. Implement Matrix multiplication and validate the rules of multiplication.

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.

8. Sort the given set of N numbers using Bubble sort.

9. Write functions to implement string operations such as compare, concatenate, and find string length.
Usethe parameter passing techniques.

10. Implement structures to read, write and compute average-marks ofthe students, list the students
scoring above and below the average marks for a class of N students.

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.

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

CSE OF DEPT, SIR MVIT 7


Lab Program:1

1. Simulation of a Simple Calculator

Algorithm

Step 1: [Start]

Step 2: [Display the menu - simple calculation]

1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder

Step 3: [Read two values]

Input a, b

Step 4: [Enter choice]

Read op

Step 5: [Switch case]

• Case 1: Sum → a + b
o break

• Case 2: Difference → a - b
o break

• Case 3: Product → a * b
o break

• Case 4: Division → a / b
o break

• Case 5: Remainder → a % b
o break

• Default:
o Print "Enter Your Correct Choice."

Step 6: [Print the result]

Output result inside each case

Step 7: [Stop]

CSE OF DEPT, SIR MVIT 8


Flow Chart

START

DISPLAY MENU

READ 2 VALUES
a, b

READ CHOICE

T
Case 1 Result = a + b

F
T
Case 2 Result = a - b

F
T
Case 3 Result = a * b

F
T
Case 4 Result = a / b
F
T
Case 5 Result = a % b

F
Default:
Print "Enter correct choice"
Print Result

STOP

CSE OF DEPT, SIR MVIT 9


PROGRAM

#include <stdio.h>
int main(void)
{
int a, b, op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n 5.Remainder\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
case 5:
printf("Remainder of %d and %d is : %d",a,b,a%b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
}

CSE OF DEPT, SIR MVIT 10


Ouptut:

CSE OF DEPT, SIR MVIT 11


2. Develop a program to compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate messages.

Algorithm

Step 1: [Start]
Step 2: [Read input values]
• Input a, b, c
Step 3: [Check for all-zero condition]
• If a = 0 and b = 0 and c = 0,
• Print “roots cannot be determined”
• Exit the program
Step 4: [Calculate the discriminant]
• disc = b * b - 4 * a * c
Step 5: [Check the discriminant and find roots]
1. If disc > 0:
• Compute
root1 = (-b + sqrt(disc))/2a, root2 = (-b - sqrt(disc))/2a
• Print “roots are real and distinct”
• Print the values of root1 and root2
2. Else if disc = 0:
• Compute
root1 = root2 = -b/2a
• Print “roots are equal”
• Print the values of root1 and root2
3. Else (i.e., disc < 0):
• Compute the real part and imaginary part:
realp = -b/2a, imagp = sqrt(|disc|)/(2|a|)
• Print “roots are complex”
• Print the complex roots as
root1 = realp + i * imagp, root2 = realp + i * imagp
Step 6: [Stop]

CSE OF DEPT, SIR MVIT 12


Flow Chart
START

Read a,b,c

T Print “roots cannot


If a = 0 and b = 0
and c = 0 be determined”

F
disc = b * b – 4 * a * c

T F
If disc > 0

F T
If disc == 0
root1 = (-b + sqrt(disc)/(2*a),
root1 = (-b - sqrt(disc)/(2*a)
root1 = -b/(2*a),
root1 = root2
If disc < 0

Print “roots are


real and distinct”, T
Print “roots are
root1, root2 realp = -b/2a,
equal”, root1,
imagp = sqrt(|disc|)/(2|a|) root2

Print “roots are complex”,


root1 = realp + i imagp,
root2 = realp – i imagp

STOP

CSE OF DEPT, SIR MVIT 13


PROGRAM

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
float a,b,c,disc;
float root1,root2,realp,imagp;
printf("enter values of a,b,c\n");
scanf("%f%f%f',&a,&b,&c);
if(a==0 && b==0 && c==0)
{
printf("roots cannot be determined\n");
exit(0);
}
else
{
disc=b*b-4*a*c;
if(disc>0)
{
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("roots are real and distinct\n");
printf("root1=%f\n",root1);
printf("root2=%f\n",root2);
}
else if(disc==0)
{
root1=-b/(2*a);
root2=root1;
printf(“roots are equal\n”);
printf(“root1=%f\n”,root1);
printf(“root2=%f\n”,root2);
}
else if(disc<0)
{
realp=-b/(2*a);
imagp=sqrt(abs(disc)/(2*a));
printf("roots are complex\n");
printf("root1=%f+i%f\n",realp,imagp);
printf("root2=%f-i%f\n",realp,imagp);
}

CSE OF DEPT, SIR MVIT 14


}

Ouptut:

CSE OF DEPT, SIR MVIT 15


3.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 Rs 1 per unit. All users are changed a
minimum of Rs. 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.

CSE OF DEPT, SIR MVIT 16


Flow Chart

START

Read consumer name

Read number of units


consumed

Meter charge = 100.0

T
Units Units
F
consumed consumed
>=0&&<2 >=200&&
00 <300

Charge=units Charge=units consumed*0.90


consumed*0.80 surcharge=0.0
surcharge=0.0
Charge=units-consumed+1+meter charge
surcharge=unit-consumed*0.15

Print total charge Print total charge Print total


=charge+surcharg =charge+surcharg charge=charge+su
e+metercharge e+metercharge rcharge

STOP

CSE OF DEPT, SIR MVIT 17


PROGRAM
#include<stdio.h>
#include<string.h>
void main()
{
int cust_no, unit_con;
float charge,surcharge=0, amt, total_amt;
char nm[25];
printf("Enter the customer IDNO :\t");
scanf("%d",&cust_no);
printf("Enter the customer Name :\t");
scanf("%s",nm);
printf("Enter the unit consumed by customer :\t");
scanf("%d",&unit_con);
if (unit_con <200 )
charge = 0.80;
else if (unit_con>=200 && unit_con<300)
charge = 0.90;
else
charge = 1.00;
amt = unit_con*charge;
if (amt>400)
surcharge = amt*15/100.0;
total_amt = amt+surcharge;
printf("\t\t\t\nElectricity Bill\n\n");
printf("Customer IDNO :\t%d",cust_no);
printf("\nCustomer Name :\t%s",nm);
printf("\nunit Consumed :\t%d",unit_con);
printf("\nAmount Charges @Rs. %4.2f per unit :\t%0.2f",charge,amt);
printf("\nSurchage Amount :\t%.2f",surcharge);
printf("\nMinimum meter charge Rs :\t%d",100);
printf("\nNet Amount Paid By the Customer :\t%.2f",total_amt+100);
}

CSE OF DEPT, SIR MVIT 18


Output:

CSE OF DEPT, SIR MVIT 19


4. Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321
---------------------------

Algorithm
Step 1: [Start]

Step 2: [Initialize variable]

• Set n = 5.

Step 3: [Outer loop to print rows]

• For i = 1 to n do:
Step 3.1: [Print leading spaces]

• For k = n down to i :

• Print a single space (" ").


Step 3.2: [Print ascending digits]

• For j = 1 to i :

• Print j .
Step 3.3: [Print descending digits]

• After the above loop, note that j = i + 1 .

• For l = j - 2 down to 1:

• Print l .
Step 3.4: [Print newline]

• Print a newline ("\n").

Step 4: [Stop]

CSE OF DEPT, SIR MVIT 20


Flowchart

START

Initialize n =5

T
Next i?

F
For k = n down to i
Print Space

For j = 1 to i
Print j STOP

For l = i – 1 down to 1
Print l

Print newline

PROGRAM

#include <stdio.h>
main()
{
int i,j,k,l,n=5;
for(i=1;i<=n;i++)
{
for(k=n;k>=i;k--)
printf(“ “);
for(j=1;j<=i;j++)
printf(“%d”,j);
for(l=j-2;l>0;l--)

CSE OF DEPT, SIR MVIT 21


printf(“%d”,l);
printf(“/n”);
}
return 0;
}

Output

CSE OF DEPT, SIR MVIT 22


5. Introduce 1D Array manipulation and implement Binary search Algorithm

Step 1: Start
Step 2: [Read the input]
Read the key number of names
Step 3: [Read the array]
for (i=0; i<n; i++) Read a[i]
Step 4: [Read key name]
Input key name
Step 5: [Initialize the result]
low =0 high = n-1
Step 6: [Compute result]
while (low <= high)
mid = (low +high)/2
If (strcmp (names [mid], key) ==0)
Print successful and print position
Else if (strcmp (name [mid], key >0))
high = mid-1
Else
low = mid+1
End of while
Step 7: [Print the result]
Print Unsuccessful
Step 8: [Finished]
Stop

CSE OF DEPT, SIR MVIT 23


Flow Chart

START

Read n

F
for (i=0; i<n; i++)
T
T
Read a[i]

Read key

low = 0
high = n-1

while (low<=high)

mid = (low + high)/2

F
if (strcmp if (strcmp
(a[mid],key F
(a[mid],key
)==0 )>0)

T
T

Print successful and


key position search

high = mid + 1 low = mid - 1

STOP Print unsuccessful search

CSE OF DEPT, SIR MVIT 24


PROGRAM

#include<stdio.h>
int main()
{
int a[100],i,n,found,mid,key,low,high;
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the element in ascending order \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the key elements \n");
scanf("%d",&key);
low=0;
high=n-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==1)
{
printf("key=%d found at position %d \n",key,mid+1);
}
else
{
printf("key=%d not found \n",key);
}
}

CSE OF DEPT, SIR MVIT 25


Output:

CSE OF DEPT, SIR MVIT 26


6. Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and
ensure the rules of multiplication are checked.
Algorithm
Step 1: [start]
Step 2: [Take input]
Read m,n,p,q
Step 3: Check
if (n!=p)
Print (“Multiplication not Possible”);
else
[Read matrix 1]
For (i=0; i<m; i++)
For (j=0; j<m; j++)
Read a[i][j]
[Read matrix 2]
for (j=0; j<q; j++)
for (i=0; i<p; i++)
Read b[i][j]
[Compute multiplication]
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]=C[i][j] + (a[i][k]*b[k][j])

Step 4: [print the result]


For (i=0; i<m; i++)
For (j=0; j<q; j++)
Print c[i][j]

Step 5: [Finished]
Stop

CSE OF DEPT, SIR MVIT 27


CSE OF DEPT, SIR MVIT 28
A B C D

for (k=0;k<n;k++)

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

F
for (i=0; i<m; i++)
T
F
for (i=0; i<q; i++)

C[i][j]=0

STOP

CSE OF DEPT, SIR MVIT 29


PROGRAM
#include<stdio.h>
#include<stdlib.h>
int main() {
int m, n, p, q, i, j, k;
int a[10][10], b[10][10], c[10][10];

// Input sizes of the matrices


printf("Enter the size of the first matrix (rows and columns): ");
scanf("%d%d", &m, &n);

printf("Enter the size of the second matrix (rows and columns): ");
scanf("%d%d", &p, &q);

// Check if multiplication is possible


if (n != p) {
printf("Matrix multiplication not possible. Number of columns of the first matrix must equal the
number of rows of the second matrix.\n");
exit(0);
}

// Input elements of the first matrix


printf("Enter the elements of the first matrix:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}

// Display the first matrix


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

// Input elements of the second matrix

CSE OF DEPT, SIR MVIT 30


printf("Enter the elements of the second matrix:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", &b[i][j]);
}
}

// Display the second matrix


printf("The second matrix is:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
printf("%d\t", b[i][j]);
}
printf("\n");
}

// Initialize the resultant matrix to zero


for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
c[i][j] = 0;
}
}
// Perform matrix multiplication
printf("Calculating the resultant matrix...\n");
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];
}
}
}
// Display the resultant matrix
printf("The resultant matrix is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d\t", c[i][j]);
}
printf("\n");
}
return 0;
}

CSE OF DEPT, SIR MVIT 31


Output:

CSE OF DEPT, SIR MVIT 32


7. Develop a program to compute Sin(x)/cos(x) using Taylor series approximation. Compare your result
with the built-in Library function. Print both the result with appropriate messages.

Algorithm

Step 1: [Start]

Step 2: [Declare variables]

• int i

• float x, t, sum, sum1, y

Step 3: [Input angle in degrees]

• Prompt: “Enter the angle”

• Read the value into x

• Store the original value in y = x

Step 4: [Convert degrees to radians]

• x = 3.1428 * (x / 180.0)

Step 5: [Initialize the Taylor series variables]

• sum = x (initial approximation for sine)

• t = x (term to be added)

• i=1

Step 6: [Compute sine using Taylor series]

• In a loop (do-while structure):

1. Increase i by 2 (i = i + 2)

2. Update the term: t = (-t * x * x) / ((i - 1) * i)

3. Update sum: sum = sum + t

4. Continue while the absolute value of t is greater than 0.00005

Step 7: [Print Taylor series result]

• Print sin(y) using taylor series = sum

Step 8: [Compute sine using inbuilt function]

• sum1 = sin(x)

• Print Using inbuilt function sin(y) = sum1

Step 9: [Stop]

CSE OF DEPT, SIR MVIT 33


Flow Chart

START

Read degree n

x = (degree * pi)/180
term = x
sum = term

F F
for (i=3;i<=n;i+=2)

term = (-term * x * x)/


(i* (i-1))
sum =sum + term

Print sum

Sum1=sin(x)
T sin(y) = sum1
Print Using inbuild function

STOP

CSE OF DEPT, SIR MVIT 34


PROGRAM

#include<stdio.h>
#include<math.h>
int main( )
{
int i;
float x,t,sum,sum1,y;
printf("Enter the angle\n");
scanf("%f",&x);
y=x;
x=3.1428*(x/180.0);
sum=x;
t=x;
i=1;
do
{
i=i+2;
t=(-t*x*x)/((i-1)*i);
sum = sum+t;
}
while(fabs(t)>0.00005);
printf("sin(%f) using taylor series=%f\n",y,sum);
sum1=sin(x);
printf("Using inbuilt function sin(%f)=%f",y,sum1);
}

CSE OF DEPT, SIR MVIT 35


Output:

CSE OF DEPT, SIR MVIT 36


8. Develop a program to sort the given set of N number using Bubble sort

Algorithm

Step 1: [start]

Step 2: [Read elements of an array]


Read n

Step 3: [Complie the number of passes required : n=1]


for (i=0; i<n; i++)
Read a[i]
To acess element in each pass
for (i=0; i<n; i++)
Print a[i]
End for
for (i=1; i<n; i++)
for (j=0; j<n-i; j++)
if a[j] > = a[i++]
exchange if out of order
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp

Step 4: [Print sorted array]


for (i=0; i<n; i++)
Print array a[i]

Step 5: [Finished]
Stop

CSE OF DEPT, SIR MVIT 37


Flow Chart
START

Read n

T F
for (i=0;i<n;i++)

Read a[i]

F for (i=1;i<=n;i++)

for (j=0;i<n-i;j++)
F
T
temp =a[j]
a[j]=a[j+1]
a[j+1]=temp

F
for (i=0;i<n;i++)

Print sorted list a[i]

STOP

CSE OF DEPT, SIR MVIT 38


PROGRAM

#include<stdio.h>
int main()
{
int i,j,n,temp;
int a[20];
printf("enter the value of n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
// bubble sort logic
for(i=0;i<n;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("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}}

CSE OF DEPT, SIR MVIT 39


Output:

CSE OF DEPT, SIR MVIT 40


9.Write function to implement string operations such as compare, concatenate, string length. Convince
the parameters passing techniques.

Algorithm:
Step 1: [Start]

Step 2: [Declare variables]

• int n (for menu choice), digit (for continuation)


• char str1[10], str2[10] (for storing strings)

Step 3: [Start a do-while loop for menu-driven operations]

• do

1. Print the menu:

• “press 1-compare 2-concatenate 3-length of string”

2. Prompt: “enter your choice=”

3. Read n (the user’s choice)

Step 4: [Switch-case on user choice]

• Case 1: Compare

1. Prompt “enter first string=” and read str1

2. Prompt “enter second string=” and read str2

3. Call compare(str1, str2) which does the following:

• Uses strcmp to check if str1 and str2 are equal

• Prints whether they are equal or not

• Case 2: Concatenate

1. Prompt “enter first string=” and read str1

2. Prompt “enter second string=” and read str2

3. Call concat(str1, str2) which does the following:

• Uses strcat(str1, str2) to concatenate str2 onto str1

• Prints the concatenated string

• Case 3: Length of a string

1. Prompt “enter string=” and read str1

2. Call length(&str1) which does the following:

• Uses strlen(str1) to find its length

• Prints the length

CSE OF DEPT, SIR MVIT 41


• Default:

• Print “wrong choice”

Step 5: [Check if user wants to continue]

• Prompt “Do you want to continue(1/0)?”

• Read digit

• If digit == 1, repeat the menu

• Otherwise, break from the loop

Step 6: [Stop]

CSE OF DEPT, SIR MVIT 42


Flow Chart

START

Read choice

T Result = length (str)


Case Length of string = %d
1
F

Case T Result = compare


2 (str1, str2)
F

T F
If
result==
0
T F
Strings are If
equal result>0

str1 > str2 Str1 < str2

T Concat (str1, str2) F


Case
3 Result = %s
Int length(char str[100])

T
While(str[i]!=’\0’ F

T
i++
STOP return (1)

CSE OF DEPT, SIR MVIT 43


PROGRAM
#include<stdio.h>
#include<string.h>
void compare(char [ ],char [ ]); .
void concat(char [ ],char [ ]);
void length(char *[ ]);
void main( )
{
int n,digit;
char str1[10],str2[10];
do
{
printf("press 1-compare 2-concatenate 3-length of string");
printf("\n enter your choice=");
scanf("%d",&n);
switch(n)
{
case 1:printf("enter first string=");
scanf("%s",str1);
printf("enter second string=");
scanf("%s",str2);
compare(str1,str2);
break;
case 2: printf("enter first string=");
scanf("%s",str1);
printf("enter second string=");
scanf("%s",str2);
concat(str1,str2);
break;
case 3: printf("enter string=");
scanf("%s",str1);
CSE OF DEPT, SIR MVIT 44
length(&str1);
break;
default: printf("wrong choice");
break;
}
printf("\n Do you want to continue(1/0)? ");
scanf("%d", &digit);
}
while(digit==1);
}
void compare(char str1[ ],char str2[ ])
{
int i;
i=strcmp(str1,str2);
if(i==0)
printf("strings are equal\n ");
else
printf("string are not equal\n");
void concat(char str1[ ],char str2[ ])
}
{
strcat(str1,str2);
printf("concatenate string=%s",str1);
void length(char *str1[ ])
}
{
int len;
len=strlen(str1);
printf("the length of string=%d",len);
}
}

CSE OF DEPT, SIR MVIT 45


Output:
press 1-compare 2-concatenate 3-length of string
enter your choice=1
enter first string=ram
enter second string=Ram
string are not equal
Do you want to continue(1/0)? 1
press 1-compare 2-concatenate 3-length of string
enter your choice=2
enter first string=RAM
enter second string=kumar
concatenate string=RAMkumar
Do you want to continue(1/0)? 1
press 1-compare 2-concatenate 3-length of string
enter your choice=3
enter string=ram
the length of string=3
Do you want to continue(1/0)? 1
press 1-compare 2-concatenate 3-length of string
enter your choice=4
wrong choice
Do you want to continue(1/0)? 0

CSE OF DEPT, SIR MVIT 46


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

Step 1: [Start]

Step 2: [Define the structure]

• struct student contains:

• char usn[10]
• char name[10]
• float m1, m2, m3
• float avg, total

Step 3: [Declare an array of structures and other variables]

• struct student s[20]


• int n, i
• float tavg, sum = 0.0 (though tavg and sum are not finally used in the code)

Step 4: [Read the number of students]

• Prompt “Enter the number of student=”


• Read n

Step 5: [Input student details in a loop]

• For i from 0 to n-1:

1. Print “Enter the detail of i-th student”


2. Read s[i].usn
3. Read s[i].name
4. Prompt “Enter the three subject score”
5. Read s[i].m1, s[i].m2, s[i].m3
6. s[i].total = s[i].m1 + s[i].m2 + s[i].m3
7. s[i].avg = s[i].total / 3

Step 6: [Check average mark and display message]

• For i from 0 to n-1:

• If s[i].avg >= 35

• Print “s[i].name has scored above the average marks”

• Else

• Print “s[i].name has scored below the average marks”

Step 7: [Stop]

CSE OF DEPT, SIR MVIT 47


Flow Chart

START

Read n

Enter the student details

For (i=0;i<n;i++)
temp!=sqrt

Enter the student details

Average = Average+s[i].marks
F

Average = Average/2
T

For (i=0;i<n;i++)
T
temp!=sqrt

Print name,usn,marks
STOP

If
st[i]marks
<average

Students marks is below Students marks is above


average average

CSE OF DEPT, SIR MVIT 48


PROGRAM
#include<stdio.h>
struct student
{
char usn[10];
char name[10];
float m1,m2,m3;
float avg,total;
};
void main()
{
struct student s[20];
int n,i;
float tavg,sum=0.0;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of %d students\n",i+1);
printf("\n Enter USN=");
scanf("%s",s[i].usn);
printf("\n Enter Name=");
scanf("%s",s[i].name);
printf("Enter the three subject score\n");
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
if(s[i].avg>=35)
printf("\n %s has scored above the average marks",s[i].name);
else
printf("\n %s has scored below the average marks",s[i].name);
}
}

CSE OF DEPT, SIR MVIT 49


Ouptut:

Output
Enter the number of student=2
Enter the detail of 1 students
Enter USN=101
Enter Name=Ram
Enter the three subject score 10 21 15
Enter the detail of 2 students
Enter USN=102
Enter Name=Kumar
Enter the three subject score 11 9 10
Ram has scored above the average marks
Kumar has scored below the average marks

CSE OF DEPT, SIR MVIT 50


11. Develop a program using pointers to compute the sum and standard deviation all elements
stored in an array of n real numbers.
Algorithm
Step 1: [Start]

Step 2: [Declare variables]

• int n, i
• float x[20], sum, mean, variance, deviation

Step 3: [Input the number of values]

• Prompt “Enter the value of n”


• Read n

Step 4: [Input the real values into the array]

• Prompt “enter n real values”


• For i from 0 to n-1, read x[i]

Step 5: [Calculate sum of the values]

• Initialize sum = 0
• For i from 0 to n-1, do sum = sum + x[i]

Step 6: [Compute mean]

• mean = sum / n

Step 7: [Calculate variance]

• Re-initialize sum = 0
• For i from 0 to n-1:
o sum = sum + (x[i] - mean) * (x[i] - mean)
• variance = sum / n

Step 8: [Compute standard deviation]

• deviation = sqrt(variance)

Step 9: [Display the results]

• Print mean, variance, deviation

Step 10: [Stop]

CSE OF DEPT, SIR MVIT 51


Flow Chart
START

sum = 0, sumstd = 0

Read n

F
for (i=0; i<n; i++)
T
Read a[i]

ptr = a

F
for (i=0; i<=n; i++)
T
sum = sum + *ptr ptr++

mean = sum/n
ptr = a

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


F

sumstd = sumstd +pow((*ptr –mean),2)


ptr++

var = sumstd/n
std = sqrt(var)

Print sum, mean, variance, standard


deviation

STOP

PROGRAM

CSE OF DEPT, SIR MVIT 52


#include<stdio.h>
#include<math.h>
int main(){
int n , i;
float x[20],sum,mean;
float variance , deviation;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("enter %d real values \n",n);
for (i=0;i<n;i++){
scanf("%f",(x+i));
}
sum=0;
for(i=0;i<n;i++){
sum= sum+*(x+i);
}
printf("sum=%f\n",sum);
mean=sum/n;
sum=0;
for(i=0;i<n;i++)
{
sum=sum+(*(x+i)-mean)*(*(x+i)-mean);
}
variance=sum/n;
deviation=sqrt(variance);
printf("mean(Average)=%f\n",mean);
printf("variance=%f\n",variance);
printf("standard deviation=%f\n",deviation);
}

Output:
Enter the value of n 5

CSE OF DEPT, SIR MVIT 53


Enter 5 real values
3
7
23
1
4
sum=38.000000
mean(Average)=7.600000
variance=63.039997
standard deviation=7.939773

CSE OF DEPT, SIR MVIT 54


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

Algorithm
Step 1: [Start]

Step 2: [Declare file pointers and variables]


• FILE *fptr1, *fptr2
• char filename[100], c

Step 3: [Open first file for reading]


• Prompt “Enter the filename to open for reading”
• Read filename into filename
• fptr1 = fopen(filename, “r”)

Step 4: [Check if first file is opened successfully]


• If fptr1 == NULL,
• Print “Cannot open file”
• exit(0)

Step 5: [Open second file for writing]


• Prompt “Enter the filename to open for writing”
• Read filename into filename
• fptr2 = fopen(filename, “w”)

Step 6: [Check if second file is opened successfully]


• If fptr2 == NULL,
• Print “Cannot open file”
• exit(0)

Step 7: [Copy contents from first file to second file]


• c = fgetc(fptr1)
• While c != EOF
• fputc(c, fptr2)
• c = fgetc(fptr1)

Step 8: [Print success message and close files]


• Print “\nContents copied to filename”
• fclose(fptr1)
• fclose(fptr2)

Step 9: [Stop]

CSE OF DEPT, SIR MVIT 55


Flow Chart
Start

Print “Enter the filename to


open for reading”

fptr1 = fopen(filename, ‘r’)

T F
fptr1==NULL

Print “Enter the


filename to open for
Cannot Open file for reading writing”

fptr2 = fopen(filename, ‘r’)

T F
fptr2==NULL

Cannot Open file for writing


c = fgetc(fptr1)

While (c != EOF)

fputc(c, fptr2)
c = fgetc(fptr1)

fclose(fptr1)
Stop fclose(fptr2)

CSE OF DEPT, SIR MVIT 56


Program:

#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

// Get the filename for reading


printf("Enter the filename to open for reading: \n");
scanf("%s", filename);

// Open the file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s for reading\n", filename);
exit(1);
}

// Get the filename for writing


printf("Enter the filename to open for writing: \n");
scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s for writing\n", filename);
fclose(fptr1); // Close the opened file before exiting
exit(1);
}

CSE OF DEPT, SIR MVIT 57


// Read contents from the first file and write them to the second file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s\n", filename);

// Close the files


fclose(fptr1);
fclose(fptr2);
return 0;
}

Output:
Enter the filename to open for reading a.txt
Enter the filename to open for writing b.txt
Contents copied to b.txt

CSE OF DEPT, SIR MVIT 58

You might also like