0% found this document useful (0 votes)
59 views70 pages

CP Practicals 1

The document appears to be a practical file submitted by a student named Shubham Tiwari containing 31 programming problems assigned over the course of a semester. The problems cover topics like inputting and calculating averages of numbers, computing properties of circles, reversing digits, finding prime numbers, matrix operations, string manipulation, and more. Functions, loops, arrays, structures and pointers are used to solve the problems.

Uploaded by

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

CP Practicals 1

The document appears to be a practical file submitted by a student named Shubham Tiwari containing 31 programming problems assigned over the course of a semester. The problems cover topics like inputting and calculating averages of numbers, computing properties of circles, reversing digits, finding prime numbers, matrix operations, string manipulation, and more. Functions, loops, arrays, structures and pointers are used to solve the problems.

Uploaded by

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

Netaji Subhas University of Technology

Computer Programming
Practical File
FCS002

Submitted To Submitted By
Ms. Barkha Nandwana Shubham Tiwari
2022UCI8012
CSIOT ( 1st Year )
1

Index
S.No Practical Date Sign.
Write a C program to input 3 numbers and
1. 21 Nov, 2022
print their average.

Write a C program to enter the radius of


2. circle/sphere and compute its 21 Nov, 2022

(i) Perimeter (ii)Area and (iii) Volume.

Write a program in C to show that Right shift


3. effectively divides a number by 2 and a left 21 Nov, 2022
shift effectively multiplies a number by 2.

Write a C program to find the roots of a


4. 28 Nov, 2022
quadratic equation.

Write down a function in C to implement


5. 28 Nov, 2022
bitwise AND, OR, XOR and NOT operations.

Given a n integer number write a program


that displays the number as follows

● First line : All digits


6. ● Second Line : All except first digit 28 Nov, 2022
● Third line : All except first two digits
● .
● .
● Last line : The last digit.

2022UCI8012 Shubham Tiwari


2

Write a program to enter an integer and


7. 5 Dec, 2022
print the sum of the digits in the integer.

Write a C program to input an investment


amount and compute its fixed deposit
8. 5 Dec, 2022
cumulative return after 10 years at the rate
of interest of 7.75%.

9. A company has categorized its employees at


5 Dec, 2022

4 different levels(from1 to 4). For different


employees at different levels the perks are
as follows

Level TA Allowance

1 7000 3000

2 6000 2000

3 5000 1500

4 5000 1500

For Level 1 Basic Rs 40000 to 60000


salary is between and Tax rate is 10%

For level 2 Basic Rs 30000 to 40000


Salary is between and Tax rate is 8%

For level 3 Basic Rs 20000 to 30000


salary is between and Tax rate is 5%

2022UCI8012 Shubham Tiwari


3

For Level 4 Basic Rs 15000 to 20000


Salary is between and tax rate is 0

Gross Salary is sum of Basic salary, Perks


and HRA which is 25% of Basic Salary Tax is
computed on Gross Salary.

Net Salary is Gross salary- Income tax.

Write a Program that will read Employees


name, Level and Basic pay and will print
Gross salary, Tax and Net Salary.

Use Switch-case statements and if


statements.

Given a number, write a program using a


while loop to reverse the digits of the
10. 12 Dec, 2022
number. For example, the number 12345
should be written as 54321.

Write a program to find the prime numbers


between a range of numbers entered by the
11. 12 Dec, 2022
user.

Write a program to find the HCF of two


12. integers entered by the user. 12 Dec, 2022

13. The numbers in the sequence


19 Dec, 2022

1 1 2 3 5 8 13 21…..

are called Fibonacci numbers. Write a


program using do…while loop to calculate

2022UCI8012 Shubham Tiwari


4

and print the first n Fibonacci numbers.

Write a program to evaluate the following


19 Dec, 2022
14. functions to 0.0001% accuracy .

Sinx = x – x 3/3! + x 5/5! – x 7/7!+……..

Write a C program to display the following


Pattern .

1
19 Dec, 2022
15. 121

12321

121

Given the two one dimensional arrays A and


B of size 10 which are sorted in ascending
order. Write a C program to merge them
16. 28 Dec, 2022
into single sorted array C that contains
every item from arrays A and B in ascending
order.

Write a program that will count the number


17. of occurrences of a specified character in a 28 Dec, 2022
given line of Text.

18. Write a program to enter two 3 x 3 matrices


28 Dec, 2022

and find their

a. sum

b. Multiplication

2022UCI8012 Shubham Tiwari


5

c. Transpose

Write a program that counts the number of


19. vowels, consonants and digits in a given line 30 Dec, 2022
of string.

Write a program that replaces a substring


20. 30 Dec, 2022
with another string in a given line of text.

Write a program that takes as input a line of


text and counts the frequency of each digit
and letter in the input. The program will
21. 30 Dec, 2022
treat an uppercase letter and its lowercase
equivalent as the same letter; for example, E
and e increment the same counter.

Write a program that takes as input


maximum 100 numbers from user (+ve
integers) and calculates

22. (I)sum 2 Jan, 2022


(ii) mean

(iii)standard deviation and

(iv) variance

23. Write a C program to display following


2 Jan, 2022

Pattern

AB

234

CDEF

2022UCI8012 Shubham Tiwari


6

56789

Write a program that reads the cost of an


item in the form RRR.PP (Where RRR
24. Represents the Rupees and PP represents 2 Jan, 2022
Paise) and converts the value to a string of
words.

Write a program using pointers to read an


25. array of integers and print its elements in 16 Jan, 2022
reverse order.

Write a function(using pointer parameters)


that compares two integer arrays to see
26. 16 Jan, 2022
whether they are identical. The function
returns 1 if they are identical else 0.

Write a program that takes as input an


integer and prints if the number is Prime or
27. 16 Jan, 2022
Fibonacci or both. Use Functions to write the
program.

Write a function substring that, given two


strings s1 and s2, returns the starting
position of the first occurrence of s1 in s2. If
s1 is not in s2,return -1.
28. 23 Jan, 2022
For example,

substring("mom","thermometer") returns 4
but substring("dad","thermometer") returns
-1.

29. Write a program in C using pointers to


23 Jan, 2022

2022UCI8012 Shubham Tiwari


7

implement insertion and deletion in a


queue. Queue is a data structure that
follows first in first out i.e. the element to go
in first is the one to come out first.

Define a structure data type called


time_struct containing three members hour,
minute and second. Develop a program that
30. will input values from the user and assign 23 Jan, 2022
values to the individual members and
display the time in the following format
16:40:40.

A start-up owner is interested in maintaining


the dataset of the newly recruited
employees. She is interested in storing the
Emp_Name (Str), Emp_Mobile(int),
Emp_Age(int), Emp_Degree (Str), Emp_Exp
(Float), Emp_add (Structure). Emp_add
needs one user defined data to store street
31. no, city, district and state for the employee 30 Jan, 2022
address. You Have to design a database
where we can store all the information for at
least 20 employees. The program should be
an interactive program to input the
employee details and also the program
should be able to retrieve the data of an
employee based on the mobile number.

32. Write a program that reads text from a file


30 Jan, 2022

and stores the frequency of each digit and


letter into another file. The program will
treat an uppercase letter and its lowercase

2022UCI8012 Shubham Tiwari


8

equivalent as the same letter.

For example, E and e increment the same


counter.

Write a function using pointers to add two


30 Jan, 2022
33. matrices and to return the resultant matrix
to the calling function.

The prime numbers from 1 to 2500 can be


obtained as follows. From a list of the
numbers 1 to 2500, cross out all multiples of
2 (but not 2 itself). Then, find the next
number (n, say) that is not crossed out and
cross out all multiples of n(but not n). repeat
this last step provided that n hasn't
exceeded 50(the square root of 2500). The 30 Jan, 2022
34.
numbers remaining in the list (except 1) are
prime. Write a program that uses this
method to print all primes from 1 to 2500.
Store your output in a file called primes.out.
This Method Is called The Sieve Of
Eratosthenes, named after the Greek
mathematician, geographer, and
philosopher.

2022UCI8012 Shubham Tiwari


9

Practical 1
Write a C program to input 3 numbers and print their average.

Program
#include <stdio.h>

int main() {
int num1, num2, num3;
float average;

printf("Enter 3 numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

average = (num1 + num2 + num3) / 3.0;

printf("Average of %d, %d, and %d is: %.2f", num1, num2, num3,


average);

return 0;
}

Output
Enter 3 numbers: 1 2 3
Average of 1, 2, and 3 is: 2.00

2022UCI8012 Shubham Tiwari


10

Practical 2
Write a C program to enter the radius of circle/sphere and compute its (i) Perimeter (ii)

Area and (iii) Volume.

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

int main() {
float radius, perimeter, area, volume;
const double pi = 3.14159;
int shape;
printf("Enter the shape (1 for circle / 2 for sphere): ");
scanf("%d", &shape);

printf("Enter the radius of the shape: ");


scanf("%f", &radius);
switch(shape) {
case 1:
perimeter = 2 * pi * radius;
area = pi * pow(radius, 2);
printf("Perimeter of the circle is: %.2f\n", perimeter);
printf("Area of the circle is: %.2f\n", area);
break;
case 2:
area = 4 * pi * pow(radius, 2);
volume = (4.0/3.0) * pi * pow(radius,3);
printf("Area of the sphere is: %.2f\n", area);
printf("Volume of the sphere is: %.2f\n", volume);
break;
default:
printf("Invalid shape option. Please enter 1 for circle or 2
for sphere.");
}
return 0;

2022UCI8012 Shubham Tiwari


11

Output
Enter the shape (1 for circle / 2 for sphere): 1
Enter the radius of the shape: 5
Perimeter of the circle is: 31.42
Area of the circle is: 78.54

Enter the shape (1 for circle / 2 for sphere): 2


Enter the radius of the shape: 5
Area of the sphere is: 314.16
Volume of the sphere is: 523.60

2022UCI8012 Shubham Tiwari


12

Practical 3
Write a program in C to show that Right shift effectively divides a number by 2 and a left

shift effectively multiplies a number by 2.

Program
#include <stdio.h>

int main() {
int num, result;

printf("Enter a number: ");


scanf("%d", &num);

// Right shift operator


result = num >> 1;
printf("%d right shifted by 1 is %d\n", num, result);

// Left shift operator


result = num << 1;
printf("%d left shifted by 1 is %d\n", num, result);

return 0;
}

Output
8 right shifted by 1 is 4
8 left shifted by 1 is 16

2022UCI8012 Shubham Tiwari


13

Practical 4
Write a C program to find the roots of a quadratic equation.

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

int main() {
float a, b, c, root1, root2, imaginary, discriminant;
printf("Enter the coefficients of a quadratic equation (a, b, c): ");
scanf("%f %f %f", &a, &b, &c);
discriminant = b*b-4*a*c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
printf("Roots are: %.2f and %.2f", root1, root2);
}
else if (discriminant == 0) {
root1 = root2 = -b / (2*a);
printf("Both roots are equal: %.2f", root1);
}
else {
imaginary = sqrt(-discriminant) / (2*a);
root1 = -b / (2*a);
printf("Roots are: %.2f + i%.2f and %.2f - i%.2f", root1,
imaginary, root1, imaginary);
}

return 0;
}

Output
Enter the coefficients of a quadratic equation (a, b, c): 1 -3 2
Roots are: 1.00 and 2.00

2022UCI8012 Shubham Tiwari


14

Practical 5
Write down a function in C to implement bitwise AND, OR, XOR and NOT operations.

Program
#include <stdio.h>

void bitwise_operations(int num1, int num2) {


int and_result, or_result, xor_result, not_result;

// Bitwise AND operation


and_result = num1 & num2;
printf("Bitwise AND of %d and %d is %d\n", num1, num2, and_result);

// Bitwise OR operation
or_result = num1 | num2;
printf("Bitwise OR of %d and %d is %d\n", num1, num2, or_result);

// Bitwise XOR operation


xor_result = num1 ^ num2;
printf("Bitwise XOR of %d and %d is %d\n", num1, num2, xor_result);

// Bitwise NOT operation


not_result = ~num1;
printf("Bitwise NOT of %d is %d\n", num1, not_result);
}

int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
bitwise_operations(num1, num2);
return 0;
}

2022UCI8012 Shubham Tiwari


15

Output
Bitwise AND of 10 and 5 is 0
Bitwise OR of 10 and 5 is 15
Bitwise XOR of 10 and 5 is 15
Bitwise NOT of 10 is -11

2022UCI8012 Shubham Tiwari


16

Practical 6
Given a n integer number write a program that displays the number as follows

● First line : All digits


● Second Line : All except first digit
● Third line : All except first two digits
● .
● .
● Last line : The last digit.

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

int main(){

int n, len = 0;

printf("Enter a number: ");


scanf("%d", &n);

int tmp = n, num;

while (tmp != 0)
{
tmp /= 10;
len++;
}

printf("Length = %d\n", len);

for (int i = len; i > 0;i--){


num = n % (int)pow(10, i);
printf("%d\n", num);
}
}

2022UCI8012 Shubham Tiwari


17

Output
Enter a number: 1542635
Length = 7
1542635
542635
42635
2635
635
35
5

2022UCI8012 Shubham Tiwari


18

Practical 7
Write a program to enter an integer and print the sum of the digits in the integer.

Program
#include <stdio.h>

int main() {
int num, sum = 0, digit;

printf("Enter an integer: ");


scanf("%d", &num);

while (num > 0) {


digit = num % 10; // get the last digit
sum += digit; // add the digit to the sum
num /= 10; // remove the last digit
}

printf("Sum of digits: %d\n", sum);


return 0;
}

Output
Enter an integer: 123
Sum of digits: 6

2022UCI8012 Shubham Tiwari


19

Practical 8
Write a C program to input an investment amount and compute its fixed deposit
cumulative return after 10 years at the rate of interest of 7.75%.

Program
#include <stdio.h>

int main() {
float principal, rate, interest, total;
int time = 10; //time in years

printf("Enter investment amount: ");


scanf("%f", &principal);

rate = 0.0775; // interest rate of 7.75%

total = principal; //initialize total with the principal


total += principal*rate*time;

printf("Cumulative return after 10 years is: $%.2f\n", total);


return 0;
}

Output
Enter investment amount: 15000
Cumulative return after 10 years is: $26625.00

2022UCI8012 Shubham Tiwari


20

Practical 9
A company has categorized its employees at 4 different levels(from1 to 4). For different
employees at different levels the perks are as follows

Level TA Allowance

1 7000 3000

2 6000 2000

3 5000 1500

4 5000 1500

For Level 1 Basic salary is between Rs 40000 to 60000 and Tax rate is 10%

For level 2 Basic Salary is between Rs 30000 to 40000 and Tax rate is 8%

For level 3 Basic salary is between Rs 20000 to 30000 and Tax rate is 5%

For Level 4 Basic Salary is between Rs 15000 to 20000 and tax rate is 0

Gross Salary is sum of Basic salary, Perks and HRA which is 25% of Basic Salary Tax is
computed on Gross Salary.

Net Salary is Gross salary- Income tax.

Write a Program that will read Employees name, Level and Basic pay and will print Gross
salary, Tax and Net Salary.

Use Switch-case statement and if statements.

2022UCI8012 Shubham Tiwari


21

Program
#include <stdio.h>

int main() {
char name[20];
int level;
float basic_pay, tax, gross_salary, net_salary, TA,
entertainment_allowance, HRA;

printf("Enter employee name: ");


scanf("%s", name);
printf("Enter employee level (1-4): ");
scanf("%d", &level);
printf("Enter employee basic pay: ");
scanf("%f", &basic_pay);

switch(level) {
case 1:
if (basic_pay >= 40000 && basic_pay <= 60000) {
TA = 7000;
entertainment_allowance = 3000;
HRA = basic_pay * 0.25;
gross_salary = basic_pay + TA + entertainment_allowance +
HRA;
tax = gross_salary * 0.1;
net_salary = gross_salary - tax;
printf("Gross salary: $%.2f\n", gross_salary);
printf("Tax: $%.2f\n", tax);
printf("Net salary: $%.2f\n", net_salary);
} else {
printf("Invalid basic pay for level 1 employee\n");
}
break;
case 2:
if (basic_pay >= 30000 && basic_pay <= 40000) {
TA = 6000;
entertainment_allowance = 2000;

2022UCI8012 Shubham Tiwari


22

HRA = basic_pay * 0.25;


gross_salary = basic_pay + TA + entertainment_allowance +
HRA;
tax = gross_salary * 0.08;
net_salary = gross_salary - tax;
printf("Gross salary: $%.2f\n", gross_salary);
printf("Tax: $%.2f\n", tax);
printf("Net salary: $%.2f\n", net_salary);
} else {
printf("Invalid basic pay for level 2 employee\n");
}
break;
case 3:
if (basic_pay >= 20000 && basic_pay <= 30000) {
TA = 5000;
entertainment_allowance = 1500;
HRA = basic_pay * 0.25;
gross_salary = basic_pay + TA + entertainment_allowance +
HRA;
tax = gross_salary * 0.05;
net_salary = gross_salary - tax;
printf("Gross salary: $%.2f\n", gross_salary);
printf("Tax: $%.2f\n", tax);
printf("Net salary: $%.2f\n", net_salary);
} else {
printf("Invalid basic pay for level 3 employee\n");
}
break;
case 4:
if (basic_pay >= 15000 && basic_pay <= 20000){
TA = 5000;
entertainment_allowance = 1500;
HRA = basic_pay * 0.25;
gross_salary = basic_pay + TA + entertainment_allowance +
HRA;
tax = 0;
net_salary = gross_salary - tax;
printf("Gross salary: $%.2f\n", gross_salary);
printf("Tax: $%.2f\n", tax);
printf("Net salary: $%.2f\n", net_salary);

2022UCI8012 Shubham Tiwari


23

} else {
printf("Invalid basic pay for level 4 employee\n");
}
break;
default:
printf("Invalid level. Level should be between 1 and 4\n");
}

return 0;
}

Output
Enter employee name: Shubham
Enter employee level (1-4): 2
Enter employee basic pay: 35000
Gross salary: $51750.00
Tax: $4140.00
Net salary: $47610.00

2022UCI8012 Shubham Tiwari


24

Practical 10
Given a number, write a program using a while loop to reverse the digits of the number.
For example, the number 12345 should be written as 54321.

Program
#include <stdio.h>

int main() {
int num, reversed = 0;

printf("Enter a number: ");


scanf("%d", &num);

while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}

printf("Reversed number: %d\n", reversed);

return 0;
}

Output
Enter a number: 12345
Reversed number: 54321

2022UCI8012 Shubham Tiwari


25

Practical 11
Write a program to find the prime numbers between a range of numbers entered by the
user.

Program
#include <stdio.h>

int main() {
int lower, upper, i, j;

printf("Enter the range of numbers (lower and upper limit): ");


scanf("%d %d", &lower, &upper);

printf("Prime numbers between %d and %d are: \n", lower, upper);

for (i = lower; i <= upper; i++) {


int isPrime = 1; // assume number is prime

// check if i is divisible by any number between 2 and i-1


for (j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}

if (isPrime)
printf("%d ", i);
}
return 0;
}

Output
Enter the range of numbers (lower and upper limit): 50 100
Prime numbers between 50 and 100 are:

2022UCI8012 Shubham Tiwari


26

53 59 61 67 71 73 79 83 89 97

Practical 12
Write a program to find the HCF of two integers entered by the user.

Program
#include <stdio.h>

int main() {
int n1, n2, i, hcf;

printf("Enter two integers: ");


scanf("%d %d", &n1, &n2);

for(i = 1; i <= n1 || i <= n2; i++) {


if(n1 % i == 0 && n2 % i == 0) {
hcf = i;
}
}

printf("HCF of %d and %d is: %d\n", n1, n2, hcf);

return 0;
}

Output
Enter two integers: 4 32
HCF of 4 and 32 is: 4

2022UCI8012 Shubham Tiwari


27

Practical 13
The numbers in the sequence 1 1 2 3 5 8 13 21….. are called Fibonacci numbers. Write a
program using do…while loop to calculate and print the first n Fibonacci numbers.

Program
#include <stdio.h>

int main() {
int n, i = 0, j = 1, k, count = 0;

printf("Enter the number of Fibonacci numbers to generate: ");


scanf("%d", &n);

printf("The first %d Fibonacci numbers are: \n", n);


printf("%d\n%d\n", i, j); // print the first two numbers in the
sequence

do {
k = i + j;
printf("%d\n", k);
i = j;
j = k;
count++;
} while (count < n - 2); // -2 because we've already printed the first
two numbers in the sequence

return 0;
}

Output
Enter the number of Fibonacci numbers to generate: 4
The first 4 Fibonacci numbers are:
0
1
1

2022UCI8012 Shubham Tiwari


28

Practical 14
Write a program to evaluate the following functions to 0.0001% accuracy .

Sinx = x – x 3/3! + x 5/5! – x 7/7!+……..

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

int main() {

double x, sinx=0,term;

printf("Enter the value of x (in radians): ");


scanf("%lf", &x);

term = x;
sinx = term;

for (int i = 3; fabs(term) > 0.0001; i+=2) {


term = (-term*x*x)/(i*(i-1));
sinx += term;
}

printf("sin(%lf) = %lf\n", x, sinx);

return 0;
}

Output
Enter the value of x (in radians): 1.57
sin(1.570000) = 1.000000

2022UCI8012 Shubham Tiwari


29

Practical 15
Write a C program to display the following Pattern .

121

12321

121

Program
#include <stdio.h>

int main() {
int i, j, k, n;

printf("Enter diagonal length of Diamond: ");


scanf("%d",&n);

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


// print spaces
for (j = 1; j <= n-i; j++) {
printf(" ");
}

// print numbers
for (j = 1; j <= i; j++) {
printf("%d ", j);
}

for (j = i-1; j >= 1; j--) {


printf("%d ", j);
}

printf("\n");
}

2022UCI8012 Shubham Tiwari


30

for (i = n-1; i > 0; i--) {


// print spaces
for (j = 0; j <= n-1-i; j++) {
printf(" ");
}

// print numbers
for (j = 1; j <= i; j++) {
printf("%d ", j);
}

for (j = i-1; j >= 1; j--) {


printf("%d ", j);
}

printf("\n");
}

return 0;
}

Output
Enter diagonal length of Diamond: 3
1
1 2 1
1 2 3 2 1
1 2 1
1

2022UCI8012 Shubham Tiwari


31

Practical 16
Given the two one dimensional arrays A and B of size 10 which are sorted in ascending
order. Write a C program to merge them into single sorted array C that contains every item
from arrays A and B in ascending order.

Program
#include <stdio.h>

int main() {
int A[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int B[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int C[20], i, j, k;

i = 0;
j = 0;
k = 0;

// merge A and B into C


while (i < 10 && j < 10) {
if (A[i] < B[j]) {
C[k++] = A[i++];
} else {
C[k++] = B[j++];
}
}

// copy remaining elements of A, if any


while (i < 10) {
C[k++] = A[i++];
}

// copy remaining elements of B, if any


while (j < 10) {
C[k++] = B[j++];
}

printf("The merged and sorted array C is: \n");

2022UCI8012 Shubham Tiwari


32

for (i = 0; i < 20; i++) {


printf("%d ", C[i]);
}

return 0;
}

Output
The merged and sorted array C is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

2022UCI8012 Shubham Tiwari


33

Practical 17
Write a program that will count the number of occurrences of a specified character in a
given line of Text.

Program
#include <stdio.h>
#include <string.h>

int main() {
char text[100], ch;
int count = 0, i;

printf("Enter a line of text: ");


fgets(text, sizeof(text), stdin);

printf("Enter the character to count: ");


scanf("%c", &ch);

for (i = 0; i < strlen(text); i++) {


if (text[i] == ch) {
count++;
}
}

printf("The character '%c' appears %d times in the text.\n", ch,


count);

return 0;
}

Output
Enter a line of text: I am a disco dancer.
Enter the character to count: a
The character 'a' appears 3 times in the text.

2022UCI8012 Shubham Tiwari


34

Practical 18
Write a program to enter two 3 x 3 matrices and find their

a. sum

b. Multiplication

c. Transpose

Program
#include <stdio.h>

int main() {
int A[3][3], B[3][3], C[3][3], i, j;

printf("Enter the elements of matrix A: \n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &A[i][j]);
}
}

printf("Enter the elements of matrix B: \n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &B[i][j]);
}
}

// Sum of matrices A and B


printf("Sum of matrices A and B: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", A[i][j] + B[i][j]);
}
printf("\n");
}

2022UCI8012 Shubham Tiwari


35

// Multiplication of matrices A and B


printf("Multiplication of matrices A and B: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
C[i][j] = 0;
for (int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
printf("%d ", C[i][j]);
}
printf("\n");
}

// Transpose of matrix A
printf("Transpose of matrix A: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", A[j][i]);
}
printf("\n");
}
// Transpose of matrix B
printf("Transpose of matrix B: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", B[j][i]);
}
printf("\n");
}

return 0;
}

2022UCI8012 Shubham Tiwari


36

Output
Enter the elements of matrix A:
1
2
3
4
5
6
7
8
9
Enter the elements of matrix B:
1
1
2
4
5
4
5
5
5
Sum of matrices A and B:
2 3 5
8 10 10
12 13 14
Multiplication of matrices A and B:
24 26 25
54 59 58
84 92 91
Transpose of matrix A:
1 4 7
2 5 8
3 6 9
Transpose of matrix B:
1 4 5
1 5 5
2 4 5

2022UCI8012 Shubham Tiwari


37

Practical 19
Write a program that counts the number of vowels, consonants and digits in a given line of
string.

Program
#include <stdio.h>
#include <ctype.h>

int main() {
char str[100];
int vowels = 0, consonants = 0, digits = 0, i;

printf("Enter a line of text: ");


fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U') {
vowels++;
} else {
consonants++;
}
} else if (isdigit(str[i])) {
digits++;
}
}

printf("Number of vowels: %d\n", vowels);


printf("Number of consonants: %d\n", consonants);
printf("Number of digits: %d\n", digits);

return 0;
}

2022UCI8012 Shubham Tiwari


38

Output
Enter a line of text: H I am a Super 9999 Start.
Number of vowels: 6
Number of consonants: 8
Number of digits: 4

2022UCI8012 Shubham Tiwari


39

Practical 20
Write a program that replaces a substring with another string in a given line of text.

Program
#include <stdio.h>
#include <string.h>

void replace_substring(char str[], char search[], char replace[]);

int main() {
char str[100], search[20], replace[20];

printf("Enter a line of text: ");


fgets(str, sizeof(str), stdin);

printf("Enter the substring to be replaced: ");


scanf("%s", search);

printf("Enter the replacement substring: ");


scanf("%s", replace);

replace_substring(str, search, replace);


printf("The modified text is: %s\n", str);
return 0;
}

void replace_substring(char str[], char search[], char replace[]) {


char *pos;
int index;

while ((pos = strstr(str, search)) != NULL) {


index = pos - str;
str[index] = '\0';
strcat(str, replace);
strcat(str, pos + strlen(search));
}
}

2022UCI8012 Shubham Tiwari


40

Output
Enter a line of text: Surprise, surprise, surpise, the king is back.
Enter the substring to be replaced: surprise
Enter the replacement substring: hi
The modified text is: Surprise, hi, surpise, the king is back.

2022UCI8012 Shubham Tiwari


41

Practical 21
Write a program that takes as input a line of text and counts the frequency of each digit
and letter in the input. The program will treat an uppercase letter and its lowercase
equivalent as the same letter; for example, E and e increment the same counter.

Program
#include <stdio.h>
#include <ctype.h>

int main() {
char str[100];
int i, letters[26] = {0}, digits[10] = {0};

printf("Enter a line of text: ");


fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
letters[tolower(str[i]) - 'a']++;
} else if (isdigit(str[i])) {
digits[str[i] - '0']++;
}
}

printf("Letter frequency: \n");


for (i = 0; i < 26; i++) {
if (letters[i] > 0) {
printf("%c: %d\n", i + 'a', letters[i]);
}
}
printf("\nDigit frequency: \n");
for (i = 0; i < 10; i++) {
if (digits[i] > 0) {
printf("%d: %d\n", i, digits[i]);
}
}
return 0;

2022UCI8012 Shubham Tiwari


42

Output
Enter a line of text: He is the Master the Blaster, 24x7
Letter frequency:
a: 2
b: 1
e: 5
h: 3
i: 1
l: 1
m: 1
r: 2
s: 3
t: 4
x: 1

Digit frequency:
2: 1
4: 1
7: 1

2022UCI8012 Shubham Tiwari


43

Practical 22
Write a program that takes as input maximum 100 numbers from user (+ve integers) and
calculates

(I)sum

(ii) mean

(iii)standard deviation and

(iv) variance

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

int main() {
int num[100], n, i;
double sum = 0, mean, variance = 0, std_deviation;
printf("Enter the number of elements (<100): ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &num[i]);
sum += num[i];
}
mean = sum / n;

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


variance += pow(num[i] - mean, 2);
}
variance /= n;
std_deviation = sqrt(variance);
printf("Sum = %lf\n", sum);
printf("Mean = %lf\n", mean);
printf("Variance = %lf\n", variance);
printf("Standard deviation = %lf\n", std_deviation);

return 0;

2022UCI8012 Shubham Tiwari


44

Output
Enter the number of elements (<100): 5
Enter the elements: 1 2 3 4 5
Sum = 15.000000
Mean = 3.000000
Variance = 2.000000
Standard deviation = 1.414214

2022UCI8012 Shubham Tiwari


45

Practical 23
Write a C program to display following Pattern

AB

234

CDEF

56789

Program
#include <stdio.h>

int main() {
int i, j,n;
int k = 1, w=65;

printf("Enter Max Number: ");


scanf("%d", &n);

int nr = (n+1)/2;

for (i = 1; i <= nr; i++) {


for(j = 1; j < nr+1-i;j++){
printf(" ");
}
for (j = 1; j <= i; j++) {
if (i%2 != 0){
printf("%d ", k++);
}else {
printf("%c ", w++);
}
}
printf("\n");
}

2022UCI8012 Shubham Tiwari


46

return 0;
}

Output
Enter Max Number: 9
1
A B
2 3 4
C D E F
5 6 7 8 9

2022UCI8012 Shubham Tiwari


47

Practical 24
Write a program that reads the cost of an item in the form RRR.PP (Where RRR Represents
the Rupees and PP represents Paise) and converts the value to a string of words. e.g. if we
input 125.75, the output should be “RUPEES ONE HUNDREDTWENTYFIVE AND PAISE
SEVENTY FIVE”

Program
#include <stdio.h>
#include <string.h>

char *ones[] = {"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
"EIGHT", "NINE"};
char *tens[] = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY",
"SEVENTY", "EIGHTY", "NINETY"};
char *teens[] = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};

void print_num(int num) {


if (num >= 100) {
printf("%s ", ones[num / 100]);
printf("HUNDRED ");
num %= 100;
}
if (num >= 10 && num < 20) {
printf("%s ", teens[num - 10]);
} else {
if (num >= 20) {
printf("%s ", tens[num / 10]);
num %= 10;
}
printf("%s ", ones[num]);
}
}

int main() {
int rupees, paise;
printf("Enter the cost of item in the format RRR.PP: ");

2022UCI8012 Shubham Tiwari


48

scanf("%d.%d", &rupees, &paise);


printf("RUPEES ");
print_num(rupees);
printf("AND PAISE ");
print_num(paise);
return 0;
}

Output
Enter the cost of item in the format RRR.PP: 100.02
RUPEES ONE HUNDRED AND PAISE TWO

2022UCI8012 Shubham Tiwari


49

Practical 25
Write a program using pointers to read an array of integers and print its elements in
reverse order.

Program
#include <stdio.h>

int main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Elements in reverse order: ");


for (i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}

return 0;
}

Output
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Elements in reverse order: 5 4 3 2 1

2022UCI8012 Shubham Tiwari


50

Practical 26
Write a function(using pointer parameters) that compares two integer arrays to see
whether they are identical. The function returns 1 if they are identical else 0.

Program
#include <stdio.h>

int compare_arrays(int *arr1, int *arr2, int size) {


int i;
for (i = 0; i < size; i++) {
if (*(arr1 + i) != *(arr2 + i)) {
return 0;
}
}
return 1;
}

int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3, 4, 5};
int size = sizeof(arr1) / sizeof(arr1[0]);

printf("%d", compare_arrays(arr1, arr2, size));

return 0;
}

Output
1

2022UCI8012 Shubham Tiwari


51

Practical 27
Write a program that takes as input an integer and prints if the number is Prime or
Fibonacci or both. Use Functions to write the program.

Program
#include <stdio.h>

int isPrime(int num) {


int i;
if (num <= 1) return 0;
for (i = 2; i <= num/2; i++) {
if (num % i == 0) return 0;
}
return 1;
}

int isFibonacci(int num) {


int a = 0, b = 1, c = 0;
while (c < num) {
c = a + b;
a = b;
b = c;
if (c == num) return 1;
}
return 0;
}

int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}

2022UCI8012 Shubham Tiwari


52

if (isFibonacci(num)) {
printf("%d is a fibonacci number.\n", num);
} else {
printf("%d is not a fibonacci number.\n", num);
}
if(isPrime(num) && isFibonacci(num))
{
printf("%d is a Fibonacci prime number",num);
}
return 0;
}

Output
Enter an integer: 3
3 is a prime number.
3 is a fibonacci number.
3 is a Fibonacci prime number

2022UCI8012 Shubham Tiwari


53

Practical 28
Write a function substring that, given two strings s1 and s2, returns the starting position of
the first occurrence of s1 in s2. If s1 is not in s2,return -1.

For example,

substring("mom","thermometer") returns 4 but substring("dad","thermometer") returns -1.

Program
#include <stdio.h>
#include <string.h>

int substring(char s1[], char s2[]) {


int i, j, k, flag = 0;
int len1 = strlen(s1);
int len2 = strlen(s2);
for (i = 0; i <= len2 - len1; i++) {
for (j = i, k = 0; k < len1; j++, k++) {
if (s2[j] != s1[k]) {
flag = 0;
break;
}
flag = 1;
}
if (flag == 1) {
return i;
}
}
return -1;
}

int main() {
char s1[100], s2[100];
printf("Enter string 1: ");
scanf("%s", s1);
printf("Enter string 2: ");
scanf("%s", s2);

2022UCI8012 Shubham Tiwari


54

int pos = substring(s1, s2);


if (pos != -1) {
printf("The substring %s is present in %s starting at position %d\
n", s1, s2, pos+1);
} else {
printf("The substring %s is not present in %s\n", s1, s2);
}

return 0;
}

Output
Enter string 1: king
Enter string 2: king254
The substring king is present in king254 starting at position 1

2022UCI8012 Shubham Tiwari


55

Practical 29
Write a program in C using pointers to implement insertion and deletion in a queue. Queue
is a data structure that follows first in first out i.e. the element to go in first is the one to
come out first

Program
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node *next;
} Node;

Node *front = NULL;


Node *rear = NULL;

void insert(int data) {


Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;

if (rear == NULL) {
front = rear = new_node;
return;
}

rear->next = new_node;
rear = new_node;
}

int delete() {
if (front == NULL) {
printf("Queue is empty\n");
return -1;
}

2022UCI8012 Shubham Tiwari


56

Node *temp = front;


int data = temp->data;
front = front->next;

if (front == NULL) {
rear = NULL;
}

free(temp);

return data;
}

void display() {
Node *temp = front;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

int main() {
insert(1);
insert(2);
insert(3);
printf("Original queue: ");
display();
printf("Deleted element: %d\n", delete());
printf("Queue after deletion: ");
display();
return 0;
}

Output
Original queue: 1 2 3
Deleted element: 1

2022UCI8012 Shubham Tiwari


57

Queue after deletion: 2 3

Practical 30
Define a structure data type called time_struct containing three members hour, minute and
second. Develop a program that will input values from the user and assign values to the
individual members and display the time in the following format 16:40:40.

Program
#include <stdio.h>

struct time_struct {
int hour, minute, second;
};

int main(){
struct time_struct time;
int hour, minute, second;

printf("Enter hour (24 hour format): ");


scanf("%d", &time.hour);
printf("Enter minutes: ");
scanf("%d", &time.minute);
printf("Enter seconds: ");
scanf("%d", &time.second);

printf("Time is %.2d:%.2d:%.2d", time.hour, time.minute, time.second);

return 0;
}

Output
Enter hour (24 hour format): 15
Enter minutes: 5
Enter seconds: 2
Time is 15:05:02

2022UCI8012 Shubham Tiwari


58

2022UCI8012 Shubham Tiwari


59

Practical 31
A start-up owner is interested in maintaining the dataset of the newly recruited employees.
She is interested in storing the Emp_Name (Str), Emp_Mobile(int), Emp_Age(int),
Emp_Degree (Str), Emp_Exp (Float), Emp_add (Structure). Emp_add needs one user defined
data to store street no, city, district and state for the employee address. You Have to design
a database where we can store all the information for at least 20 employees. The program
should be an interactive program to input the employee details and also the program
should be able to retrieve the data of an employee based on the mobile number.

Program
#include <stdio.h>
#define MAX_EMPLOYEES 20

struct Address{
int street_no;
char city[40];
char district[40];
char state[40];
};

struct Employee{
char Emp_Name[40];
int Emp_Mobile;
int Emp_Age;
char Emp_Degree[40];
float Emp_Exp;
struct Address Emp_add;
};

struct Employee employees[MAX_EMPLOYEES];


int num_employees = 0;

void add_employee() {
if (num_employees >= MAX_EMPLOYEES) {
printf("Cannot add more employees, database is full.\n");
return;

2022UCI8012 Shubham Tiwari


60

struct Employee e;
printf("Enter name: ");
scanf("%s", &e.Emp_Name);
printf("Enter mobile number: ");
scanf("%d", &e.Emp_Mobile);
printf("Enter age: ");
scanf("%d", &e.Emp_Age);
printf("Enter degree: ");
scanf("%s", &e.Emp_Degree);
printf("Enter experience: ");
scanf("%f", &e.Emp_Exp);
printf("Enter street number: ");
scanf("%d", &e.Emp_add.street_no);
printf("Enter city: ");
scanf("%s", &e.Emp_add.city);
printf("Enter district: ");
scanf("%s", &e.Emp_add.district);
printf("Enter state: ");
scanf("%s", &e.Emp_add.state);

employees[num_employees++] = e;
printf("Employee added successfully.\n");
}

void retrieve_employee() {
int mobile;
printf("Enter mobile number to search: ");
scanf("%d", &mobile);

for (int i = 0; i < num_employees; i++) {


if (employees[i].Emp_Mobile == mobile) {
printf("Employee Name: %s\n", employees[i].Emp_Name);
printf("Employee Mobile: %d\n", employees[i].Emp_Mobile);
printf("Employee Age: %d\n", employees[i].Emp_Age);
printf("Employee Degree: %s\n", employees[i].Emp_Degree);
printf("Employee Experience: %.2f\n", employees[i].Emp_Exp);
printf("Employee Address: %d, %s, %s, %s\n",
employees[i].Emp_add.street_no,

2022UCI8012 Shubham Tiwari


61

employees[i].Emp_add.city,
employees[i].Emp_add.district,
employees[i].Emp_add.state);
return;
}
}

printf("Employee not found.\n");


}

int main(){

int choice;
do {
printf("1. Add employee\n");
printf("2. Retrieve employee\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_employee();
break;
case 2:
retrieve_employee();
break;
case 3:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice.\n");
}
} while (choice != 3);

return 0;
}

2022UCI8012 Shubham Tiwari


62

Output
1. Add employee
2. Retrieve employee
3. Exit
Enter your choice: 1
Enter name: Tony
Enter mobile number: 4785123690
Enter age: 25
Enter degree: Genius
Enter experience: 12
Enter street number: 2
Enter city: New_York
Enter district: East_Delhi
Enter state: Delhi
Employee added successfully.
1. Add employee
2. Retrieve employee
3. Exit
Enter your choice: 2
Enter mobile number to search: 4512369870
Employee not found.
1. Add employee
2. Retrieve employee
3. Exit
Enter your choice: 2
Enter mobile number to search: 4785123690
Employee Name: Tony
Employee Mobile: 490156394
Employee Age: 25
Employee Degree: Genius
Employee Experience: 12.00
Employee Address: 2, New_York, East_Delhi, Delhi
1. Add employee
2. Retrieve employee
3. Exit
Enter your choice: 3
Exiting program...

2022UCI8012 Shubham Tiwari


63

2022UCI8012 Shubham Tiwari


64

Practical 32
Write a program that reads text from a file and stores the frequency of each digit and letter
into another file. The program will treat an uppercase letter and its lowercase equivalent as
the same letter.

For example, E and e increment the same counter.

Program
#include <stdio.h>
#include <ctype.h>

#define NUM_CHARS 36 // number of distinct characters (26 letters + 10


digits)

int main()
{
int freqs[NUM_CHARS] = {0}; // an array to keep track of the frequency
of each character
char c;
FILE *infile, *outfile;

// Open input and output files


infile = fopen("input.txt", "r");
outfile = fopen("output.txt", "w");
if (infile == NULL || outfile == NULL)
{
printf("Error: Could not open file.\n");
return 1;
}

// Read input file character by character


while ((c = fgetc(infile)) != EOF)
{
if (isalpha(c))
{

2022UCI8012 Shubham Tiwari


65

// Convert to lowercase and subtract 'a' to get index in freqs


array for letters
freqs[tolower(c) - 'a']++;
}
else if (isdigit(c))
{
// Subtract '0' to get index in freqs array for digits
freqs[c - '0' + 26]++;
}
}

// Write output file with frequency counts


for (int i = 0; i < NUM_CHARS; i++)
{
if (freqs[i] == 0)
{
continue;
}
if (i < 26)
{
fprintf(outfile, "%c: %d\n", 'a' + i, freqs[i] + freqs[i + 'A' -
'a']);
}
else
{
fprintf(outfile, "%c: %d\n", '0' + i - 26, freqs[i]);
}
}

// Close files
fclose(infile);
fclose(outfile);

return 0;
}

2022UCI8012 Shubham Tiwari


66

Output

Input File
Hi, I am a disco dancer.

Ouput File
a: 3
c: 2
d: 2
e: 1
h: 1
i: 3
m: 1
n: 1
o: 1
r: 1
s: 1

2022UCI8012 Shubham Tiwari


67

Practical 33
Write a function using pointers to add two matrices and to return the resultant matrix to
the calling function.

Program
#include <stdio.h>
void add_matrices(int *a, int *b, int *result, int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
*(result + i*cols + j) = *(a + i*cols + j) + *(b + i*cols + j);
}
}
}
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
int i, j;
add_matrices(&a[0][0], &b[0][0], &result[0][0], 2, 2);
printf("Resultant matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}

Output
Resultant matrix:
6 8

2022UCI8012 Shubham Tiwari


68

10 12

Practical 34
The prime numbers from 1 to 2500 can be obtained as follows. From a list of the numbers
1 to 2500, cross out all multiples of 2 (but not 2 itself). Then, find the next number (n, say)
that is not crossed out and cross out all multiples of n(but not n). repeat this last step
provided that n hasn't exceeded 50(the square root of 2500). The numbers remaining in
the list (except 1) are prime. Write a program that uses this method to print all primes from
1 to 2500. Store your output in a file called primes.out. This Method Is called The Sieve Of
Eratosthenes, named after the Greek mathematician, geographer, and philosopher.

Program
#include <stdio.h>
#include <stdbool.h>
#define LIMIT 2500
int main() {
bool primes[LIMIT+1]; // an array to keep track of which numbers are
prime
int i, j;
// Initialize all numbers as prime
for (i = 2; i <= LIMIT; i++) {
primes[i] = true;
}
// Cross out multiples of each prime number
for (i = 2; i*i <= LIMIT; i++) {
if (primes[i]) {
for (j = i*i; j <= LIMIT; j += i) {
primes[j] = false;
}
}
}
// Print all prime numbers to file "primes.out"
FILE *outfile = fopen("primes.out", "w");
if (outfile == NULL) {

2022UCI8012 Shubham Tiwari


69

printf("Error: Could not open file for writing.\n");


return 1;
}
for (i = 2; i <= LIMIT; i++) {
if (primes[i]) {
fprintf(outfile, "%d\n", i);
}
}
printf("Prime numbers written to file successfully.");
fclose(outfile);

return 0;
}

Output
Prime numbers written to file successfully.

2022UCI8012 Shubham Tiwari

You might also like