C Programming Lab Exercises Guide
C Programming Lab Exercises Guide
Example 2:
#include <stdio.h>
void main()
{
int a,b,sum;
printf("Enter a, b: ");
scanf("%d%d", &a,&b);
sum = a+b;
printf("Sum = %d\n", sum);
}
Input: Enter a, b: 50 100
Output: Sum = 150
1
Lab Record for Programming for Problem Solving
2) Write a simple C program that prints the results of all the operators available in C. Read
required operand values from standard input
#include <stdio.h>
void main()
{
int a, b;
printf("Enter a,b: ");
scanf("%d%d", &a,&b);
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("a == b: %d\n", a == b);
printf("a != b: %d\n", a != b);
printf("a > b : %d\n", a > b);
printf("a < b : %d\n", a < b);
printf("a >= b: %d\n", a >= b);
printf("a <= b: %d\n", a <= b);
printf("a++ = %d\n", ++a); //pre increment
printf("b-- = %d\n", --b); //pre decrement
}
Input:
Enter a, b: 10 4
Output:
a + b = 14
a-b=6
a * b = 40
a/b=2
a%b=2
a == b: 0
a != b: 1
a>b:1
a<b:0
a >= b: 1
a <= b: 0
a++ = 11
b-- = 3
2
Lab Record for Programming for Problem Solving
3) Write the program for the simple, compound interest.
#include <stdio.h>
#include <math.h> // For pow() function
void main()
{
float p, t, r, q, amount, si, ci;
printf("Enter the principal amount: ");
scanf("%f", &p);
printf("Enter the time (in years): ");
scanf("%f", &t);
printf("Enter the annual interest rate: ");
scanf("%f", &r);
q = r/100;
si = p * t * q;
amount = p * pow((1 + q), t);
ci = amount - p;
printf("Simple Interest = %f\n", si);
printf("Compound Interest = %f\n", ci);
}
Input:
Enter the principal amount: 10000
Enter the time (in years): 2
Enter the annual interest rate: 5
Output:
Simple Interest = 1000.00
Compound Interest = 1025.00
3
Lab Record for Programming for Problem Solving
4) Ramesh works as a Mess supervisor in an engineering college hostel, where different
messes are available based on the years. The student count varies daily in all the hostels
due to continuous holidays. Since Ramesh is in charge of the cooking team, he faces
difficulty in calculating the quantity of food that needs to be prepared because of the
varying student count. Even if a small quantity of food is prepared by the cooking team, it
should be divided equally among the number of messes. Ramesh needs automated software
to identify the amount of food available (in the number of packets) and the Mess count.
Can you help him divide the food equally and also calculate the remaining quantity of food
that will be available after sharing the food equally?
#include <stdio.h>
void main()
{
int p, m, q, r;
printf("Enter the total number of food packets available: ");
scanf("%d", &p);
printf("Enter the total number of messes: ");
scanf("%d", &m);
q = p / m;
r = p % m;
printf("Food packets each mess will receive: %d\n", q);
printf("Remaining food packets: %d\n", r);
}
Input:
Enter the total number of food packets available: 483
Enter the total number of messes: 6
Output:
Food packets each mess will receive: 80
Remaining food packets: 3
4
Lab Record for Programming for Problem Solving
5) Tina's brother gave her a fun mathematical challenge involving a chessboard-like grid.
The task is to determine the total number of squares that can be found in a board, where
each square is . However, Tina needs to count not only the smallest squares but also the
larger squares that can be formed on the board.
For example, on a board, there are 9 squares of size, 4 squares of size, and 1 square of size,
resulting in a total of 14 squares.
Your task is to help Tina calculate the total number of squares of all possible sizes on the
board.
#include <stdio.h>
void main()
{
int n, ts;
printf("Enter the size of the board: ");
scanf("%d", &n);
ts = (n * (n + 1) * (2 * n + 1)) / 6;
printf("Total number of squares: %d\n", ts);
}
Input:
Enter the size of the board: 4
Output:
Total number of squares: 30
5
Lab Record for Programming for Problem Solving
6) Bhushan is playing chess on an N × M grid, where all the cells start uncolored. His score
starts at zero, and on each turn, he picks an uncolored cell and colors it. The score for that
turn is equal to the number of already colored neighboring cells (cells that share a side
with it).
The game continues until all cells are colored. Bhushan's final score is the total of all the
points he earned in each step. He wants to maximize his final score. Can you help him
figure out the highest score he can achieve?
#include <stdio.h>
void main()
{
int n, m, s;
printf("Enter the number of rows and columns: ");
scanf("%d%d", &n, &m);
s = n*(m-1) + m*(n-1);
printf("Maximum score: %d\n", s);
}
Input:
Enter the number of rows and columns: 8 8
Output:
Maximum score: 112
6
Lab Record for Programming for Problem Solving
7) Surya used to wear a smartwatch when he was on the treadmill and during cycling.
Surya's smartwatch displays the total workout time in seconds. But Surya would like to
know the time he spent on the workout in H:M:S format.
Can you help Surya in knowing the time he spent on the workout in the prescribed format?
#include <stdio.h>
void main()
{
int t, h, m, s;
printf("Enter total workout time in seconds: ");
scanf("%d", &t);
h = t / 3600;
m = (t % 3600) / 60;
s = t % 60;
printf("Workout Duration: %02d:%02d:%02d \n", h, m, s);
}
Input:
Enter total workout time in seconds: 3672
Output:
Workout Duration: 01:01:12
7
Lab Record for Programming for Problem Solving
8) Flipkart has announced its year-end stock clearance sale, including a contest where users
answering the questions can win a Moto One Power for free. The task is to display the sum
of the first three powers of the given number. Pawan is eager to win a Moto One Power,
and if you help him solve the task, he may get his favourite mobile. Can you assist him?
#include <stdio.h>
#include <math.h> // For pow() function
void main()
{
int n, sum;
printf("Enter a number: ");
scanf("%d", &n);
sum = pow(n, 1) + pow(n, 2) + pow(n, 3);
printf("Sum of first three powers is: %d\n", sum);
}
Input:
Enter a number: 5
Output:
Sum of first three powers is: 155
8
Lab Record for Programming for Problem Solving
9) Write a program for finding the max and min from the three numbers using ternary
operator
#include <stdio.h>
void main()
{
int a, b, c, max, min;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
min = (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
printf("Maximum = %d\n", max);
printf("Minimum = %d\n", min);
}
Input:
Enter three numbers: 15 6 18
Output:
Maximum = 18
Minimum = 6
9
Lab Record for Programming for Problem Solving
10) Write a C program to evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A++ + ++B - --A
d. (i++) + (++i)
#include <stdio.h>
void main()
{
int a, b, c, d, e, f, g, i, x, y, z, w;
printf("Enter values for a, b, c, d, e, f, g, i:\n");
scanf("%d %d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g, &i);
x= a + b*c + (d*e) + f*g;
y = (a / b) * c - b + (a * d) / 3;
z = (a++) + (++b) - (--a);
w = (i++) + (++i);
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("z = %d\n", z);
printf("w = %d\n", w);
}
Input:
Enter values for a, b, c, d, e, f, g, i: 5 2 3 4 5 6 7 1
Output:
x = 73
y = 10
z=3
w=4
10
Lab Record for Programming for Problem Solving
PROGRAMS USING CONTROL STRUCTURES
11) Caleb and Irfan are purchasing apples that are priced according to their size, but their
budget is limited. To ensure they stay within budget, they plan to choose one small
(apple1), one medium (apple2), and one large (apple3) apple.
Can you help them determine if their choices fit into their budget? Check the condition: if
apple2 is greater than apple1 and apple3 is greater than apple2. If this condition is true
print "Fit into Budget"; otherwise, print "Doesn't fit into Budget.
#include <stdio.h>
void main()
{
int apple1, apple2, apple3;
printf("Enter price of small apple (apple1): ");
scanf("%d", &apple1);
printf("Enter price of medium apple (apple2): ");
scanf("%d", &apple2);
printf("Enter price of large apple (apple3): ");
scanf("%d", &apple3);
if (apple2 > apple1 && apple3 > apple2)
printf("Fit into Budget\n");
else
printf("Doesn't fit into Budget\n");
}
Input:
Enter price of small apple (apple1): 5
Enter price of medium apple (apple2): 10
Enter price of large apple (apple3): 15
11
Lab Record for Programming for Problem Solving
12) Agathiyan is the Chief In charge of carrying out the World Economic Survey in India. As a
part of the survey, his team collected the salaries of the citizens of India. The Salaries of
different people are in different number of digits.
Now Agathiyan would like to classify the earnings of the citizen based on the number of
digits of his/her salary into 5 different categories as follows:
1. Insufficient Earning
2. Very Low Earning
3. Low Earning
4. Sufficient Earning
5. High Earning
Can you help him do the above classification if he gives the salary of the particular person
to you as input?
#include <stdio.h>
void main()
{
int salary;
printf("Enter the salary: ");
scanf("%d", &salary);
if (salary >= 0 && salary <= 9)
printf("Insufficient Earning\n");
else if (salary >= 10&& salary <= 99)
printf("Very Low Earning\n");
else if (salary >= 100 && salary <= 999)
printf("Low Earning\n");
else if (salary >= 1000 && salary <= 9999)
printf("Sufficient Earning\n");
else if (salary >= 10000)
printf("High Earning\n");
else
printf("Invalid salary input\n");
}
12
Lab Record for Programming for Problem Solving
13) Write a C program that declares Class awarded for a given percentage of marks, where
mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=70% =
Distinction. Read percentage from standard input.
#include <stdio.h>
void main()
{
float percentage;
printf("Enter the percentage of marks: ");
scanf("%f", &percentage);
if (percentage < 40)
printf("Class awarded: Failed\n");
else if ((percentage >= 40)&&(percentage < 60))
printf("Class awarded: Second Class\n");
else if ((percentage >= 61)&&(percentage < 70))
printf("Class awarded: First Class\n");
else if (percentage >= 70)
printf("Class awarded: Distinction\n");
else
printf("Invalid Input\n");
}
Input:
Enter the percentage of marks: 85.2
Output:
Class awarded: Distinction
13
Lab Record for Programming for Problem Solving
14) Once upon a time in the small village of Codeton, a diligent programmer named Alex was
working on a task for the village elders. The elders wanted a program that could take an
integer input representing the day of the week and return the corresponding day's name.
The challenge was to ensure that the program gracefully handled all possible inputs. Alex,
known for their meticulous coding skills, decided to use a switch-case statement for this
task. Can you help Alex to complete this task?
#include <stdio.h>
void main()
{
int day;
printf("Enter a number: ");
scanf("%d", &day);
switch(day)
{
case 1: printf("Monday\n");
break;
case 2: printf("Tuesday\n");
break;
case 3: printf("Wednesday\n");
break;
case 4: printf("Thursday\n");
break;
case 5: printf("Friday\n");
break;
case 6: printf("Saturday\n");
break;
case 7: printf("Sunday\n");
break;
default: printf("Invalid input\n");
}
}
Input:
Enter a number: 1
Output:
Monday
14
Lab Record for Programming for Problem Solving
15) Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result. (Consider the operators +,-,*, /, % and
use Switch Statement).
#include <stdio.h>
void main()
{
int a,b,c;
char n;
printf("Enter a,b: ");
scanf("%d%d", &a,&b);
printf("Enter your operator: ");
scanf(" %c", &n); // Note the space before %c
switch(n)
{
case '+':
printf("Result = %d\n", a + b);
break;
case '-':
printf("Result = %d\n", a - b);
break;
case '*':
printf("Result = %d\n", a * b);
break;
case '/':
printf("Result = %d\n", a / b);
break;
case '%':
printf("Result = %d\n", a % b);
break;
default:
printf("Invalid operator.\n");
}
}
Input:
Enter a,b: 6 3
Enter your operator: *
Output:
Result = 18
15
Lab Record for Programming for Problem Solving
16) Write a program to display the cube of the numbers up to a given integer
#include <stdio.h>
void main()
{
int n, i = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n)
{
printf("Cube of %d = %d\n", i, i * i * i);
i++;
}
}
Input:
Enter a number: 5
Output:
Cube of 1 = 1
Cube of 2 = 8
Cube of 3 = 27
Cube of 4 = 64
Cube of 5 = 125
16
Lab Record for Programming for Problem Solving
17) Write a C program to find the sum of individual digits of a positive integer
#include <stdio.h>
void main()
{
int n, sum = 0, r;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (n != 0)
{
r = n % 10; // Get the last digit
sum = sum + r; // Add the digit to the sum
n = n / 10; // Remove the last digit from the number
}
printf("Sum of the individual digits: %d\n", sum);
}
17
Lab Record for Programming for Problem Solving
18) Write a C program to test given number is palindrome or not
#include <stdio.h>
void main()
{
int n, n1, rev = 0, r;
printf("Enter an integer: ");
scanf("%d", &n);
n1 = n;
while (n != 0)
{
r = n % 10; // Get the last digit
rev = (rev * 10) + r; // Build the reversed number
n = n / 10; // Remove the last digit from the number
}
if (rev == n1)
printf("%d is a palindrome number.\n", n1);
else
printf("%d is not a palindrome number.\n", n1);
}
18
Lab Record for Programming for Problem Solving
19) Write a program that prints a multiplication table for a given number and the number of
rows in the table. For example, for a number 5 and rows = 3, the output should be:
5x1=5
5 x 2 = 10
5 x 3 = 15
#include <stdio.h>
void main()
{
int n, rows, i;
printf("Enter the number for the multiplication table: ");
scanf("%d", &n);
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++)
printf("%d x %d = %d\n", n, i, n * i);
}
Input:
Enter the number for the multiplication table: 9
Enter the number of rows: 5
Output:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
19
Lab Record for Programming for Problem Solving
20) Jagadeesh is heading to the city of Vizag for work and is in search of a hotel room with a
prime number. He is interested in creating an app in C that can determine whether a given
room number is prime or not. Can you assist Jagadeesh in developing this C program?
#include <stdio.h>
void main()
{
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
20
Lab Record for Programming for Problem Solving
21) A perfect number is a positive integer that is equal to the sum of its positive divisors,
excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, print True if n is a perfect number, otherwise print False.
#include <stdio.h>
void main()
{
int n, i, sum = 0;
int mn, mx;
printf("Input the number : ");
scanf("%d", &n);
for (i = 1; i < n; i++)
{
if (n % i == 0) // If 'i' is a divisor of 'n'.
sum = sum + i;
}
if (sum == n)
printf("\n Number is perfect.");
else
printf("\n Number is not perfect.");
}
21
Lab Record for Programming for Problem Solving
22) Write a C program that prints the first N numbers of the Fibonacci series.
#include <stdio.h>
void main()
{
int n, first = 0, second = 1, next, i;
printf("Enter the number of terms (N) for the Fibonacci series: ");
scanf("%d", &n);
printf("%d %d", first, second);
for (i = 2; i < n; i++)
{
next = first + second;
printf(" %d", next);
first = second;
second = next;
}
}
Input: Enter the number of terms (N) for the Fibonacci series: 9
Output: 0 1 1 2 3 5 8 13 21
22
Lab Record for Programming for Problem Solving
23) Write a program that takes the binary representation of an unsigned integer and prints the
number of '1' bits it has (also known as the Hamming weight).
#include <stdio.h>
void main()
{
unsigned int num, temp;
int count=0;
printf("Enter an unsigned integer: ");
scanf("%u", &num);
temp = num;
while(temp)
{
if(temp % 2) count++;
temp /= 2;
}
printf("Number of 1 bits = %d\n", count);
}
23
Lab Record for Programming for Problem Solving
24) Write a C program to generate all the prime numbers between 1 and n.
#include <stdio.h>
#include <math.h>
void main()
{
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i=2; i<=n; i++)
{
int flag=0;
for(int j=2; j<=sqrt(i); j++)
{
if(i % j == 0)
{
flag=1;
break;
}
}
if(flag==0)
printf("%d ", i);
}
printf("\n");
}
Input: Enter n: 30
Output: 2 3 5 7 11 13 17 19 23 29
24
Lab Record for Programming for Problem Solving
25) Write a C Program to print the following pattern
1
22
333
4444
#include <stdio.h>
void main()
{
int i, j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
printf("%d", i);
printf("\n");
}
}
1
23
456
78910
#include <stdio.h>
void main()
{
int val=1, i, j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
printf("%d", val++);
printf("\n");
}
}
25
Lab Record for Programming for Problem Solving
*
***
*****
*******
#include <stdio.h>
void main()
{
int n = 4, i, j;
for(i=1; i<=n; i++)
{
for(j=1; j<=n-i; j++)
printf(" ");
for(j=1; j<=2*i-1; j++)
printf("*");
printf("\n");
}
}
26
Lab Record for Programming for Problem Solving
Programs using Arrays and Strings
26) Write a C program to find the minimum, maximum, sum and average in an array of
integers.
#include <stdio.h>
void main()
{
int n, arr[100], i, min, max, sum;
float avg;
printf("Enter number of values: ");
scanf("%d", &n);
printf(“Enter the values: “);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
min=arr[0];
max=arr[0];
sum=0;
for(i=0;i<n;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
sum = sum + arr[i];
}
avg = (float) sum/n;
printf("Min = %d\n”, min);
printf("Max = %d\n”, max);
printf("Sum = %d\n”, sum);
printf("Average = %.2f\n", avg);
}
27
Lab Record for Programming for Problem Solving
27) Write a C program to square the elements that are at even positions and cube the elements
that are at odd positions in an array.
#include <stdio.h>
#include <math.h>
void main()
{
int n, arr[100], i;
printf("Enter number of values: ");
scanf("%d",&n);
printf(“Enter the values: “);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
if((i+1)%2==0)
arr[i]=pow(arr[i],2);
else arr[i]=pow(arr[i],3);
}
printf("Modified Array: ");
for(i=0;i<n;i++)
printf("%d ", arr[i]);
printf("\n");
}
28
Lab Record for Programming for Problem Solving
28) Write a C program to move all the negative elements to one side (i.e., to the left) of the
array while maintaining the original order of appearance.
#include <stdio.h>
void main()
{
int n, i, arr[100], neg[100], pos[100], ni = 0, pi = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter the elements:");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
if (arr[i] < 0)
neg[ni++] = arr[i]; // store negative numbers
else
pos[pi++] = arr[i]; // store non-negative numbers
}
// Combine back into original array
for (i = 0; i < ni; i++)
arr[i] = neg[i];
for (int j = 0; j < pi; j++)
arr[ni + j] = pos[j];
printf("Array after moving negatives to left:");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
}
29
Lab Record for Programming for Problem Solving
29) Write a C program that finds the greatest number from each row of a matrix
#include <stdio.h>
void main()
{
int rows, cols, matrix[10][10], i, j, max;
printf("Enter number of rows and columns: ");
scanf("%d%d", &rows, &cols);
printf("Enter the matrix elements:\n");
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
scanf("%d", &matrix[i][j]);
printf("\nGreatest element in each row:\n");
for (i = 0; i < rows; i++)
{
max = matrix[i][0]; // assume first element is max
for (j = 1; j < cols; j++)
{
if (matrix[i][j] > max)
max = matrix[i][j];
}
printf("Row %d: %d\n", i + 1, max);
}
}
Input:
Enter number of rows: 3
Enter number of columns: 4
Enter the matrix elements:
1632
9047
6281
Output:
Greatest element in each row:
Row 1: 6
Row 2: 9
Row 3: 8
30
Lab Record for Programming for Problem Solving
30) Write a C program to find addition of two matrices of order m x n.
#include <stdio.h>
void main()
{
int m,n, a[10][10], b[10][10], c[10][10], i, j;
printf("Enter rows and columns: ");
scanf("%d%d",&m,&n);
printf("Enter first matrix: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Enter second matrix: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("Sum Matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
Input:
Enter rows and columns: 2 2
Enter first matrix:
12
34
Enter second matrix:
56
78
Output:
Sum Matrix:
68
10 12
31
Lab Record for Programming for Problem Solving
31) Write a C program to find multiplication of two matrices of order m x n ,p x q.
#include <stdio.h>
void main()
{
int m,n,p,q, a[10][10], b[10][10], c[10][10], i, j, k;
printf("Enter dimensions of first matrix: ");
scanf("%d %d",&m,&n);
printf("Enter first matrix:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Enter dimensions of second matrix: ");
scanf("%d %d",&p,&q);
printf("Enter second matrix:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
if(n!=p)
printf("Matrix multiplication not possible\n");
else
{
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]+=a[i][k]*b[k][j];
}
printf("Product Matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
}
32
Lab Record for Programming for Problem Solving
Input: Enter dimensions of first matrix: 2 3
Enter first matrix:
1
2
3
4
5
6
Enter dimensions of second matrix: 3 2
Enter second matrix:
1
2
3
4
5
6
Output:
Product Matrix:
22 28
49 64
33
Lab Record for Programming for Problem Solving
32) Write a C program to count the number of digits, spaces, special characters, and alphabets
in a string.
#include <stdio.h>
void main()
{
char str[200];
int i, alphabets = 0, digits = 0, spaces = 0, special = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++)
{
if ((str[i] >= 'a' && str[i] <= 'z') ||
(str[i] >= 'A' && str[i] <= 'Z'))
alphabets++;
else if (str[i] >= '0' && str[i] <= '9')
digits++;
else if (str[i] == ' ')
spaces++;
else if (str[i] != '\n')
special++;
}
printf("\nAlphabets: %d", alphabets);
printf("\nDigits : %d", digits);
printf("\nSpaces : %d", spaces);
printf("\nSpecial : %d\n", special);
}
Output: Alphabets: 10
Digits : 3
Spaces : 2
Special : 3
34
Lab Record for Programming for Problem Solving
33) Write a C program to count the frequency of each character in a given string.
#include <stdio.h>
#include <string.h>
void main()
{
char str[100], ch;
int i, freq[256] = {0}; // Array for all ASCII characters
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++)
{
ch = str[i];
freq[ch]++;
}
printf("\nCharacter Frequencies:\n");
for (i = 0; i < 256; i++)
{
if (freq[i] > 0 && i != '\n')
{
printf("'%c' = %d\n", i, freq[i]);
}
}
}
35
Lab Record for Programming for Problem Solving
34) Write a C program to determine if the given string is a palindrome or not (Spelled same in
both directions with or without a meaning like madam, civic, noon, abcba, etc.)
#include <stdio.h>
#include <string.h>
void main( )
{
char str[100], rev[100];
printf("Enter a string: ");
scanf("%s",&str);
strcpy(rev, str); // Copy original string
strrev(rev); // Reverse the copied string
if (strcmp(str, rev) == 0)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
}
36
Lab Record for Programming for Problem Solving
35) Write a C program to insert a sub-string into a given main string from a given position.
#include <stdio.h>
#include <string.h>
void main()
{
char mainStr[200], subStr[100], result[300];
int pos, i = 0, j = 0, k = 0;
printf("Enter the main string: ");
fgets(mainStr, sizeof(mainStr), stdin);
printf("Enter the substring to insert: ");
fgets(subStr, sizeof(subStr), stdin);
mainStr[strcspn(mainStr, "\n")] = '\0'; // Remove newline characters from fgets
subStr[strcspn(subStr, "\n")] = '\0';
printf("Enter the position to insert (0-based index): ");
scanf("%d", &pos);
while (i < pos && mainStr[i] != '\0') // Copy characters before position
{
result[k++] = mainStr[i++];
}
while (subStr[j] != '\0') // Insert substring
{
result[k++] = subStr[j++];
}
while (mainStr[i] != '\0') // Copy remaining characters of main string
{
result[k++] = mainStr[i++];
}
result[k] = '\0';
printf("\nResulting string: %s\n", result);
}
37
Lab Record for Programming for Problem Solving
36) Write a C program to delete n character from a given position in a given string.
#include <stdio.h>
#include <string.h>
void main()
{
char str[200];
int pos, n, i, len;
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline from fgets
printf("Enter the position to delete from (0-based index): ");
scanf("%d", &pos);
printf("Enter number of characters to delete: ");
scanf("%d", &n);
len = strlen(str);
38
Lab Record for Programming for Problem Solving
37) Write a C program to count the lines, words and characters in a given text.
#include <stdio.h>
void main()
{
char text[500];
int i = 0, lines = 1, words = 1, chars = 0;
printf("Enter text (end input with ENTER):\n");
fgets(text, sizeof(text), stdin);
while (text[i] != '\0')
{
chars++;
if (text[i] == ' ' || text[i] == '\t')
words++;
if (text[i] == '\n')
lines++;
i++;
}
printf("\nCharacters: %d\n", chars);
printf("Words: %d\n", words);
printf("Lines: %d\n", lines);
}
Output: Characters: 22
Words: 5
Lines: 2
39
Lab Record for Programming for Problem Solving
38) Lokesh usually likes to play cricket, but now, he is bored of playing it too much, so he is
trying new games with strings. Lokesh's friend Tina gave him binary strings S and R, each
with length N, and told him to make them identical. However, unlike Tina, Lokesh does not
have any superpower and Tina lets Lokesh perform only operations of one type: choose
any pair of integers (i,j) such that 1≤i,j≤N and swap the i-th and j-th character of S. He
may perform any number of operations (including zero). For Lokesh, this is much harder
than cricket and he is asking for your help.
Tell him whether it is possible to change the string S to the target string R only using
operations of the given type.
#include <stdio.h>
#include <string.h>
void main()
{
char S[200], R[200];
int countS0 = 0, countS1 = 0, countR0 = 0, countR1 = 0;
printf("Enter string S: ");
scanf("%s", S);
printf("Enter string R: ");
scanf("%s", R);
if (strlen(S) != strlen(R))
{
printf("NO\n");
return 0;
}
for (int i = 0; S[i] != '\0'; i++) // Count 0s and 1s in S
{
if (S[i] == '0')
countS0++;
else
countS1++;
}
for (int i = 0; R[i] != '\0'; i++) // Count 0s and 1s in R
{
if (R[i] == '0')
countR0++;
else
countR1++;
}
if (countS0 == countR0 && countS1 == countR1) // Compare counts
printf("YES\n");
40
Lab Record for Programming for Problem Solving
else
printf("NO\n");
}
Output: YES
41
Lab Record for Programming for Problem Solving
39) There are N students standing in a row and numbered 1 through N from left to right. You
are given a string S with length N, where for each valid i, the i-th character of S is 'g'. If the
i-th student is a girl or 'b' if this student is a boy. Students standing next to each other in
the row are friends. The students are asked to form pairs for a dance competition. Each
pair must consist of a boy and a girl. Two students can only form a pair if they are friends.
Each student can only be part of at most one pair. What is the maximum number of pairs
that can be formed?
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int n, i, pairs = 0;
printf("Enter number of students: ");
scanf("%d", &n);
printf("Enter string (g for girl, b for boy): ");
scanf("%s", s);
for (i = 0; i < n - 1; i++)
{
// Check if adjacent characters form a valid pair
if ((s[i] == 'g' && s[i+1] == 'b') || (s[i] == 'b' && s[i+1] == 'g'))
{
pairs++;
i++; // skip the next student because they are already paired
}
}
printf("\nMaximum pairs = %d\n", pairs);
}
42
Lab Record for Programming for Problem Solving
40) Given a string consisting of words and spaces, print the length of the last word in the
string. A word is a maximal substring consisting of non-space characters only.
#include <stdio.h>
#include <string.h>
void main()
{
char str[200];
int length, i, count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
length = strlen(str);
if (str[length - 1] == '\n')
{
str[length - 1] = '\0';
length--;
}
i = length - 1;
while (i >= 0 && str[i] == ' ')
i--;
while (i >= 0 && str[i] != ' ')
{
count++;
i--;
}
printf("Length of last word: %d\n", count);
}
43
Lab Record for Programming for Problem Solving
41) You are given an array/list of box sizes sorted in ascending order and an integer
representing the size of an item. Your task is to write a code to find the best-fit box size for
the given item.
#include <stdio.h>
void main()
{
int n, item, i, bestFit = -1, boxes[100];
printf("Enter number of box sizes: ");
scanf("%d", &n);
printf("Enter box sizes (in ascending order):");
for (i = 0; i < n; i++)
scanf("%d", &boxes[i]);
printf("Enter item size: ");
scanf("%d", &item);
for (i = 0; i < n; i++)
{
if (boxes[i] >= item)
{
bestFit = boxes[i];
break;
}
}
if (bestFit == -1)
printf("No box can fit the item.\n");
else
printf("Best-fit box size: %d\n", bestFit);
}
44
Lab Record for Programming for Problem Solving
42) Given a string, find the first non-repeating character in it and print its index. If it does not
exist, print -1.
#include <stdio.h>
#include <string.h>
void main()
{
char str[200];
int freq[256] = {0};
int i, index = -1;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
for (i = 0; str[i] != '\0'; i++)
freq[(unsigned char)str[i]]++;
for (i = 0; str[i] != '\0'; i++)
{
if (freq[(unsigned char)str[i]] == 1)
{
index = i;
break;
}
}
printf("Index of first non-repeating character: %d\n", index);
}
45
Lab Record for Programming for Problem Solving
43) Write a C program that implements the Bubble sort method to sort a given list of integers
in ascending order.
#include <stdio.h>
void main()
{
int n, arr[100], i, j, temp;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("Sorted array: ");
for(i=0;i<n;i++)
printf("%d ", arr[i]);
printf("\n");
}
46
Lab Record for Programming for Problem Solving
PROGRAMS USING FUNCTIONS AND RECURSION
44) Write a C program to swap to numbers using call by value.
#include <stdio.h>
void main()
{
int a, b;
void swap(int a, int b);
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("\nBefore calling swap:\n");
printf("a = %d, b = %d\n", a, b);
swap(a, b);
printf("\nAfter calling swap (in main):\n");
printf("a = %d, b = %d\n", a, b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("\nInside swap function:\n");
printf("a = %d, b = %d\n", a, b);
}
Output:
Before calling swap:
a = 15, b = 30
47
Lab Record for Programming for Problem Solving
45) In the coding town of Programland, Jake, a budding coder, has crafted a simple geometry
calculator in C. Jake's program features easy-to-use functions that magically calculate the
areas of common shapes such as squares, rectangles, triangles, and circles. Each shape has
its own dedicated chapter, turning the program into an accessible adventure.
John, a student, found joy in using Jake's creation and is now inspired to create his own
geometry calculator. Can you help John write the code to build this geometric calculator?
#include <stdio.h>
void main()
{
int choice;
float side, length, width, base, height, radius;
float areaOfSquare(float side);
float areaOfRectangle(float length, float width);
float areaOfTriangle(float base, float height);
float areaOfCircle(float radius);
printf("Geometry Calculator\n");
printf("1. Area of Square\n");
printf("2. Area of Rectangle\n");
printf("3. Area of Triangle\n");
printf("4. Area of Circle\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter side of square: ");
scanf("%f", &side);
printf("Area of Square = %.2f\n", areaOfSquare(side));
break;
case 2:
printf("Enter length of rectangle: ");
scanf("%f", &length);
printf("Enter width of rectangle: ");
scanf("%f", &width);
printf("Area of Rectangle = %.2f\n", areaOfRectangle(length, width));
break;
case 3:
printf("Enter base of triangle: ");
scanf("%f", &base);
printf("Enter height of triangle: ");
48
Lab Record for Programming for Problem Solving
scanf("%f", &height);
printf("Area of Triangle = %.2f\n", areaOfTriangle(base, height));
break;
case 4:
printf("Enter radius of circle: ");
scanf("%f", &radius);
printf("Area of Circle = %.2f\n", areaOfCircle(radius));
break;
default:
printf("Invalid choice! Please run the program again.\n");
}
}
float areaOfSquare(float side)
{
return side * side;
}
float areaOfRectangle(float length, float width)
{
return length * width;
}
float areaOfTriangle(float base, float height)
{
return 0.5 * base * height;
}
float areaOfCircle(float radius)
{
return 3.14159 * radius * radius;
}
Input:
Geometry Calculator
1. Area of Square
2. Area of Rectangle
3. Area of Triangle
4. Area of Circle
Enter your choice (1-4): 2
Enter length of rectangle: 5
Enter width of rectangle: 6
Output:
Area of Rectangle = 30.00
49
Lab Record for Programming for Problem Solving
46) Imagine you are a software developer working for an educational institution that needs to
automate the process of calculating students' average grades for their performance in three
core subjects: Math, English, and Science. The institution wants a program that can
efficiently calculate these averages to streamline its grading process.
Your task is to design and implement a C program that includes a function called
calculateAverage to compute the average grade for a student's scores in these three subjects.
#include <stdio.h>
void main()
{
float math, english, science, average;
float calculateAverage(float math, float english, float science);
printf("Enter Maths, English, Science grades: ");
scanf("%f%f%f", &math, &english, &science);
average = calculateAverage(math, english, science);
printf("Average Grade: %.2f\n", average);
}
float calculateAverage(float math, float english, float science)
{
return (math + english + science) / 3;
}
50
Lab Record for Programming for Problem Solving
47) Imagine you are working on a payroll management system for a company. As part of the
system, you need to develop a C program that calculates the minimum salary among a
group of employees.
Write a program that prompts the user to input the number of employees and their respective
salaries. Utilize an array to store the salaries and to find and display the minimum salary in
the dataset.
#include <stdio.h>
void main()
{
int n, i, arr[100], minSalary;
int findMinimum(int arr[], int n);
printf("Enter the number of employees: ");
scanf("%d", &n);
printf("Enter the salaries of the employees:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
minSalary = findMinimum(arr, n);
printf("\nThe minimum salary is: %d\n", minSalary);
}
int findMinimum(int arr[], int n)
{
int i, min;
min = arr[0];
for (i = 1; i < n; i++)
{
if (arr[i] < min)
min = arr[i];
}
return min;
}
51
Lab Record for Programming for Problem Solving
48) Write a C program to print the transpose of a matrix using functions.
#include <stdio.h>
void main()
{
int a[10][10], r, c;
void readMatrix(int a[10][10], int r, int c);
void printMatrix(int a[10][10], int r, int c);
void transpose(int a[10][10], int r, int c);
printf("Enter number of rows: ");
scanf("%d", &r);
printf("Enter number of columns: ");
scanf("%d", &c);
readMatrix(a, r, c);
printf("\nOriginal Matrix:\n");
printMatrix(a, r, c);
transpose(a, r, c);
}
void readMatrix(int a[10][10], int r, int c)
{
int i, j;
printf("Enter elements of the matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &a[i][j]);
}
void printMatrix(int a[10][10], int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
void transpose(int a[10][10], int r, int c)
{
int i, j;
printf("\nTranspose of the matrix:\n");
for (i = 0; i < c; i++) {
52
Lab Record for Programming for Problem Solving
for (j = 0; j < r; j++)
printf("%d ", a[j][i]);
printf("\n");
}
}
Input:
Enter number of rows: 2
Enter number of columns: 2
Enter elements of the matrix:
1
2
3
4
Output:
Original Matrix:
12
34
53
Lab Record for Programming for Problem Solving
49) Write a C program to calculate x^n using recursion.
#include <stdio.h>
void main()
{
int x, n;
long long result;
long long power(int x, int n);
printf("Enter the value of x: ");
scanf("%d", &x);
printf("Enter the value of n: ");
scanf("%d", &n);
result = power(x, n);
printf("\n%d^%d = %lld\n", x, n, result);
}
long long power(int x, int n)
{
if (n != 0)
return x * power(x, n - 1);
else
return 1;
}
54
Lab Record for Programming for Problem Solving
50) In the fast-paced world of physics research, the "Quantum Dynamics Research Team" led
by Dr. Maria Rodriguez is actively exploring groundbreaking experiments. As part of their
endeavors, they require a specialized scientific calculator program to compute the sum of a
series crucial for their experiments. They've reached out to you to develop this program,
and you're determined to meet their needs. Write a C program to help the researchers.
The series is defined as: S=1 + ½ + 1/3 +………+1/n
#include <stdio.h>
void main()
{
int n;
double result;
double harmonicSeries(int n);
printf("Enter a positive number: ");
scanf("%d", &n);
result = harmonicSeries(n);
printf("\nThe sum of the series S = 1 + 1/2 + ... + 1/%d is: %f\n", n, result);
}
double harmonicSeries(int n)
{
int i;
double sum = 0.0;
for (i = 1; i <= n; i++)
sum += 1.0 / i;
return sum;
}
Output: The sum of the series S = 1 + 1/2 + ... + 1/6 is: 2.450000
55
Lab Record for Programming for Problem Solving
51) In the world of computer science education, Professor Anderson is teaching a
programming course where students are delving into the fascinating world of algorithms
and recursion. As a part of their learning journey, he assigns a task to the students: create
a program to print the Fibonacci series up to the nth term. This task aims to reinforce their
understanding of recursion and sequence generation. Can you help the students in solving
this problem?
#include <stdio.h>
void main()
{
int n;
int fibonacci(int n);
printf("Enter how many terms you want: ");
scanf("%d", &n);
printf("Fibonacci Series:");
for (int i = 0; i < n; i++)
{
printf("%d ", fibonacci(i));
}
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
56
Lab Record for Programming for Problem Solving
52) Write a C program to find the GCD (greatest common divisor) of two given integers.
#include <stdio.h>
void main()
{
int a, b, g;
int gcd(int a, int b);
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
g = gcd(a,b);
printf("GCD is %d\n", g);
}
int gcd(int a, int b)
{
if (b != 0)
return gcd(b, a % b); // Recursive case
else
return a; // Base case
}
Output: GCD is 5
57
Lab Record for Programming for Problem Solving
53) Write a C program to form a string containing all the capital letters found in another
string in C using Recursion.
#include <stdio.h>
#include <ctype.h>
void main()
{
char str[100], caps[100];
void extractCaps(char source[], char result[], int i, int j);
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // read input safely
extractCaps(str, caps, 0, 0);
printf("\nCapital letters extracted: %s\n", caps);
}
void extractCaps(char source[], char result[], int i, int j)
{
if (source[i] == '\0')
{
result[j] = '\0'; // terminate result string
return;
}
if (isupper(source[i]))
{
result[j] = source[i];
extractCaps(source, result, i + 1, j + 1);
}
else
extractCaps(source, result, i + 1, j);
}
58
Lab Record for Programming for Problem Solving
PROGRAMS USING POINTERS AND STRUCTURES
54) Write a C program to swap two numbers using call by reference.
#include <stdio.h>
void main()
{
int a, b;
void swap(int *a, int *b);
printf("Enter two numbers:");
scanf("%d%d", &a, &b);
printf("\nBefore swapping: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping (In main): a = %d, b = %d\n", a, b);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf("After swapping (In sub): a = %d, b = %d\n", *a, *b);
}
59
Lab Record for Programming for Problem Solving
55) Write a program for reading elements using a pointer into an array and display the values
using the array.
#include <stdio.h>
void main()
{
int n, i, arr[100], *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = arr; // pointer points to array
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", ptr + i); // reading using pointer
printf("Array elements are:\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]); // displaying using array
}
60
Lab Record for Programming for Problem Solving
56) Write a program for display values reverse order from an array using a pointer.
#include <stdio.h>
void main()
{
int n, i, arr[100], *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for(i = 0; i < n; i++)
scanf("%d", &arr[i]); // reading into array
ptr = arr + n - 1; // pointer points to the last element
printf("Array elements in reverse order:");
for(i = 0; i < n; i++)
printf("%d ", *(ptr - i)); // accessing elements in reverse using pointer
}
61
Lab Record for Programming for Problem Solving
57) Mike has a unique way of modifying strings using pointers. He wants to remove all the
characters other than alphabets from a string, and then capitalize all the alphabets. Write
a C program to help Mike perform this character modification operation using pointers.
#include <stdio.h>
#include <ctype.h> // for isalpha() and toupper()
void main()
{
char str[100];
void modifyString(char *str);
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
char *newline = str;
while (*newline != '\0')
{
if (*newline == '\n')
{
*newline = '\0';
break;
}
newline++;
}
modifyString(str);
printf("Modified string: %s\n", str);
}
void modifyString(char *str)
{
char *src = str; // source pointer
char *dst = str; // destination pointer
while (*src != '\0')
{
if (isalpha(*src)) // check if it's an alphabet
{
*dst = toupper(*src); // capitalize and store
dst++;
}
src++;
}
*dst = '\0'; // null-terminate the modified string
}
62
Lab Record for Programming for Problem Solving
58) Write a C program to create an one dimensional array dynamically using malloc() to store
n elements and find sum, average of array elements.
#include <stdio.h>
#include <stdlib.h> // for malloc() and free()
void main()
{
int n, *arr, sum = 0;
float average;
printf("Enter the number of elements: ");
scanf("%d", &n);
arr = (int *) malloc (n * sizeof(int));
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
sum += arr[i];
}
average = (float)sum / n;
printf("Sum of array elements: %d\n", sum);
printf("Average of array elements: %.2f\n", average);
free(arr); // free the allocated memory
}
63
Lab Record for Programming for Problem Solving
59) You are tasked with creating a program to manage employee information for a small
company. Each employee has a unique ID, a name, and a monthly salary. Your program
should allow input for multiple employees and then display their details.
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[50];
float salary;
}emp[300];
void main()
{
int n,i;
printf("Enter the number of employees: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter details for employees:\n");
scanf("%d%s%f", &emp[i].id, emp[i].name, &emp[i].salary);
}
printf("\nEmployee Details:\n");
for (i = 0; i < n; i++)
printf("%d\n%s\n%.2f\n", emp[i].id, emp[i].name, emp[i].salary);
}
Output:
Employee Details:
101
Ramu
93000.60
201
Renu
75000.30
64
Lab Record for Programming for Problem Solving
60) Develop a program to manage a library's book inventory. The program should collect
details for a specified number of books, calculate the total cost of all books, and display
details of books whose price exceeds Rs. 500.
#include <stdio.h>
#include <string.h>
struct Book
{
int id;
char title[150];
char author[300];
float price;
} b[300];
void main()
{
int n, i;
float totalcost = 0;
printf("Enter the number of books: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter details for books:\n");
scanf("%d%s%s%f", &b[i].id, b[i].title, b[i].author, &b[i].price);
totalcost = totalcost + b[i].price;
}
printf("Total cost of all books: Rs. %.2f\n", totalcost);
printf("\nBooks with price exceeding Rs. 500:\n");
for (i = 0; i < n; i++)
{
if (b[i].price > 500)
printf("%d\t%s\t%s\t%.2f\n", b[i].id, b[i].title, b[i].author, b[i].price);
}
}
65
Lab Record for Programming for Problem Solving
61) Construct a C program that executes the following operations:
Establishes a nested structure called Customer, which includes:
A char array for the customer’s name.
An int for the customer ID.
A nested Address structure, containing a char array for the city.
Requests the user to input the number of customers to be entered into the system.
Initializes an array of Customer structures, sized based on the user’s input.
Iterates over the array to collect and assign each customer’s name, ID, and city to
the respective Customer structures.
Iterates over the array again to display the detailed information of each customer.
This task is to use nested structures to manage and present customer data within your
program. Ensure that you prompt the user for all the necessary details and handle the
input and output processes with care.
#include <stdio.h>
#include <string.h>
struct customer
{
char name[50];
int id;
struct Address
{
char city[50];
}address;
}c[100];
void main()
{
int n, i;
printf("Enter the number of customers: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter details for customer:\n");
scanf("%s%d%s",c[i].name,&c[i].id,c[i].[Link]);
}
printf("Customer Details:\n");
for (i = 0; i < n; i++)
printf("%d\t%s\t%s\n", c[i].id, c[i].name, c[i].[Link]);
}
66
Lab Record for Programming for Problem Solving
Input:
Enter the number of customers: 3
Enter details for customer: Ramu 3003 Hyderabad
Enter details for customer: Raju 4005 Chennai
Enter details for customer: Rani 1002 Delhi
Output:
Customer Details:
3003 Ramu Hyderabad
4005 Raju Chennai
1002 Rani Delhi
67
Lab Record for Programming for Problem Solving
62) Develop a C program that executes the following operations:
Introduces a nested structure titled Employee, which should encompass:
A char array to hold the employee’s name.
A nested Date structure, composed of integer fields for the day, month, and year, to
record the employee’s hire date.
Inquires the user for the total count of employees to be cataloged.
Generates an array of Employee structures, with its length determined by the user’s
input.
Proceeds through the array to solicit and store each employee’s name and hire date
within the Employee structures.
Traverses the array again to exhibit the name and hire date of each employee.
#include <stdio.h>
#include <string.h>
struct Employee
{
char name[50];
struct Date
{
int day;
int month;
int year;
}hiredate;
}e[300];
void main()
{
int n, i;
printf("Enter the number of employees: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter details for employee:\n");
scanf("%s%d%d%d", e[i].name, &e[i].[Link], &e[i].[Link],
&e[i].[Link]);
}
printf("Employee Details:\n");
for (i = 0; i < n; i++)
printf("%s\t%02d/%02d/%04d\n", e[i].name, e[i].[Link],
e[i].[Link], e[i].[Link]);
}
68
Lab Record for Programming for Problem Solving
Input:
Enter the number of employees: 2
Enter details for employee: John 27 05 2024
Enter details for employee: Cena 15 06 2024
Output:
Employee Details:
John 27/05/2024
Cena 15/06/2024
69
Lab Record for Programming for Problem Solving
PROGRAMS USING FILES
63) Write a C Program to read the data from a standard input device, store it in a file and then
display the content of a file to standard output device.
#include <stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "w"); // This example assumes the file opens successfully.
printf("Enter text:\n");
while ((ch = getchar()) != EOF)
fputc(ch, fp);
fclose(fp); // close file after writing
fp = fopen("[Link]", "r");
printf("Content of the file:\n");
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
}
Note: The following code can be included after fopen() to avoid any inconsistencies in the program.
if (fp == NULL)
{
printf("Error opening file!\n");
return 1;
}
70
Lab Record for Programming for Problem Solving
64) Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.
#include <stdio.h>
#include <ctype.h> // for toupper()
void main()
{
FILE *src, *dest;
char ch;
src = fopen("[Link]", "r");
dest = fopen("[Link]", "w"); // This example assumes the files open successfully.
while ((ch = fgetc(src)) != EOF)
{
ch = toupper(ch); // convert if lowercase
fputc(ch, dest);
}
printf("File copied successfully with uppercase conversion.\n");
fclose(src);
fclose(dest);
}
71
Lab Record for Programming for Problem Solving
65) Write a C program to merge two files into a third file (i.e., the contents of the first file
followed by those of the second are put in the third file).
#include <stdio.h>
void main()
{
FILE *f1, *f2, *f3;
char ch;
f1 = fopen("[Link]", "r");
f2 = fopen("[Link]", "r");
f3 = fopen("[Link]", "w");
while ((ch = fgetc(f1)) != EOF) // Copy contents of first file
fputc(ch, f3);
while ((ch = fgetc(f2)) != EOF) // Copy contents of second file
fputc(ch, f3);
printf("Files merged successfully into [Link]\n");
fclose(f1);
fclose(f2);
fclose(f3);
}
72
Lab Record for Programming for Problem Solving
66) Emily wants to analyze the contents of a text file. She needs a C program to read the
content of the file, count the number of lines, words, and characters, and display these
statistics. Implement the program to assist Emily in analyzing the file.
#include <stdio.h>
#include <ctype.h>
void main()
{
FILE *fp;
char ch;
int lines = 0, words = 0, characters = 0, inWord = 0;
fp = fopen("[Link]", "r");
while ((ch = fgetc(fp)) != EOF)
{
characters++;
if (ch == '\n') // Count lines
lines++;
if (isspace(ch)) // Count words
inWord = 0;
else if (!inWord)
{
inWord = 1;
words++;
}
}
fclose(fp);
printf("Characters: %d\n", characters);
printf("Words : %d\n", words);
printf("Lines : %d\n", lines);
}
Sample Input:
Assume that the file “[Link]” contains the following data:
Hello World!
This is a sample file.
It contains multiple lines,
words, and characters.
Sample Output:
Characters: 85
Words : 15
Lines :4
73
Lab Record for Programming for Problem Solving
67) We are maintaining a file for employees working in an office of their logged in timings and
sign off timings. Write a program that can add the entries of multiple employees every day
at the end of the file.
#include <stdio.h>
void main()
{
FILE *fp;
char name[50], login[10], signoff[10], choice;
fp = fopen("employee_log.txt", "a");
do
{
printf("Enter Employee Name: ");
scanf(" %[^\n]", name); // Read full line including spaces
fprintf(fp, "Name: %s, Login: %s, Sign-Off: %s\n", name, login, signoff);
Sample Output:
Name: Ramu, Login: 09:00, Sign-Off: 17:00
Name: Raju, Login: 08:45, Sign-Off: 17:30
Name: Rani, Login: 09:15, Sign-Off: 18:00
74
Lab Record for Programming for Problem Solving
68) Noah needs a C program to read the content of a text file, remove all special characters
excluding spaces, and then print the cleaned content. If there are no special characters in
the file, he should print the contents as they are. Can you implement the program to assist
Noah in achieving this task?
#include <stdio.h>
#include <ctype.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
printf("Cleaned File Content:\n");
while ((ch = fgetc(fp)) != EOF)
{
// Keep letters, digits, and spaces; skip other special characters
if (isalnum((unsigned char)ch) || ch == ' ' || ch == '\n')
putchar(ch);
}
fclose(fp);
}
Sample Output:
Hello World Welcome to C programming
This is line 2 with special characters
75
Lab Record for Programming for Problem Solving
69) Write a C program that takes a numerical input from the user and uses macros SQUARE
and CUBE to calculate either the square or cube of the input, depending on the user's
choice. Implement a menu system displaying options for the user to choose between the
square and cube operations.
Use conditional preprocessor directives to check if the SQUARE and CUBE macros are
defined before applying them in the program. If the macros are not defined, prompt an error
message.
#include <stdio.h>
#define SQUARE(x) ((x) * (x)) // Define macros
#define CUBE(x) ((x) * (x) * (x))
void main()
{
int choice;
double num, result;
printf("Enter a number: ");
scanf("%lf", &num);
printf("Enter your choice: ");
scanf("%d", &choice);
#ifdef SQUARE // Check if macros are defined before using
#ifdef CUBE
switch(choice)
{
case 1:
result = SQUARE(num);
printf("Square of %.2lf = %.2lf\n", num, result);
break;
case 2:
result = CUBE(num);
printf("Cube of %.2lf = %.2lf\n", num, result);
break;
default:
printf("Invalid choice!\n");
}
#else
#error "CUBE macro is not defined!"
#endif
#else
#error "SQUARE macro is not defined!"
#endif
}
Input: Enter a number: 3
Enter your choice: 2
Output: Cube of 3.00 = 27.00
76
Lab Record for Programming for Problem Solving
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("Number of command line arguments: %d\n", argc);
printf("Arguments passed:\n");
for (i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
return 0;
}
Sample Input:
Command: ./program Ramu 25 Developer
Sample Output:
Number of command line arguments: 4
Arguments passed:
argv[0] = ./program
argv[1] = Ramu
argv[2] = 25
argv[3] = Developer
77