IT22111 Word Record Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 113

IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Exercise 1 Usage of Basic Linux commands

Exp No: 1
Date:
Question:
Commnands : mkdir , cd , mv , rm , ls , cat , vi , cp , etc.,
Aim:
To study the various Linux Commands.
Commands & their Description :

1. Command : mkdir
Description : Creating a new directorty
Usage : $mkdir dirname
Example : $mkdir ECE
Output : $mkdir ECE
$ls
$ECE

2. Command : ls
Description : To list all files and directory
Usage : $ls
Example : $ls
Output : $ECE

3. Command : cd
Description : To change directory
Syntax : $cd dirname
Usage : $cd ECE
Output : $ECE

4. Command : cd..
Description : To come out from a directory
Syntax : $cd..
Usage : $cd..
Output : ~$:
5. Command : cat>
Description : to create a new file
Syntax : $cat>filename.txt
Usage : $cat>sample.txt
Output : Hello
^z
+stopped

Reg No: 2127230701020 Page No:1


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
6. Command : cat
Description : to display the contents of a file
Syntax : $cat filename.txt
Usage : $cat sample.txt
Output : Hello

7. Command : cat>>
Description : to append content to existing files
Syntax : $cat>>filename.txt
Usage : $cat>>sample.txt
Output : We are from ECE-A!
^z
+stopped

8. Command : cp
Description : to copy contents from one file to another within same directory.
Syntax : $cp oldfile.txt newfile.txt
Usage : $cp sample.txt
$ls
Output : Sample.txt newfile.txt

9. Command : mv
Description : to move a file from aone directory to another
Syntax : $mv sourcedir/newfile.txt
Usage : $mv eceB/info.txt eceA
$ls
Output : Sample.txt

10. Command : rm
Description : to remove a file from a directory
Syntax : rm filename.txt
Usage : $rm sample.txt
$ls
Output : Sample.txt

11. Command : rmdir


Description : to remove a directory
Syntax : rmdir dirname
Usage : rmdir eceB
ls
Output : eceA

12. Command : vi
Description : It is a command line , an interactive editor that can be used to
create and edit text
Syntax : vi filename.c
Usage : vi file1.c

13. Command : cc

Reg No: 2127230701020 Page No:2


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Description : It is a compiler used to compile file c language codes and executables
Syntax : cc file.c
Usage : cc pgm.c

14. Command : ./a.out


Description : to create c program executables and displays output
Syntax : ./a.out
Usage : ./a.out

15. Command : password


Description : to change password
Syntax : $ password
Usage : $password
Enter current password :
Enter new password:
Re-enter the new password

Result:

Reg No: 2127230701020 Page No:3


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Exercise 2 C Programming using Simple statements and expressions

Exp No: 2(1)


Date:
Question: Print your name, I am an Engineer. Sample: My name is Sivaji, I am an Engineer.
Get familiar with vi, cc, and ./a.out.
Aim: To print a simple statement “My name is Bawadharani Sree. R I am an Engineer”.
Algorithm:
Step 1. Start
Step 2: use the printf to print the
" Name: Your Name,
I am an Engineer."
Step 3: Stop
Code:
#include<stdio.h>
void main()
{
printf("Name:\tBawadharani Sree. R,\nI am an Engineer.");
}
Output:

Result:

Reg No: 2127230701020 Page No:4


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 2(2)
Date:
Question: Print your details Name, age, Gender (M/F), Address, CutOff (in HSC) with one detail per
line and tab between label and value.
Aim: To print the details in the order of one detail per line.
Algorithm:
Step 1: Start
step 2: Use the printf() to print the basic details
Step 3: Stop
Code:
#include<stdio.h>
void main()
{
printf("Name:\tBawadharani Sree. R\nAge:\t17\nGender:\tFemale\nAddress:\tWest Tambaram,
Chennai-45\n12th cutoff:\t155\n");
}
Output:

Result:

Reg No: 2127230701020 Page No:5


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 2(3)
Date:
Question: Kumar has Rs.x and Sheela has Rs.y. Both exchange their amounts. Simulate this as an
interactive C program.
Aim: To swap the two values in a program
Algorithm:
Step 1:Start
Step 2: declare the input variables, a, b and temporary variables as t
Step 3: Get the amount that Kumar has in variable 'a' and sheela has variable 'b' from the user using
scanf()
step 4: swap the items
ta ; ab; bt
Step 5: Displays the amount after swapping using printf()
Step 6: stop
Code:
#include<stdio.h>
int main()
{
int x,y,t;
printf("Enter the amount that Kumar has[x]:");
scanf("%d",&x);
printf("Enter the amount that Shella has[y]:");
scanf("%d",&y);
t=x;
x=y;
y=t;
printf("After Exchanging\nNow Kumar has %d \nNow Shella has %d \n",x,y);
}

Reg No: 2127230701020 Page No:6


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:7


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 2(4)
Date:
Question: Box 1 has M apples and Box 2 has N apples. Assuming you do not have any other
space/storage to hold the apples, exchange the apples in Box 1 and Box 2. (Swap without temp)
Aim: To swap the values of the variables without temporary variable.
Algorithm:
Step 1: Start
Step 2: Declare the variable x, y
Step 3: Get the number of apples in Box 1 and Box2 in x&y
step 4: Swap
xx+y; yx-y; xx-y;
Step 5: Display the swapped number of apples using printf()
Step 6: Stop
Code:
#include<stdio.h>
int main()
{
int m,n;
printf("Enter the number of Apples in the Box1:");
scanf("%d",&m);
printf("Enter the number of Apples in the Box2:");
scanf("%d",&n);
m=m+n;
n=m-n;
m=m-n;
printf("After swapping\nThe Box 1 has %d Apples\nThe Box 2 has %d Apples\n",m,n);
}

Reg No: 2127230701020 Page No:8


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:9


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 2(5)
Date:
Question: Calculate the daily wage of a labour taking into account the pay per day, number of hours
worked, TA, and DA.
Aim: To calculate the Gross Salary, Travel Allowance, and Dearness Allowance of a person using
Basic Salary.
Algorithm:
Step 1: Start
Step 2: Declare the variables gs, bs, ta, da
Step 3: Get Basic Salay as bs.
Step 4: Calculate
ta= (102 * bs) /100
da = (10* bs) /100
gs = bs + ta + da
Step 5: print the gross salary gs
step 6: Stop
Code:
#include<stdio.h>
int main()
{
int gs,bs,ta,da;
printf("Enter the Basic salary:");
scanf("%d",&bs);
ta=(12*bs)/100;
da=(10*bs)/100;
gs=bs+ta+da;
printf("BS=%d\n",bs);
printf("TA=%d\n",ta);
printf("DA=%d\n",da);
printf("GS=%d\n",gs);
}

Reg No: 2127230701020 Page No:10


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:11


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 3 Scientific problems solving using decision making

Exp No: 3(1)


Date:
Question: Ram, Balaji, and Kumar are siblings aged x,y, and z respectively. Find the youngest and
oldest among them.
Aim: To find the oldest and youngest among three members.
Algorithm:
Step 1: Start
Step 2: Declare the variables r,b,k.
Step 3: Get the age of Ram, Balaji & Kumar in r, b & k respectively.
Step 4: check the condition if (r>b)&&(r>k) then output Ram is oldest
Check the condition if (b<k)&&(b>r)
then output Balaji is oldest otherwise Kumar is oldest
Step 5: Check the condition if (r<b)&&(r<k) then Ram 5 Youngest
check the condition of (b<k)&&(b<k) the Balaji is Youngest
otherwise Kumar is Oldest
Step 6: Stop
Code:
#include<stdio.h>
int main()
{
int r,b,k;
printf("Enter the age of Ram, Balaji, Kumar:\n");
scanf("%d%d%d",&r,&b,&k);
if((r>b)&&(r>k))
{printf("Ram is the oldest\n");}
else if ((b>k)&&(b>r))
{printf("Balaji is the oldest\n");}
else
{printf("Kumar is the oldest\n");}

Reg No: 2127230701020 Page No:12


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
if((r<b)&&(r<k))
{printf("Ram is the youngest\n");}
else if((b<k)&&(b<r))
{printf("Balaji is the youngest\n");}
else
{printf("Kumar is the youngest\n");}
}
Output:

Result:

Reg No: 2127230701020 Page No:13


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 3(2)
Date:
Question: “This Month” is an application that reads a number between 1 and 12 and prints the
numbers of days in that month. For example, if it reads 3, it displays 31. Develop the application
‘This Month’. Take care of Leap years. (Use if-else)
Aim: To print the number of days in a month.
Algorithm:
Step 1: Start
Step 2: Declare the variables y; m as integer
Step 3: Get the value of year as y and month as m
Step 4: Check if m==1 or 3 or 5 or 7 or 8 or 10 or 12 then point this month has 31 days
Step 5: check If m== 2
then check if ((y%4)==0) then point 29 days
otherwise print 28 days
Step 6: Otherwise points the month has 30 days
Stop 7: Stop
Code:
#include<stdio.h>
int main()
{
int y,m;
printf("Enter the Year:");
scanf("%d",&y);
printf("Enter the Month 1 to 12:");
scanf("%d",&m);
if((m==1)||(m==3)||(m==5)||(m==7)||(m==8)||(m==10)||(m==12))
{printf("This month has 31 days");}
else if (m==2)
{
if((y%4)==0)
{printf("This month has 29 days");}

Reg No: 2127230701020 Page No:14


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
else
{printf("This month has 28 days");}
}
else
{printf("This month has 30 days");}
}
Output:

Result:

Reg No: 2127230701020 Page No:15


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 3(3)
Date:
Question: ‘Solar System’ is an application that reads a number between 1 and 9 and prints the
respective planet. For example, if it reads 3, it displays ‘Venus’. Develop the application Solar
System. (simple switch)
Aim: To read a number and print the respective planet.
Algorithm:
Step 1: Start
Step 2: Declare a variable x
Step 3: Read the value of x from the user as between 1to 9
Step 4: paint the planet corresponding to the number
Step 5: Use switch case of x
case 1: print "SUN"
case 2: print "Mercury"
Case 3: print "Venus"
case 4: print " Earth"
case 5: print " Mars"
case 6: print "Jupitor"
case 7: print " Saturn"
case 8: print "Uranus"
case 9:print "Neptune"
Step 6: stop
Code:
#include<stdio.h>
int main()
{
int x;
printf("Solar System\nEnter 1 to 9:");
scanf("%d",&x);
switch(x)
{

Reg No: 2127230701020 Page No:16


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
case 1:
printf("SUN");
break;
case 2:
printf("Mercury");
break;
case 3:
printf("Venus");
break;
case 4:
printf("Earth");
break;
case 5:
printf("Mars");
break;
case 6:
printf("Jupiter");
break;
case 7:
printf("Saturn");
break;
case 8:
printf("Uranus");
break;
case 9:
printf("Neptune");
break;
default:
printf("Entered valuse is invalid");
break;

Reg No: 2127230701020 Page No:17


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
}
}
Output:

Result:

Reg No: 2127230701020 Page No:18


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 3(4)
Date:
Question: Develop a ‘Kids Laptop’ with minimum of 10 English letters to display A says Apple, B
says Ball… Enable the kids to learn both upper and lower case letters with same word. (Use switch
case clustering)
Aim: To display the word corresponding to the alphabet.
Algorithm:
Step 1: Start
Step 2: Declare c as character variable
Step 3: Read the alphabet in variable
Step 4: Using switch case clustering print the respective word.
step 5: As case A:
case 'a':
printf("Apple");
break;
Step 6: write this for alphabet A to J for both uppercase and lower case
Step 7: Stop
Code:
#include<stdio.h>
int main()
{
char c;
printf("Enter the alphabet:");
scanf("%c",&c);
switch(c)
{
case 'A':
case 'a':
printf("Apple");
break;
case 'B':

Reg No: 2127230701020 Page No:19


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
case 'b':
printf("Ball");
break;
case 'C':
case 'c':
printf("Cat");
break;
case 'D':
case 'd':
printf("Dog");
break;
case 'E':
case 'e':
printf("Elephant");
break;
case 'F':
case 'f':
printf("Fox");
break;
case 'G':
case 'g':
printf("Goat");
break;
case 'H':
case 'h':
printf("Hat");
break;
case 'I':
case 'i':
printf("Ice Cream");

Reg No: 2127230701020 Page No:20


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
break;
case 'J':
case 'j':
printf("Joker");
break;
default:
printf("Invalid");
}
}
Output:

Result:

Reg No: 2127230701020 Page No:21


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 4 Scientific problem solving using looping

Exp No: 4(1)


Date:
Question: Write a program that prints the numbers from 1 to 100. But for multiples of three print
“Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are
multiples of both three and five print “FizzBuzz”.
Aim: To print Fixx instead of multiples of 3 , Buzz instead of multiples of 5 and FizzBuzz instead of
multiples of 3&5.
Algorithm:
Step 1: Start
Sop 2: Declare i looping variable
Step 3: Inftialize a for, loop
for(i=1; i<=100; i++)
if((i%3==0)&&(i%5==0))
then print "Fizz Buzz"
else if(i%3==0)
then print "Fizz"
else if(i%5==0)
then print "Buzz"
otherwise
print the number
Step 4: Stop
Code:
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=100;i++)
{
if((i%3==0)&&(i%5==0))
printf("\tFizzBuzz");

Reg No: 2127230701020 Page No:22


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
else if(i%3==0)
printf("\tFizz");
else if(i%5==0)
printf("\tBuzz");
else
printf("\t%d",i);
}
}
Output:

Result:

Reg No: 2127230701020 Page No:23


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 4(2)
Date:
Question: An astrologer calculates the day’s fortune as the sum of the numbers in the date of birth.
If the sum is between 1 and 5(both inclusive), he predicts the day as ‘Excellent’. If the sum is
between 6 and 8 (both inclusive) he predicts the day as ‘Good’ and if the sum is 9 he predicts the day
as ‘Fair’. Develop an application for this model. (Hint: Repeat the process until the sum is a single
digit)
Aim: To predict the day using the date.
Algorithm:
Stop 1: Start
Step 2: Declare the input variable date as d, r for calculation
stop 3: Get the date in d variable
Step 4: calculate the sum of digits by
d = 8+ (d%10)*
d=d/10
Step 5: Repeat the step 4 until the r becomes a single digit
Step 6: if ((>=1&&(8<=5))
then display the day is Excellent
if(Cr >=6)&&(x<=8))
then display the day is Good
Otherwise display the day is Fair
Step 7: Stop
Code:
#include<stdio.h>
int main()
{
int d,r;
r=0;
printf("Enter The Date [DDMMYYY]:");
scanf("%d",&d);
while(d>0||r>9)
{

Reg No: 2127230701020 Page No:24


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
if(d==0)
{
d=r;
r=0;
}
r=r+(d%10);
d=d/10;
}
printf("%d",r);
if((r>=1)&&(r<=5))
printf("\nThe day is Excellent");
else if((r>=6)&&(r<=8))
printf("\nThe day is Good");
else
printf("\nThe day is Fair");
}
Output:

Result:

Reg No: 2127230701020 Page No:25


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 4(3)
Date:
Question: Print the following patterns using the concept of nested loops
(a)1
22
333
4444
55555
Aim: To print the above as output.
Algorithm:
Step 1: Start
Step 2: Declare i and j as loop variables
Step 3: use nested for loop for calculation
for(i=1;i<=5;i++)
{ for(j=1;j<=i;j++)
Printf(“%d”,i);
printf(“\n”);}
Step 4: Stop
Code:
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");

Reg No: 2127230701020 Page No:26


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
}
}
Output:

Result:

Reg No: 2127230701020 Page No:27


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

(b)1
23
456
7 8 9 10
11 12 13 14 15
Aim: To print the above as output.
Algorithm:
Step 1: Start
Step 2: Declare i and j as loop variables and k for incrementing values
Step 3: use nested for loop for calculation
for(i=1;i<=5;i++)
{ for(j=1;j<=i;j++)
Printf(“%d”,++k);
printf(“\n”);}
Step 4: Stop
Code:
#include<stdio.h>
int main()
{
int i,j,k=0;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",++k);
}
printf("\n");
}
}

Reg No: 2127230701020 Page No:28


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Output:

Result:

Reg No: 2127230701020 Page No:29


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
(c )
*
**
***
****
*****
Aim: To print the above as output.
Algorithm:
Step 1: Start
Step 2: Declare i and j as loop variables and set variable space=9
Step 3: use nested for loop for calculations
for(i=1;i<=5;i++)
within this loop use another loop to print space
for(j=1;j<=space;j++)
printf(“ “);
space=space-2;
then use for(j=1;j<=i;j++)
printf(“\n”):
Step 4: Stop
Code:
#include<stdio.h>
int main()
{
int i,j,space=9;
for(i=1;i<=5;i++)
{
for(j=1;j<space;j++)
{
printf(" ");
}
space=space-2;

Reg No: 2127230701020 Page No:30


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
}

Output:

Result:

Reg No: 2127230701020 Page No:31


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 5 Simple Programming For One Dimensional
And Two Dimensional array
Exp No: 5(1)
Date:
Question: Dr.Sudha marks daily attendance of N students as a sequence of ‘P’ and ‘A’ for present
and absent respectively help her to find the number of present and absentees for a day.
Aim: To determine the number of present and absent students by processing the attendance sequence
of ‘P’ and ‘A’.
Algorithm:
Step 1: Start.
Step 2: Initialize the variables precount and abscount to 0 and student.
Step 3: Read the no. of students in the variable student.
Step 4: Get the attendance sequence as a string as ‘P’ or ‘A’ for the specified no. of students
Step 5: For each element i in the attendance sequence
a) If i in ‘P’, increment precount.
b) If i in ‘A’, increment abscount.
Step 6: Display precount & abscount as result.
Step 7: Stop.
Code:
#include<stdio.h>
#include<string.h>
int main()
{
int student, precount=0, abscount=0;
char attendance[student];
printf("Enter the number of students: ");
scanf("%d",&student);
printf("Enter the attendance sequence (P for present, A for absent): \n");
int i;
for(i=0;i<student;i++)
{

Reg No: 2127230701020 Page No:32


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
scanf(" %c",&attendance[i]);
}
for (i=0;i<student;i++)
{
if (attendance[i] == 'P' || attendance[i] == 'p')
{
precount++;
} else if (attendance[i] == 'A' || attendance[i] == 'a')
{
abscount++;
}
else
{
printf("Invalid attendance input. Use only 'P' or 'A'.\n");
return 1; // Exit the program with an error code
}

}
printf("Number of present students: %d\n", precount);
printf("Number of absent students: %d\n", abscount);
}

Reg No: 2127230701020 Page No:33


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:34


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 5(2)
Date:
Question: Calculate the mean, variance and SD of N values using the following formulae:
a) Mean as the average of values.
∑(𝑋−𝑋̅ )2
b) Variance : 𝑠 2 = 𝑁−1
c) SD = s(square root of Variance)
Aim: To determine the mean, variance and standard deviation of the given sequence of numbers.
Algorithm:
Step 1: Start.
Step 2: Initialize N, I, sum, mean, variance and sd.
Step 3: Read the no. of values in variable ‘N’.
Step 4: Read the value in an array using for loop.
Step 5: Calculate the sum of values using for loop by
sum+=value[i]
Step 6: Calculate mean : mean = sum/n.
Step 7: Calculate variance :
Using for (i=0;i<N;i++)
variance+=pow(value[i]-mean, 2);
then varience/=(N-1);
Step 8: Calculate standard deviation:
sd = sqrt(variance);
Step 9: Display the mean, variance and SD.
Step 10: Stop.
Code:
#include<stdio.h>
#include<math.h>
int main()
{
int N,i;
printf("Enter the number of values (N): ");
scanf("%d", &N);

Reg No: 2127230701020 Page No:35


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
if (N <= 1) {
printf("Invalid input. N should be greater than 1.\n");
return 1;
}

double values[N];
double sum = 0.0;
printf("Enter %d values:\n", N);
for (i = 0; i < N; i++) {
printf("Value %d: ", i + 1);
scanf("%lf", &values[i]);
sum += values[i];
}
double mean = sum / N;
double variance = 0.0;
for (i = 0; i < N; i++) {
variance += pow(values[i] - mean, 2);
}
variance /= (N - 1);
double standardDeviation = sqrt(variance);
printf("\nMean: %.2lf\n", mean);
printf("Variance: %.2lf\n", variance);
printf("Standard Deviation: %.2lf\n", standardDeviation);
return 0;
}

Reg No: 2127230701020 Page No:36


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Output:

Result:

Reg No: 2127230701020 Page No:37


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 5(3)
Date:
Question: Read the sales done by 2 salesmen in 5 months for 4 products. Calculate the total sales
done for every month (matrix addition).
Aim: To calculate the total sales done for each product for every month.
Algorithm:
Step 1: Start.
Step 2: Initialize a 3- dimensional matrix sales [2][5][4] to store sales data for each salesman,
months and products.
Step 3: Initialize a 2- dimensional matrix tolalsales[5][4] to store the combined total sales for each
month and product.
Step 4: Use 3 for loops to
a) Read the sales date for each salesman, month and product into the sales matrix.
b) Perform matrix addition to calculate totalsales for each month and product by
Totalsales[j][k]+=sales[i][j][k];
Step 5: Display the totalsales matrix.
Step 6: Stop.
Code:
#include<stdio.h>
int main()
{
int sales[2][5][4],i,j,k;
int totalSales[5][4] = {0};
printf("Enter the sales data for each salesman, month, and product:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
for (k = 0; k < 4; k++) {
printf("Salesman %d, Month %d, Product %d: ", i + 1, j + 1, k + 1);
scanf("%d", &sales[i][j][k]);
totalSales[j][k] += sales[i][j][k];
}
}

Reg No: 2127230701020 Page No:38


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
}
printf("\nTotal Sales for Each Product for Every Month:\n");
for (j = 0; j < 5; j++) {
for (k = 0; k < 4; k++) {
printf("%d ", totalSales[j][k]);
}
printf("\n");
}
}

Reg No: 2127230701020 Page No:39


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Output:

Result:

Reg No: 2127230701020 Page No:40


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 5(4)
Date:
Question: A shopkeeper delivers rice bags to three shops SHOP1, SHOP2, SHOP3 in quantities of
10kg, 20kg and 30kg bags are Rs. 100, Rs. 200 and Rs. 300 respectively. If the shopkeeper delivers
one bag to each shop, calculate the income from the three shops separately (Vector -Matrix
multiplication).
Approach: Read the quantities sold as 1X3vector; treat as quantity per shop row-wise[1,1,1]. Read
the amounts of 10kg, 20kg and 30kg bags for each shop as a 3X3 matrix; treat shops column -wise
100 100 100
200 200 200
300 300 300
Then the income from each shop as vector- matrix multiplication is [600, 600, 600].
(Suggestion: Extend the vector as matrix as sales in 3 months for complete matrix multiplication)
Aim: To calculate the income from the three shops separately.
Algorithm:
Step 1: Start.
Step 2: Initialize ‘quantities’ array with the number of items sold at each shop.
Step 3: Initialize ‘prices’ 2D array with the prices of items in each shop.
Step 4: Initialize income array to zero.
Step 5: Using 2 for loops calculate the income from each shop as
for (j=0; j<3; j++)
for (k=0; k<3; k++)
income[j]+=quantities[k]*prices[k][j];
Step 6: Again, using a for loop, print the income from each shop.
Step 7: Stop.
Code:
#include <stdio.h>
int main() {
int quantities[3] = {1, 1, 1},j,k;
int prices[3][3] = {
{100, 100, 100},
{200, 200, 200},
{300, 300, 300}

Reg No: 2127230701020 Page No:41


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
};
int income[3] = {0};
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
income[j] += quantities[k] * prices[k][j];
}
}
printf("Income from each shop:\n");
for (j = 0; j < 3; j++) {
printf("Shop %d: Rs %d\n", j + 1, income[j]);
}

return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:42


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 6 Solving problems using Strings

Exp No: 6(1)


Date:
Question: Read a name and count the number of vowels in it.
Aim: To read a name and count the number of vowels in it.
Algorithm:
Step 1: Start
Step 2: Initialize the variable 'name' and get the string from the user
Step 3: Initialize variables:
-l (length of the name) to 0
-i (loop counter) to 0.
-k (vowel count) to 0.
Step4: Calculate the length of the name: l= strlen(name)
Step 5: Loop through each character in the name?
a) If the cuvant characters ‘A’, ‘a’, ’E’, ‘e’, ‘I’, ‘i’, ‘O’, ‘o’, ‘U’, ‘u’
b) then increment k by l
Step 6: Display the number of vowels k
Step 7: Stop
Code:
#include<stdio.h>
#include<string.h>
int main()
{
char name[50];
printf("Enter your Name:");
gets(name);
int l=0,i,k=0;
l=strlen(name);
for(i=0;i<l;i++)
{

Reg No: 2127230701020 Page No:43


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
if(name[i]=='A'||name[i]=='a'||name[i]=='E'||name[i]=='e'||name[i]=='I'||name[i]=='i'||name[i]=='O'||na
me[i]=='o'||name[i]=='U'||name[i]=='u')
{
k++;
}
}
printf("Your name has %d vowels",k);
}
Output:

Result:

Reg No: 2127230701020 Page No:44


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 6(2)
Date:
Question: Read the first name, middle name, and last name of a person and form a full name as
the concatenation of them. (Using and without using library functions)
Aim: To Read the first name, middle name, last name and form full name (with using library
function)
Algorithm: (with using library function)
Step 1: Start
Step 2: Initialize 3 variable to get first name, middle name, last name and get the input from the user
Step 3 Initialize another variable to store the fullname
Ste4 Concatenate
a) firstname to fullname
b) space to full name
c) middle name to fullname
d) space to fullname
e) lastname to full name
using strcat() function
Step 5: Display the full name
Step 6: Stop
Code:
#include <stdio.h>
#include <string.h>
int main() {
char firstName[50], middleName[50], lastName[50], fullName[150];
printf("Enter the first name: ");
gets(firstName);
printf("Enter the middle name: ");
gets(middleName);
printf("Enter the last name: ");
gets(lastName);
strcat(fullName, firstName);
strcat(fullName, " ");

Reg No: 2127230701020 Page No:45


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
strcat(fullName, middleName);
strcat(fullName, " ");
strcat(fullName, lastName);
printf("Full Name: %s\n", fullName);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:46


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Aim: To Read the first name, middle name, last name and form full name (without using library
function)
Algorithm: (without using library function)
Step 1: Start
Step 2: Initialize 3 variables to get firstname, middlename, lastname and get input from the user
Step 3: Initialize another variable to store the full name.
Step 4: Using for loop (or) while loop. and concatenate.
a) firstname to fullname
b) space to fullnance
e) middle name to fullname
d) space to fullname
e) lastname to fullname
Step 5: Display the fullname
Step 6: Stop.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char firstName[50], middleName[50], lastName[50], fullName[150];
printf("Enter the first name: ");
gets(firstName);
printf("Enter the middle name: ");
gets(middleName);
printf("Enter the last name: ");
gets(lastName);
int i = 0;
while (firstName[i] != '\0') {
fullName[i] = firstName[i];
i++;
}

Reg No: 2127230701020 Page No:47


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
fullName[i++] = ' ';
int j = 0;
while (middleName[j] != '\0') {
fullName[i++] = middleName[j++];
}
fullName[i++] = ' ';
j = 0;
while (lastName[j] != '\0') {
fullName[i++] = lastName[j++];
}
fullName[i] = '\0';
printf("Full Name: %s\n", fullName);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:48


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 6(3)
Date:
Question: The strength of a name is the sum of the ASCII values of its characters. Find the
strength of a name.
Aim: To find the sum of ASCII values of a string
Algorithm:
Step 1: Start
Step2: Initialize a variable to get the name from the user
Step 3. Initialize a variable strength to 0.
Step 4: Use for loop to traverse the string 'name' add the ASCII values to strength.
Step5: Display the strength
Step6: Stop
Code:
#include <stdio.h>
int main()
{
char name[50];
printf("Enter the name: ");
gets(name);
int strength = 0;
for (int i = 0; name[i] != '\0'; i++)
{
strength += (int)name[i];
}
printf("Strength of the name %s is: %d\n", name, strength);
return 0;
}

Reg No: 2127230701020 Page No:49


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:50


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 6(4)
Date:
Question: Read a string and check if it’s a palindrome.
Aim: To check whether a string and check if it’s a palindrome or not.
Algorithm:
Step 1: Start
Step 2: Initialise & variables 8[25], i, j, flag=1
Step 3: Gret the strings from the user
Step 4: Convert everything into lowercase using for loop
Step 5: Use for loop to compare characters:
for (i = 0, j =strlen(s)-1; i < j; i++, j--)
compare s[i] != s[j]
then flag=0; break;
Step 6: if flag=0
then palindrome
else not palindrome
Step 7: Stop
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char s[25];
int i, j, flag = 1;
printf("Enter a String: ");
gets(s);
for (i = 0; s[i] != '\0'; i++)
{
s[i] = tolower(s[i]);
}

Reg No: 2127230701020 Page No:51


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
for (i = 0, j =strlen(s)-1; i < j; i++, j--)
{
if (s[i] != s[j]) {
flag = 0;
break;
}
}
if (flag == 1) {
printf("It's a Palindrome");
} else {
printf("It's not a Palindrome");
}
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:52


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 7 Programs to illustrate structures and union

Exp No: 7(1)


Date:
Question: Create a structure Complex and perform addition, subtraction, and multiplication of 2
complex numbers.
Aim: To Create a structure Complex and perform addition, subtraction, and multiplication of 2
complex numbers.
Algorithm:
Step 1: Start
Step 2 Define a structure Complex to store real and imaginary numbers.
Step 3: Define functions to add, subtract and multiply using strut Complex as datatype
Step4: Initialize num1, num2, result as structure Complex
Step 5: Create the real and Imaginary parts of the two numbers.
Step6: Create a menu for choosing () add subtract con multiply in switchcase
Step 7: Display the result
Step 8: Stop
Code:
#include <stdio.h>
struct Complex
{
float real;
float imag;
};
struct Complex add(struct Complex num1, struct Complex num2);
struct Complex subtract(struct Complex num1, struct Complex num2);
struct Complex multiply(struct Complex num1, struct Complex num2);
int main()
{
struct Complex num1, num2, result;
int choice;

Reg No: 2127230701020 Page No:53


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
char continueChoice;
do
{
printf("Enter real and imaginary parts of the first complex number:\n");
printf("Real part: ");
scanf("%f", &num1.real);
printf("Imaginary part: ");
scanf("%f", &num1.imag);
printf("\nEnter real and imaginary parts of the second complex number:\n");
printf("Real part: ");
scanf("%f", &num2.real);
printf("Imaginary part: ");
scanf("%f", &num2.imag);
printf("\nMenu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("Enter your choice (1/2/3): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
result = add(num1, num2);
printf("Result of addition: %.2f + %.2fi\n", result.real, result.imag);
break;
case 2:
result = subtract(num1, num2);
printf("Result of subtraction: %.2f + %.2fi\n", result.real, result.imag);
break;
case 3:

Reg No: 2127230701020 Page No:54


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
result = multiply(num1, num2);
printf("Result of multiplication: %.2f + %.2fi\n", result.real, result.imag);
break;
default:
printf("Invalid choice\n");
}
printf("\nDo you want to continue? (y/n): ");
scanf(" %c", &continueChoice);
} while (continueChoice == 'y' || continueChoice == 'Y');
printf("Exiting the program. Goodbye!\n");
return 0;
}
struct Complex add(struct Complex num1, struct Complex num2) {
struct Complex r;
r.real = num1.real + num2.real;
r.imag = num1.imag + num2.imag;
return r;
}
struct Complex subtract(struct Complex num1, struct Complex num2) {
struct Complex r;
r.real = num1.real - num2.real;
r.imag = num1.imag - num2.imag;
return r;
}
struct Complex multiply(struct Complex num1, struct Complex num2) {
struct Complex r;
r.real = (num1.real * num2.real) - (num1.imag * num2.imag);
r.imag = (num1.real * num2.imag) + (num1.imag * num2.real);
return r;
}

Reg No: 2127230701020 Page No:55


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Output:

Result:

Reg No: 2127230701020 Page No:56


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 7(2)
Date:
Question: Create a structure STUDENT with <Roll_no,Name,Gender,marks[5],
grades[5],GPA>. Calculate the grade of each subject (assuming one-to-one mapping
of marks and grades) and GPA as the average of marks scored by a student.
Aim: To calculate the grade of each subject and GPA & of a student
Algorithm:
Step 1: Start
Step 2: Create a stricture STUDENT with rollno, Name, Gender, marks, grades, GPA
Step3: Get the necessary details from the user
Step4: Calculate the grades of each subject
Step 5: Calculate the GPA with as average of marks scored
Step 6: Display the graded and GPA
Step 7: Stop
Code:
#include <stdio.h>
struct STUDENT
{
int Roll_no;
char Name[50];
char Gender;
int marks[5];
char grades[5];
float GPA;
};
char calculateGrade(int marks)
{
if (marks >= 90) return 'A';
else if (marks >= 80) return 'B';
else if (marks >= 70) return 'C';

Reg No: 2127230701020 Page No:57


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
else if (marks >= 60) return 'D';
else return 'F';
}
float calculateGPA(struct STUDENT s)
{
float sum = 0;
for (int i = 0; i < 5; ++i) {
sum += s.marks[i];
}
return sum / 5.0;
}
int main()
{
struct STUDENT student;
printf("Enter Roll number: ");
scanf("%d", &student.Roll_no);
printf("Enter Name: ");
getchar();
gets(student.Name);
printf("Enter Gender (M/F): ");
scanf(" %c", &student.Gender);
for (int i = 0; i < 5; ++i)
{
printf("Enter marks for Subject %d: ", i + 1);
scanf("%d", &student.marks[i]);
student.grades[i] = calculateGrade(student.marks[i]);
}
student.GPA = calculateGPA(student);
printf("\nStudent Details:\n");
printf("Roll Number: %d\n", student.Roll_no);

Reg No: 2127230701020 Page No:58


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("Name: %s\n", student.Name);
printf("Gender: %c\n", student.Gender);
printf("\nSubject-wise Details:\n");
for (int i = 0; i < 5; ++i)
{
printf("Subject %d: Marks = %d, Grade = %c\n", i + 1, student.marks[i], student.grades[i]);
}
printf("\nGPA: %.2f\n", student.GPA);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:59


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 7(3)
Date:
Question: Create a structure DOB <Day,month,year>. Include this as a sub structure in
STUDENT and read and print the DOB a student along with other details.
Aim: To create sub structure DOB in STUDENT , read and print the DOB ofa Student along with
other details.
Algorithm:
Step1: Start
Step2: Create a structure DOB with Day, Month, year
Step 3: Create a structure STUDENT with rollno, name, gender, marks, grades. GPA, DOB
Step 4: Get the necessary details from the user
Step 5: Then display all the content
Step 6: Stop
Code:
#include <stdio.h>
struct DOB
{
int day;
int month;
int year;
};
struct STUDENT
{
int Roll_no;
char Name[50];
char Gender;
int marks[5];
char grades[5];
float GPA;
struct DOB dateOfBirth;
};

Reg No: 2127230701020 Page No:60


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
char calculateGrade(int marks)
{
if (marks >= 90) return 'A';
else if (marks >= 80) return 'B';
else if (marks >= 70) return 'C';
else if (marks >= 60) return 'D';
else return 'F';
}
float calculateGPA(struct STUDENT s)
{
float sum = 0;
for (int i = 0; i < 5; ++i) {
sum += s.marks[i];
}
return sum / 5.0;
}
int main()
{
struct STUDENT student;
printf("Enter Roll number: ");
scanf("%d", &student.Roll_no);
printf("Enter Name: ");
getchar();
gets(student.Name);
printf("Enter Gender (M/F): ");
scanf(" %c", &student.Gender);
printf("Enter Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &student.dateOfBirth.day, &student.dateOfBirth.month,
&student.dateOfBirth.year);
for (int i = 0; i < 5; ++i)
{

Reg No: 2127230701020 Page No:61


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("Enter marks for Subject %d: ", i + 1);
scanf("%d", &student.marks[i]);
student.grades[i] = calculateGrade(student.marks[i]);
}
student.GPA = calculateGPA(student);
printf("\nStudent Details:\n");
printf("Roll Number: %d\n", student.Roll_no);
printf("Name: %s\n", student.Name);
printf("Gender: %c\n", student.Gender);
printf("Date of Birth: %02d/%02d/%d\n", student.dateOfBirth.day, student.dateOfBirth.month,
student.dateOfBirth.year);
printf("\nSubject-wise Details:\n");
for (int i = 0; i < 5; ++i) {
printf("Subject %d: Marks = %d, Grade = %c\n", i + 1, student.marks[i], student.grades[i]);
}
printf("\nGPA: %.2f\n", student.GPA);
return 0;
}

Reg No: 2127230701020 Page No:62


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:63


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 7(4)
Date:
Question: Create a union employee <emp_id, salary>. Read and write the employee details and
demonstrate the significance of union’s space management.
Aim: To create union employee, read and write the employee details and to demonstrate the
significance of union's space management.
Algorithm:
Step1: Start
Step 2: Create a union employee with. name, gender, empid, salary.
Step 3: declare a variable emp of type union employee
Step 4: Get the detail of the employee and point them one by one
Step 5: Display the space management ug or size complexity using sizeof each element and union
Step 6: Stop
Code:
#include <stdio.h>
union employee
{
char name[20],gender;
int empId,salary;
};
void main()
{
union employee emp;
printf("\nEnter details :\n");
printf("Name: ");
gets(emp.name);
printf("Name: %s",emp.name);
printf("\nGender: ");
scanf("%c",&emp.gender);
printf("Gender: %c",emp.gender);
printf("\nID: ");

Reg No: 2127230701020 Page No:64


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
scanf("%d",&emp.empId);
printf("Id: %d",emp.empId);
printf("\nSalary:");
scanf("%d",&emp.salary);
printf("Salary: %d\n",emp.salary);
printf("Size of string Name: %d\n",sizeof(emp.name));
printf("Size of char Gender: %d\n",sizeof(emp.gender));
printf("Size of int empId: %d\n",sizeof(emp.empId));
printf("Size of int Salary: %d\n",sizeof(emp.salary));
printf("Size of Union: %d\n",sizeof(union employee));
}
Output:

Result:

Reg No: 2127230701020 Page No:65


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 8 Programs to illustrate Pointers
Use pointers for to implement the following
Exp No: 8(1)
Date:
Question: Implement a Pocket calculator with arithmetic operators (include increment/decrement
also).
Aim: To implement a pocket calculator with arithmetic operators(include increment/decrement also).
Algorithm:
Step 1: Start
Step 2: Declare a user defined function add, subtract, multiply, divide, increment, decrement with
pointer (*)
Step 3: Create a menu-based system to do the operations.
Step 4: Get the necessary input from the user.
Step 5: Call the function to do the operations with ampersand (&)
Step 6: Display the output.
Step 7: Stop.
Code:
#include <stdio.h>
void add(int *result, int a, int b)
{
*result = a + b;
printf("Addition: %d + %d = %d\n", a, b, *result);
}
void subtract(int *result, int a, int b)
{
*result = a - b;
printf("Subtraction: %d - %d = %d\n", a, b, *result);
}
void multiply(int *result, int a, int b)
{
*result = a * b;

Reg No: 2127230701020 Page No:66


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("Multiplication: %d * %d = %d\n", a, b, *result);
}
void divide(int *result, int a, int b)
{
if (b != 0) {
*result = a / b;
printf("Division: %d / %d = %d\n", a, b, *result);
} else {
printf("Error: Division by zero!\n");
}
}
void increment(int *num)
{
(*num)++;
printf("Increment: %d + 1 = %d\n", *num - 1, *num);
}
void decrement(int *num)
{
(*num)--;
printf("Decrement: %d - 1 = %d\n", *num + 1, *num);
}
int main()
{
int a, b, result;
char operator;
while (1) {
printf("Menu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");

Reg No: 2127230701020 Page No:67


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("4. Division\n");
printf("5. Increment\n");
printf("6. Decrement\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf(" %c", &operator);
if (operator == '0')
{
printf("Exiting calculator. Goodbye!\n");
break;
}
if (operator >= '1' && operator <= '6')
{
if (operator != '5' && operator != '6')
{
printf("Enter first number: ");
scanf("%d", &a);

printf("Enter second number: ");


scanf("%d", &b);
} else
{
printf("Enter a number: ");
scanf("%d", &a);
}
switch (operator)
{
case '1':
add(&result, a, b);
break;

Reg No: 2127230701020 Page No:68


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
case '2':
subtract(&result, a, b);
break;
case '3':
multiply(&result, a, b);
break;
case '4':
divide(&result, a, b);
break;
case '5':
increment(&a);
result = a;
break;
case '6':
decrement(&a);
result = a;
break;
}
} else
{
printf("Invalid choice. Please enter a valid option.\n");
}
}
return 0;
}

Reg No: 2127230701020 Page No:69


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:70


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 8(2)
Date:
Question: Demonstrate the effect that changing the value through the pointer to a structure
variable reflects the actual value of the variable. (Hint: Initialize a structure variable;
create a pointer to the variable; modify the value using pointer and show the changes)
Aim: To demonstrate the effect that changing the value through the pointer to a structure
variable reflects the actual value of the variable.
Algorithm:
Step 1: Start
Step 2: Define a structure Person with its members as Name, Age.
Step 3: Declare a structure variable person1.
Step 4: Initialize Structure Variable:
- Use strcpy to set the initial name to "John".
- Set the initial age to 25.
Step 5: Declare a pointer to the Person structure named and assign the address of person1 to the
pointer.
Step 6: Display Initial Values
Step 7: Modify Values Using Pointer
Step 8: Display Modified Values
Step 9: Stop.
Code:
#include <stdio.h>
struct Person
{
char name[50];
int age;
};
int main()
{
struct Person person1;
strcpy(person1.name, "John");

Reg No: 2127230701020 Page No:71


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
person1.age = 25;
struct Person *ptr = &person1;
printf("Initial values:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n\n", person1.age);
strcpy(ptr->name, "Alice");
(*ptr).age = 30;
printf("Modified values through pointer:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:72


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 8(3)
Date:
Question: Read and display the details of N books where each book has
<ISBN,title,price,author>.
Aim: To read and display the details of N books using pointers.
Algorithm:
Step 1: Start.
Step 2: Define a structure named Book with members ISBN (char array), title (char array), price
(float), and author (char array).
Step 3: Read the number of books
Step 4: Declare an array of structure Book named books with size N.
Step 5: Declare a pointer to a Book structure.
Step 6: Input details for each book using pointers.
Step 7: Reset the pointer to the beginning of the array.
Step 8: Display details of each book using pointers.
Step 9: Stop.
Code:
#include <stdio.h>
struct Book
{
char ISBN[15];
char title[50];
float price;
char author[50];
};
int main()
{
int N;
printf("Enter the number of books: ");
scanf("%d", &N);
struct Book books[N];

Reg No: 2127230701020 Page No:73


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
struct Book *ptr = books;
for (int i = 0; i < N; i++)
{
printf("\nEnter details for book %d:\n", i + 1);
printf("ISBN: ");
scanf("%s", ptr->ISBN);
printf("Title: ");
scanf(" %[^\n]s", ptr->title);
printf("Price: ");
scanf("%f", &ptr->price);
printf("Author: ");
scanf(" %[^\n]s", ptr->author);
ptr++;
}
ptr = books;
printf("\nDetails of the books:\n");
for (int i = 0; i < N; i++)
{
printf("\nBook %d:\n", i + 1);
printf("ISBN: %s\n", ptr->ISBN);
printf("Title: %s\n", ptr->title);
printf("Price: %.2f\n", ptr->price);
printf("Author: %s\n", ptr->author);
ptr++;
}
return 0;
}

Reg No: 2127230701020 Page No:74


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:75


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 8(4)
Date:
Question: Generate a multiplication table for user input M and N.
Aim: To generate a multiplication table for user input M and N using pointers.
Algorithm:
Step 1: Start
Step 2: Declare variables:
- n, i, m as integers
- ptr as an integer pointer
Step 3: Read user input for n:
- Print "Enter the no:"
- Read n
Step 4: Read user input for m:
- Print "Enter the limit:"
- Read m
Step 5: Set the pointer to the address of n:
- Set ptr to the address of n
Step 6: Print the multiplication table:
- Print "\nMULTIPLICATION TABLE"
Step 7: For each value of i from 1 to m:
a. Print the multiplication result using pointers:
- Print "n X i = n * i" where *ptr represents the value at the address pointed by ptr.
Step 8: Stop.
Code:
#include<stdio.h>
int main()
{
int n,i,m;
int *ptr;
printf("Enter the no:");

Reg No: 2127230701020 Page No:76


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
scanf("%d",&n);
printf("Enter the limit:");
scanf("%d",&m);
ptr=&n;
printf("\nMULTIPLICATION TABLE \n");
for(i=1;i<=m;i++)
{
printf("\n%d X %d = %d",n,i,*ptr*i);
}
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:77


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 9 Programs to illustrate user defined functions

Exp No: 9(1)


Date:
Question: Create functions of prototypes print_int(int), print_float(float),
print_char(char),print_string(char *). Define the functions with only printf(). Read
your roll_no, GPA, gender, and name and use the prototypes to print them.
Aim: To create various user defined function to print the details. Get the details from the user.
Algorithm:
Step 1: Start.
Step 2: Function Prototypes:
- Define function prototypes for print_int, print_float, print_char, and print_string.
Step 3: Declare variables:
- roll_no, gpa as integers
- gender as a character
- name as a character array
Step 4: Read student information.
Step 5: Print student information using user-defined functions:
a. Print "\nStudent Information:".
b. Call print_int function with roll_no as an argument.
c. Call print_float function with gpa as an argument.
d. Call print_char function with gender as an argument.
e. Call print_string function with name as an argument.
Step 6: Stop.
Code:
#include <stdio.h>
void print_int(int);
void print_float(float);
void print_char(char);
void print_string(char *);
int main()

Reg No: 2127230701020 Page No:78


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
{
int roll_no;
float gpa;
char gender, name[50];
printf("Enter Roll Number: ");
scanf("%d", &roll_no);
printf("Enter GPA: ");
scanf("%f", &gpa);
printf("Enter Gender (M/F): ");
scanf(" %c", &gender);
printf("Enter Name: ");
scanf(" %[^\n]s", name);
printf("\nStudent Information:\n");
print_int(roll_no);
print_float(gpa);
print_char(gender);
print_string(name);
return 0;
}
void print_int(int num)
{
printf("Roll Number: %d\n", num);
}
void print_float(float num)
{
printf("GPA: %.2f\n", num);
}
void print_char(char ch)
{
printf("Gender: %c\n", ch);

Reg No: 2127230701020 Page No:79


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
}
void print_string(char *str)
{
printf("Name: %s\n", str);
}
Output:

Result:

Reg No: 2127230701020 Page No:80


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 9(2)
Date:
Question: Simulate pocket calculator operations using functions of various styles (with/without
parameter/return). Pass a variable result in main() by reference to demonstrate pass by
reference.
Aim: To simulate pocket calculator operations using functions of various styles (with/without
parameter/return). Pass a variable result in main() by reference to demonstrate pass by reference.

Algorithm:
Step 1: Start.
Step 2: Display the menu options:
- Addition
- Subtraction
- Multiplication
- Division
- Increment
- Decrement

Step 3: Prompt the user to enter their choice (p).

Step 4: If the choice (p) is between 1 and 4, prompt the user to enter two numbers (a and b).
- If the choice is 5 or 6, prompt the user to enter one number (a).

Step 5: Use a switch-case statement based on the user's choice (p).


a. Case 1:
- Call the add function with the address of result, a, and b.
- Display the result of addition.
b. Case 2:
- Call the sub function with the address of result, a, and b.
- Display the result of subtraction.
c. Case 3:
- Call the mul function with the values of a and b.
- Display the result of multiplication.
d. Case 4:

Reg No: 2127230701020 Page No:81


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
- Call the div function with the values of a and b.
- Display the result of division.
e. Case 5:
- Call the increment function with the address of a.
- Display the incremented value.
f. Case 6:
- Call the decrement function with the value of a.
- Display the decremented value.
Step 6: End the program.
Functions:
- add(result, a, b):
o Calculate the sum of a and b.
o Store the result at the memory location pointed to by the result pointer.
- sub(result, a, b):
o Calculate the difference between a and b.
o Return the result.
- mul(a, b):
o Calculate the product of a and b.
o Display the result.
- div(a, b):
o Check if b is not equal to 0.
o If true, calculate the division of a by b and display the result.
o If false, display an error message for division by zero.
- increment(x):
o Increment the value at the memory location pointed to by the x pointer.
- decrement(x):
o Display the decremented value of x.
Step 7: Stop.
Code:
#include<stdio.h>
void add(int*,int,int);
int sub(int*,int,int);
void mul(int,int);
void div(int,int);

Reg No: 2127230701020 Page No:82


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
void increment(int*);
void decrement(int);
void main()
{
int res,a,b,p,r;
printf("1-Addition\n2-Subtraction\n3-Multiplication\n4-Division\n5-Increment\n6-decrement\n");
printf("Enter your choice:");
scanf("%d",&p);
if(p>=1 && p<=4)
{
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
}
else if(p==5||p==6)
{
printf("Enter a number: ");
scanf("%d",&a);
}
else
{
printf("Enter a valid number");
}
switch(p)
{
case 1:
add(&res,a,b);
printf("%d+%d=%d",a,b,res);
break;
case 2:
r=sub(&res,a,b);

Reg No: 2127230701020 Page No:83


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("%d-%d=%d",a,b,r);
break;
case 3:
mul(a,b);
break;
case 4:
div(a,b);
break;
case 5:
increment(&a);
printf("Incremented value is: %d",a);
break;
case 6:
decrement(a);
break;
}
}
void add(int *x, int y, int z)
{
*x=y+z;
} int sub(int *x, int y, int z)
{
*x=y-z;
return *x;
}
void mul(int x, int y)
{
printf("%d x %d = %d", x, y, x*y);
}
void div(int x, int y)

Reg No: 2127230701020 Page No:84


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
{
printf("%d / %d = %d", x, y, x/y);
}
void increment(int *x)
{
*x+=1;
}
void decrement(int x)
{
printf("Decremented value is:%d",x-1);
}
Output:

Result:

Reg No: 2127230701020 Page No:85


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 9(3)
Date:
Question: Demonstrate sorting N student details using a function rank_students(student[], n)
based on their GPA. Use STUDENT <roll_no,name,GPA>.
Aim: To demonstrate sorting of N student details using user defined functions.
Algorithm:
Step 1: Start.
Step 2: Declare a structure Student with roll no, name, GPA.
Step 3: Define a user defined function to sort them according to their rank.
Step 4: Define a user defined function to swap elements.
Step 5: Get the necessary details from the user as input.
Step 6: Pass the input to the functions.
Step 7: Display the sorted list.
Step 8: Stop.
Code:
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_STUDENTS 100
struct Student
{
int roll_no;
char name[MAX_NAME_LENGTH];
float GPA;
};
void rank_students(struct Student students[], int n);
void swap(struct Student *a, struct Student *b);
int main()
{
int n;

Reg No: 2127230701020 Page No:86


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("Enter the number of students: ");
scanf("%d", &n);
if (n <= 0 || n > MAX_STUDENTS)
{
printf("Invalid number of students. Exiting program.\n");
return 1;
}
struct Student students[MAX_STUDENTS];
for (int i = 0; i < n; i++)
{
printf("Enter details for Student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &students[i].roll_no);
printf("Name: ");
scanf("%s", students[i].name);
printf("GPA: ");
scanf("%f", &students[i].GPA);
}
rank_students(students, n);
printf("\nSorted list of students based on GPA and Roll No:\n");
printf("Roll No\tName\t\tGPA\n");
for (int i = 0; i < n; i++)
{
printf("%d\t%s\t\t%.2f\n", students[i].roll_no, students[i].name, students[i].GPA);
}
return 0;
}
void rank_students(struct Student students[], int n)
{
for (int i = 0; i < n - 1; i++)

Reg No: 2127230701020 Page No:87


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
{
for (int j = 0; j < n - i - 1; j++)
{
if (students[j].GPA == students[j + 1].GPA && students[j].roll_no > students[j + 1].roll_no)
{
swap(&students[j], &students[j + 1]);
}
else if (students[j].GPA < students[j + 1].GPA)
{
swap(&students[j], &students[j + 1]);
}
}
}
}
void swap(struct Student *a, struct Student *b)
{
struct Student temp = *a;
*a = *b;
*b = temp;
}

Reg No: 2127230701020 Page No:88


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:89


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 9(4)
Date:
Question: Write programs using recursive functions for the following:
a) Find the sum of digits of a number (refer Astrologer scenario)
b) Search an element in an array (Linear search)
c) Print the marks in letters (refer SVCE exam portal scenario)

Aim: To write programs using recursive functions for the following:


a) Find the sum of digits of a number (refer Astrologer scenario)
b) Search an element in an array (Linear search)
c) Print the marks in letters (refer SVCE exam portal scenario)

Algorithm: a) Find the sum of digits of a number (refer Astrologer scenario)

Step 1: Start the program.

Step 2: Declare a function sumOfDigits with the following signature:

int sumOfDigits(int n);

Step 3: In the main function:

a. Declare a variable num to store the input number.


b. Prompt the user to enter a number and store it in the variable num.
c. Call the sumOfDigits function with num as an argument and store the result in a
variable result.
d. Display the result: "Sum of digits of [num] is: [result]".

Step 4: In the sumOfDigits function:

a. Check if the number n is less than 10.

- If true, return n (base case).


- If false, proceed to the recursive case.

b. In the recursive case, return the sum of the last digit of n and the sumOfDigits function called
with the remaining part (n / 10).

Step 5: End the program.


Code:
#include <stdio.h>
int sumOfDigits(int n);
int main()

Reg No: 2127230701020 Page No:90


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
int result = sumOfDigits(num);
printf("Sum of digits of %d is: %d\n", num, result);
return 0;
}
int sumOfDigits(int n)
{
if (n < 10)
{
return n;
} else
{
return sumOfDigits(n % 10 + sumOfDigits(n / 10));
}
}
Output:

Result:

Reg No: 2127230701020 Page No:91


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Algorithm: b) Search an element in an array (Linear search)
Step 1: Start
Step 2: Get the size of the array (size) from the user.
Step 3: Check if the array size (size) is less than or equal to 0.
- If true, display an error message and exit the program.
- If false, proceed to the next step.
Step 4: Declare an array arr of integers with size elements.
Step 5: Use a for loop to input elements into the array arr.
- For i = 1 to size:
a. Display "Enter element i: ".
b. Read and store the input in arr[i-1].
Step 6: Display "Enter the element to search: ".
- Read and store the input in the variable key.
Step 7: Call the recursive function linearSearch with parameters arr, key, and size.
- Store the result in a variable index.
Step 8: If index is not equal to -1, display "Element key found at index index."
- Otherwise, display "Element key not found in the array."
Step 9: Stop
Code:
#include <stdio.h>
int linearSearch(int arr[], int key, int size);
int main()
{
int size, key;
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size <= 0)
{
printf("Invalid array size. Exiting program.\n");
return 1;

Reg No: 2127230701020 Page No:92


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
}
int arr[size];
printf("Enter elements of the array:\n");
for (int i = 0; i < size; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);
int index = linearSearch(arr, key, size);
if (index != -1)
{
printf("Element %d found at index %d.\n", key, index);
} else
{
printf("Element %d not found in the array.\n", key);
}
return 0;
}
int linearSearch(int arr[], int key, int size)
{
if (size == 0)
{
return -1;
}
if (arr[0] == key)
{
return 0;
} else

Reg No: 2127230701020 Page No:93


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
{
int result = linearSearch(arr + 1, key, size - 1);
if (result != -1)
{
return result + 1;
} else
{
return -1;
}
}
}
Output:

Result:

Reg No: 2127230701020 Page No:94


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Algorithm: c) Print the marks in letters (refer SVCE exam portal scenario)
Step 1: Start
Step 2: Declare a function f with the signature void f(int n).
Step 3: In the main function:
a. Declare a variable num to store the input number.
b. Display "Enter any number: ".
c. Read and store the input in the variable num.
d. Call the function f with num as the argument.
Step 4: In the function f:
a. If n is equal to 0, return (base case).
b. Make a recursive call to f with n/10 as the argument.
c. Use a switch statement on n%10 to print the corresponding word for the digit:
- Case 0: Print "zero ".
- Case 1: Print "one ".
- Case 2: Print "two ".
- Case 3: Print "three ".
- Case 4: Print "four ".
- Case 5: Print "five ".
- Case 6: Print "six ".
- Case 7: Print "seven ".
- Case 8: Print "eight ".
- Case 9: Print "nine ".
Step 5: Stop.
Code:
#include<stdio.h>
void f(int n);
int main(){
int num ;
printf("Enter any number: ");
scanf("%d",&num);

Reg No: 2127230701020 Page No:95


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
f(num);
return 0;
}
void f(int n){
if(n==0)
{
return;
}
f(n/10);
switch(n%10){
case 0: printf("zero ");break;
case 1: printf("one ");break;
case 2: printf("two ");break;
case 3: printf("three ");break;
case 4: printf("four ");break;
case 5: printf("five ");break;
case 6: printf("six ");break;
case 7: printf("seven ");break;
case 8: printf("eight ");break;
case 9: printf("nine ");break;
}
}
Output:

Result:

Reg No: 2127230701020 Page No:96


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 10 File Handling in C

Exp No: 10(1)


Date:
Question: Read a sentence from console and write into a file out.txt. Read out.txt, change the
case of each character, and write in console.
Aim: To read a sentence from console and write into a file out.txt. Read out.txt, change the
case of each character, and write in console.
Algorithm:
Step 1: Start
Step 2: Declare variables:
- file: FILE pointer to handle file operations.
- sentence: Array to store the input sentence.
Step 3: Read a sentence from the console and store it in the array 'sentence' using fgets.
Step 4: Open the file "out.txt" for writing (mode "w").
- If the file opening fails, display an error message and exit the program.
Step 5: Write the content of the 'sentence' array into the file using fprintf.
Step 6: Close the file.
Step 7: Open the file "out.txt" for reading (mode "r").
- If the file opening fails, display an error message and exit the program.
Step 8: Print "Modified content from file:".
Step 9: Read each character from the file until the end of file (EOF) using a while loop.
a. Change the case of each alphabetic character:
- If the character is lowercase, convert it to uppercase.
- If the character is uppercase, convert it to lowercase.
- Print the modified character to the console.
Step 10: Close the file.
Step 11: Stop.
Code:
#include <stdio.h>
#include <stdlib.h>

Reg No: 2127230701020 Page No:97


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
void changeCase(char *str);
int main()
{
FILE *file;
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
file = fopen("out.txt", "w");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
fprintf(file, "%s", sentence);
fclose(file);
file = fopen("out.txt", "r");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
printf("Modified content from file:\n");
int ch;
while ((ch = fgetc(file)) != EOF)
{
if (ch >= 'a' && ch <= 'z')
{
ch = ch - 'a' + 'A';
} else if (ch >= 'A' && ch <= 'Z')
{

Reg No: 2127230701020 Page No:98


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
ch = ch - 'A' + 'a';
}
putchar(ch);
}
fclose(file);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:99


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 10(2)
Date:
Question: Read any of the C files from your previous exercises and print the same on the
console.
Aim: To read any of the C files from your previous exercises and print the same on the
console.
Algorithm:
Step 1: Start
Step 2: Declare variables:
- file: FILE pointer to handle file operations.
- filename: Array to store the filename.
- ch: Variable to store each character read from the file.
Step 3: Get the filename from the user.
- Display "Enter the filename to read: ".
- Read and store the input in the array 'filename'.
Step 4: Open the file specified by 'filename' for reading (mode "r").
- Use fopen to open the file.
- If the file opening fails, display an error message and exit the program.
Step 5: Print "Content of the file '[filename]':".
Step 6: Read each character from the file until the end of file (EOF) using a while loop.
- Read a character using fgetc.
- If the character is not EOF, print it to the console using putchar.
Step 7: Close the file using fclose.
Step 8: Stop.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;

Reg No: 2127230701020 Page No:100


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
char filename[100];
char ch;
printf("Enter the filename to read: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
printf("Content of the file '%s':\n", filename);
while ((ch = fgetc(file)) != EOF)
{
putchar(ch);
}
fclose(file);
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:101


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 10(3)
Date:
Question: Read <roll, Name,GPA> of a student from console and write into a file student.txt
Aim: To read <roll, Name,GPA> of a student from console and write into a file student.txt
Algorithm:
Step 1: Start
Step 2: Declare variables:
- file: FILE pointer to handle file operations.
- student: Structure to store student details (roll, name, GPA).
Step 3: Open the file "student.txt" for writing (mode "w").
- Use fopen to open the file.
- If the file opening fails, display an error message and exit the program.
Step 4: Display "Enter Roll Number: ".
- Read and store the input in student.roll.
Step 5: Display "Enter Name: ".
- Read and store the input in student.name (assuming the name does not contain spaces).
Step 6: Display "Enter GPA: ".
- Read and store the input in student.GPA.
Step 7: Write student details into the file using fprintf.
- Use fprintf to write the details in the format "<roll, name, GPA>".
Step 8: Close the file using fclose.
Step 9: Stop.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Student {
int roll;
char name[50];
float GPA;
};

Reg No: 2127230701020 Page No:102


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
int main(){
FILE *file;
struct Student student;
file = fopen("student.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
printf("Enter Roll Number: ");
scanf("%d", &student.roll);
printf("Enter Name: ");
getchar();
scanf("%[^\n]", student.name);
printf("Enter GPA: ");
scanf("%f", &student.GPA);
fprintf(file, "<%d, %s, %.2f>", student.roll, student.name, student.GPA);
fclose(file);
printf("The content has been writen on to the file student.txt");
return 0;
}
Output:

Student.txt

Result:

Reg No: 2127230701020 Page No:103


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 10(4)
Date:
Question: Copy the contents of student.txt to new_student.txt
Aim: To copy the contents of student.txt to new_student.txt
Algorithm:
Step 1: Start
Step 2: Declare variables:
- sourceFile: FILE pointer for the source file.
- destinationFile: FILE pointer for the destination file.
- ch: Variable to store each character read from the source file.
Step 3: Open the source file "student.txt" for reading (mode "r").
- Use fopen to open the source file.
- If the source file opening fails, display an error message and exit the program.
Step 4: Check if the source file opened successfully.
Step 5: Open the destination file "new_student.txt" for writing (mode "w").
- Use fopen to open the destination file.
- If the destination file opening fails, display an error message, close the source file, and exit.
Step 6: Check if the destination file opened successfully.
Step 7: Read each character from the source file until the end of file (EOF).
- Read a character using fgetc.
- If the character is not EOF, write it to the destination file using fputc.
Step 8: Close both the source and destination files using fclose.
Step 9: Display "Contents copied from student.txt to new_student.txt".
Step 10: Stop.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *sourceFile, *destinationFile;

Reg No: 2127230701020 Page No:104


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
char ch;
sourceFile = fopen("student.txt", "r");
if (sourceFile == NULL) {
perror("Error opening source file");
return 1;
}
destinationFile = fopen("new_student.txt", "w");
if (destinationFile == NULL) {
perror("Error opening destination file");
fclose(sourceFile);
return 1;
}
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}
fclose(sourceFile);
fclose(destinationFile);
printf("Contents copied from student.txt to new_student.txt\n");
return 0;
}
Output:

new_student.txt

Result:

Reg No: 2127230701020 Page No:105


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exercise 11 Enumerated data types, macros, and storage classes

Exp No: 11(1)


Date:
Question: Create an enumerator for months of a year, days of a week, and display them.
Aim: To create an enumerator for months of a year, days of a week, and display them.
Algorithm:
Step 1: Start
Step 2: Declare enumerated data types for months and days:
- Enum for months: JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
- Enum for days: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
Step 3: Declare function prototypes for getMonthName and getDayName:
- const char* getMonthName(enum Months month);
- const char* getDayName(enum Days day);
Step 4: Define the getMonthName function:
- Switch on the month argument and return the corresponding month name.
Step 5: Define the getDayName function:
- Switch on the day argument and return the corresponding day name.
Step 6: In the main function:
a. Display "Months of the Year:".
b. Iterate over each month using the enum Months and display its name.
c. Display "Days of the Week:".
d. Iterate over each day using the enum Days and display its name.
Step 7: Stop.
Code:
#include <stdio.h>
enum Months
{
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,

Reg No: 2127230701020 Page No:106


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
};
enum Days
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
};
const char* getMonthName(enum Months month);
const char* getDayName(enum Days day);
int main()
{
printf("Months of the Year:\n");
for (enum Months month = JANUARY; month <= DECEMBER; ++month)
{
printf("%d. %s\n", month + 1, getMonthName(month));
}
printf("\nDays of the Week:\n");
for (enum Days day = SUNDAY; day <= SATURDAY; ++day)
{
printf("%d. %s\n", day + 1, getDayName(day));
}
return 0;
}
const char* getMonthName(enum Months month)
{
switch (month) {
case JANUARY: return "January";
case FEBRUARY: return "February";
case MARCH: return "March";
case APRIL: return "April";
case MAY: return "May";

Reg No: 2127230701020 Page No:107


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
case JUNE: return "June";
case JULY: return "July";
case AUGUST: return "August";
case SEPTEMBER: return "September";
case OCTOBER: return "October";
case NOVEMBER: return "November";
case DECEMBER: return "December";
default: return "Invalid Month";
}
}
const char* getDayName(enum Days day)
{
switch (day) {
case SUNDAY: return "Sunday";
case MONDAY: return "Monday";
case TUESDAY: return "Tuesday";
case WEDNESDAY: return "Wednesday";
case THURSDAY: return "Thursday";
case FRIDAY: return "Friday";
case SATURDAY: return "Saturday";
default: return "Invalid Day";
}
}

Reg No: 2127230701020 Page No:108


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:109


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 11(2)
Date:
Question: Calculate the square and cube of a number using macro functions.
Aim: To calculate the square and cube of a number using macro functions.
Algorithm:
Step 1: Start
Step 2: Declare variables:
- num: Variable to store the input number.
Step 3: Display "Enter a number".
- Read and store the input number in the variable num.
Step 4: Calculate and display the square using the SQUARE macro:
a. Display "Square of num is SQUARE(num)".
Step 5: Calculate and display the cube using the CUBE macro:
a. Display "Cube of num is CUBE(num)".
Step 6: Stop.
Code:
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define CUBE(x) ((x) * (x) * (x))
int main()
{
double num;
printf("Enter a number: ");
scanf("%lf", &num);
printf("Square of %.2lf is %.2lf\n", num, SQUARE(num));
printf("Cube of %.2lf is %.2lf\n", num, CUBE(num));
return 0;
}

Reg No: 2127230701020 Page No:110


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB

Output:

Result:

Reg No: 2127230701020 Page No:111


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
Exp No: 11(3)
Date:
Question: SBI generates tickets at its automated counter machine starting from 100. Each user
gets a subsequent ticket number. Demonstrate this using appropriate storage class.
Aim: To generates tickets for SBI at its automated counter machine starting from 100. Each user
gets a subsequent ticket number. Demonstrate this using appropriate storage class.
Algorithm:
Step 1: Start
Step 2: Declare variables:
- numTickets: Variable to store the number of tickets entered by the user.
Step 3: Get the number of tickets from the user:
- Display "Enter the number of tickets".
- Read and store the input in the variable numTickets.
Step 4: Display ticket numbers for the specified number of tickets:
a. Display "Ticket Numbers:".
b. Use a loop to iterate over the specified number of tickets.
c. Call getNextTicketNumber function for each iteration and display the user's ticket number.
Step 5: Stop.
Code:
#include <stdio.h>
int getNextTicketNumber()
{
static int ticketCounter = 100;
return ticketCounter++;
}
int main()
{
int numTickets;
printf("Enter the number of tickets: ");
scanf("%d", &numTickets);

Reg No: 2127230701020 Page No:112


IT22111 PROGRAMMING FOR PROBLEM SOLVING LAB
printf("Ticket Numbers:\n");
for (int i = 0; i < numTickets; ++i)
{
printf("User %d Ticket: %d\n", i + 1, getNextTicketNumber());
}
return 0;
}
Output:

Result:

Reg No: 2127230701020 Page No:113

You might also like