0% found this document useful (0 votes)
3 views

C Code

The document contains programming exercises for a Fundamentals of Programming course, including tasks such as finding the maximum of three numbers, swapping values, determining student grades based on percentage, and calculating areas of geometric shapes. Each exercise includes a C program, sample output, and explanations of the logic used. The document serves as a practical guide for students to practice and understand basic programming concepts.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Code

The document contains programming exercises for a Fundamentals of Programming course, including tasks such as finding the maximum of three numbers, swapping values, determining student grades based on percentage, and calculating areas of geometric shapes. Each exercise includes a C program, sample output, and explanations of the logic used. The document serves as a practical guide for students to practice and understand basic programming concepts.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

ROLL NO.

: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q1. Write a program to determine the maximum of 3 numbers.

PROGRAM:
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter Three numbers: \n");
scanf("%d%d%d",&a,&b,&c);
if(a>b&&a>c){
printf("%d = a is Max number.",a);
}
else if(b>a&&b>c){
printf("%d = b is Max number.",b);
}
else{
printf("%d = c is Max number.",c);
}
}

OUTPUT:
Enter Three numbers:
54
87
95
95 = c is Max number.
__________________________

1|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q2. Write a program to swap the values of two variables.


PROGRAM:
#include<stdio.h>
void main(){
int num,n1,n2;
printf("Enter Value A: \n");
scanf("%d",&n1);
printf("Enter Value B: \n");
scanf("%d",&n2);
printf("Before swapping A= %d & B= %d\n",n1,n2);
num=n1;//a=a+b;
n1=n2;//b=a-b;
n2=num;//a=a-b;
printf("After swapping A= %d & B= %d",n1,n2);
}

OUTPUT:
Enter Value A:
12
Enter Value B:
48
Before swapping A= 12 & B= 48
After swapping A= 48 & B= 12
__________________________

2|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q3. Write a program that reads the percentage obtained by the students and
determines and prints
the class obtained by the student as per the following rules
Percentage Class
0 - 39 Fail
40 - 59 Second class
60 - 79 First class
80 - 100 Distinction
PROGRAM:
#include<stdio.h>
void main(){
float per;
printf("Percentage: \n");
scanf("%f",&per);
if(per>=0 && per<=39)
{
printf("Fail");
}
else if(per>=40 && per<=59)
{
printf("Second Class");
}
else if(per>=60 && per<=79)
{
printf("First Class");
}
else if(per>=80 && per<=100)
{
printf("Distinction");
}
else
{
printf("Invalid Percentage Enter.");
}
}

OUTPUT:
Percentage:
89
Distinction
_______________________

3|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q4. Write a program to calculate the area of circle/rectangle/triangle.


C indicate circle ,
R indicate rectangle,
T indicate triangle.
use symbolic constant to define the value of pie.
PROGRAM:
#include<stdio.h>
#define pi 3.14
void main()
{ float ac,radius,ar,length,width,at,base,height;
printf("Area of Circle:\n");
printf("radius= ");
scanf("%f",&radius);
printf("Area of Rectangle:\n");
printf("length= ");
scanf("%f",&length);
printf("width= ");
scanf("%f",&width);
printf("Area of Triangle:\n");
printf("base= ");
scanf("%f",&base);
printf("height= ");
scanf("%f",&height);
ac=pi*radius*radius;
ar=length*width;
at=(base*height)/2;
printf("Area of Circle: %f\nArea of Rectangle: %f\nArea of Triangle: %f",ac,ar,at);

OUTPUT:
Area of Circle:
radius= 3
Area of Rectangle:
length= 10
width= 15
Area of Triangle:
base= 20
height= 30
Area of Circle: 28.260000
Area of Rectangle: 150.000000
Area of Triangle: 300.000000
__________________________

4|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q5. Write a program that accept basic, HRA, and DA from the user and
calculate total salary.
PROGRAM:
#include<stdio.h>
void main(){
float basic,hra,da,total_salary;
printf("Enter Basic: \n");
scanf("%f",&basic);
printf("Enter HRA: \n");
scanf("%f",&hra);
printf("Enter DA: \n");
scanf("%f",&da);
total_salary=basic+hra+da;
printf("Total Salary: %.2f\n ",total_salary);

OUTPUT:
Enter Basic:
35000
Enter HRA:
15000
Enter DA:
2000
Total Salary: 52000.00

________________________

5|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q6. Write a program to print the multiplication table of given number.


PROGRAM:
#include<stdio.h>
void main(){
int i=1,num;
printf("Enter number for table:");
scanf("%d",&num);
printf("Multiplication of %d number.\n",num);
while(i <= 10)
{
printf("%d x %d = %d\n",num,i,num*i);
i++;
}
}
OUTPUT:
Enter number for table:22
Multiplication of 22 number.
22 x 1 = 22
22 x 2 = 44
22 x 3 = 66
22 x 4 = 88
22 x 5 = 110
22 x 6 = 132
22 x 7 = 154
22 x 8 = 176
22 x 9 = 198
22 x 10 = 220

___________________

6|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q7. Write a program to determine given number is prime or not.


PROGRAM:
#include<stdio.h>
void main()
{
int i,num,count;
printf("Enter number: ");
scanf("%d,",&num);
if(num<=1)
{
printf("%d is Not Prime Number.",num);
exit(1);
}
count= 0;
for(i=2;i<=num/2;i++)
{
if((num%i)==0)
{
count=1;
break;
}
}

if(count == 0)
{
printf("%d is Prime Number.\n",num);
}
else{
printf("%d is Not Prime Number.",num);
}
}
OUTPUT:
Enter number: 3
3 is Prime Number.

___________________

7|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q8. Write a program to reverse a given number and display the sum of all
digits.
PROGRAM:
#include<stdio.h>
void main(){
int n,rd,rs=0,sum=0;
printf("Enter number to reverse:");
scanf("%d",&n);
int t=n;
while(t!=0)
{
rd=t%10;
rs=rs*10+rd;
n=n/10;
sum += rd;
t/=10;
}
printf("Reverse of enter number: %d\n",rs);
printf("Sum of Digits: %d\n", sum);
}
OUTPUT:
Enter number to reverse:1234
Reverse of enter number: 4321
Sum of Digits: 10

_______________________________

8|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q9. Write a program to accept two numbers and perform basic operation of
calculator (+,-,*,/).(Use switch…case)
PROGRAM:
#include<stdio.h>
void main()
{
char operater;
float num1,num2;
printf("Enter operation of calculator: ");
scanf("%f",&num1);
printf("operation's ");
scanf("%c",&operater);
printf("");
scanf("%f",&num2);
switch(operater){

case '+':
printf("Result is: %f\n",num1+num2);
break;
case '-':
printf("Result is: %f\n",num1-num2);
break;
case '*':
printf("Result is: %f\n",num1*num2);
break;
case '/':
if(num2!=0){
printf("Result is: %f\n",num1/num2);
}
else{
printf("Result is Error:Division by zero\n");
}
break;
default:
{
printf("Result is Error:Invalid Operation\n");
}
break;
}
}
OUTPUT:
Enter operation of calculator: 23*8
operation's Result is: 184.000000
__________________________

9|Page
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q10. Write a program to find maximum and minimum element from 1-


Dimensional array.
PROGRAM:
#include <stdio.h>
int main() {
int n, i;
int max, min;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

max = min = arr[0];


for (i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}

printf("Maximum element = %d\n", max);


printf("Minimum element = %d\n", min);

return 0;
}
OUTPUT:
Enter the number of elements in the array: 5
Enter 5 elements:
48
98
74
68
12
Maximum element = 98
Minimum element = 12
__________________________

10 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q11. Write a program to sort given array in ascending order.


PROGRAM:
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: \n", n);
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 in ascending order: ");


for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

OUTPUT:
Enter the number of elements in the array: 5
Enter 5 elements:
12
45
78
95
36
Sorted array in ascending order: 12 36 45 78 95

________________________

11 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q12. Write a program to add two matrices.


PROGRAM:
#include <stdio.h>
int main() {
int rows, cols, i, j;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols];
printf("Enter elements of the first matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]); }
}
printf("Enter elements of the second matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]); }
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j]; }
}
printf("Sum of the matrices:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter the number of rows and columns: 3
3
Enter elements of the first matrix:
10
12
14
15
16
17
18
19
11
Enter elements of the second matrix:
2
5
4
9
7
6
3
4
5
Sum of the matrices:
12 17 18
24 23 23
21 23 16

____________________

12 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q13. Write a program to find element at given position from 2-Dimensional


array.
PROGRAM:
#include <stdio.h>
int main() {
int rows, cols, i, j;
int row_pos, col_pos;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);

int arr[rows][cols];
printf("Enter elements of the array:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}
printf("Enter the position (row and column) to find the element: ");
scanf("%d %d", &row_pos, &col_pos);

if (row_pos >= 0 && row_pos < rows && col_pos >= 0 && col_pos < cols) {
printf("Element at position (%d, %d) is: %d\n", row_pos, col_pos, arr[row_pos][col_pos]);
} else {
printf("Invalid position!\n");
}

return 0;
}

OUTPUT:
Enter the number of rows and columns: 3
3
Enter elements of the array:
12
15
45
78
95
62
35
16
17
Enter the position (row and column) to find the element: 1
2
Element at position (1, 2) is: 62
____________________________

13 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q14. Write a program that will read a text and count all occurrences of a
particular character using function.
PROGRAM:
#include <stdio.h>
int countOccurrences(char *str, char ch) {
int count = 0;
while (*str) {
if (*str == ch) {
count++;
}
str++;
}
return count;
}

int main() {
char text[1000], ch;
int count;
printf("Enter the text: ");
scanf("%[^\n]", text);
getchar();
printf("Enter the character to count: ");
scanf("%c", &ch);
count = countOccurrences(text, ch);
printf("The character '%c' occurs %d times in the text.\n", ch, count);
return 0;
}
OUTPUT:
Enter the text: PRIYANKA RATHOD
Enter the character to count: A
The character 'A' occurs 3 times in the text.

___________________________________

14 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q15.Write a function which returns 1 if the given number is palindrome


otherwise returns 0.
PROGRAM:
#include <stdio.h>
int isPalindrome(int number) {
int original = number;
int reversed = 0;
int remainder;

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

if (original == reversed) {
return 1; // palindrome
} else {
return 0; // not a palindrome
}
}

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (isPalindrome(num)) {
printf("%d is a palindrome.\n", num);
} else {
printf("%d is not a palindrome.\n", num);
}

return 0;
}
OUTPUT:
Enter a number: 22
22 is a palindrome.

_______________________________

15 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

16. Write a recursive function for finding the factorial of a number.*/


PROGRAM:
#include <stdio.h>
int factorial(int n)
{
// Base case for factorial function
if (n == 0 || n == 1)
{
return 1;
}
else
{
return(n * factorial(n - 1));
}
}
int main()
{
int n,ans;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &n);
if (n < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
ans = factorial(n);
printf("The Factorial of %d is %d.\n", n, ans);
}
return 0;
}
OUTPUT:
Enter a number to find it's Factorial: 10
The Factorial of 10 is 3628800.

________________

16 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q17. Write a program to perform summation of all elements of array using


pointers.
PROGRAM:
#include <stdio.h>
int main() {
int n, i,sum = 0;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int *ptr = arr;
for (i = 0; i < n; i++) {
sum += *(ptr + i);
}
printf("Sum of the elements: %d\n", sum);

return 0;
}
OUTPUT:
Enter the number of elements in the array: 5
Enter 5 elements: 10
14
15
18
54
Sum of the elements: 111

__________________________

17 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q18. Write a function using pointers to exchange the value stored in two
locations in the memory.
PROGRAM:
#include <stdio.h>
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x,y;
printf("Enter value for x: ");
scanf("%d", &x);
printf("Enter value for y: ");
scanf("%d", &y);
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
OUTPUT:
Enter value for x: 24
Enter value for y: 56
Before swap: x = 24, y = 56
After swap: x = 56, y = 24

_______________________

18 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q19. Write a program to create structure Student with student’s roll no, name and marks of three
subjects (Maths, Science and English) and display the details of student with total marks of all
subjects along with the percentage and passing class in proper format.

PROGRAM:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float marks[3];
};
int main() {
struct Student s;
float total = 0.0, percentage;
char *passing_class;
int i;
printf("Enter Roll No: ");
scanf("%d", &s.roll_no);
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter marks for Maths: ");
scanf("%f", &s.marks[0]);
printf("Enter marks for Science: ");
scanf("%f", &s.marks[1]);
printf("Enter marks for English: ");
scanf("%f", &s.marks[2]);
for (i = 0; i < 3; i++) {
total += s.marks[i];
}
percentage = total / 3;
if (percentage >= 60) {
passing_class = "First Class";
} else if (percentage >= 50) {
passing_class = "Second Class";
} else if (percentage >= 40) {
passing_class = "Third Class";
} else {
passing_class = "Fail";
}
printf("\nStudent Details:\n");
printf("Roll No: %d\n", s.roll_no);
printf("Name: %s\n", s.name);
printf("Maths: %.2f\n", s.marks[0]);
printf("Science: %.2f\n", s.marks[1]);
printf("English: %.2f\n", s.marks[2]);
printf("Total Marks: %.2f\n", total);
printf("Percentage: %.2f%%\n", percentage);
printf("Passing Class: %s\n", passing_class);
return 0;
}
OUTPUT:

Enter Roll No: 22


Enter Name: PRIYANKA
Enter marks for Maths: 82
Enter marks for Science: 79
Enter marks for English: 89

Student Details:
Roll No: 22
Name: PRIYANKA
Maths: 82.00
Science: 79.00
English: 89.00
Total Marks: 250.00
Percentage: 83.33%
Passing Class: First Class
___________________________

19 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q20. Write a program to create structure Time (data members : int h, int m,
int sec). Read a value as seconds from user to display new time after adding
seconds to Time structure.

PROGRAM:

#include <stdio.h>
struct Time {
int h;
int m;
int sec;
};
void addSeconds(struct Time* time, int secondsToAdd) {
time->sec += secondsToAdd;
while (time->sec >= 60) {
time->sec -= 60;
time->m++;
}
while (time->m >= 60) {
time->m -= 60;
time->h++;
}
while (time->h >= 24) {
time->h -= 24;
}
}
int main() {
struct Time currentTime;
int secondsToAdd;
printf("Enter current time (hours, minutes, seconds): ");
scanf("%d %d %d", &currentTime.h, &currentTime.m, &currentTime.sec);
printf("Enter seconds to add: ");
scanf("%d", &secondsToAdd);
addSeconds(&currentTime, secondsToAdd);
printf("New time: %02d:%02d:%02d\n", currentTime.h, currentTime.m, currentTime.sec);
return 0;
}

OUTPUT:

Enter current time (hours, minutes, seconds): 9 18 15


Enter seconds to add: 15
New time: 09:18:30

______________________

20 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q21. Write a program to define a structure called book. Write a program to


read information about 5 books and display books details in ascending order
of price in proper format.

PROGRAM:
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
char author[50];
float price;
};
void sortBooksByPrice(struct Book books[], int n) {
struct Book temp;
int i,j;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (books[i].price > books[j].price) {
temp = books[i];
books[i] = books[j];
books[j] = temp;
}
}
}
}
int main() {
struct Book books[5];
int n = 5,i;
for (i = 0; i < n; i++) {
printf("Enter details of book %d\n", i + 1);
printf("Title: ");
scanf(" %[^\n]s", books[i].title);
printf("Author: ");
scanf(" %[^\n]s", books[i].author);
printf("Price: ");
scanf("%f", &books[i].price);
}
sortBooksByPrice(books, n);
printf("\nBooks in ascending order of price:\n");
for (i = 0; i < n; i++) {
printf("Title: %s, Author: %s, Price: %.2f\n", books[i].title, books[i].author, books[i].price);
}
return 0;
}
OUTPUT:

Title: ANSI C

21 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Author: BALAGURUSAMY
Price: 629
Enter details of book 2
Title: DBMS
Author: RAMAKRISHNAN
Price: 354
Enter details of book 3
Title: INTERNET TECHNOLOGY AND WEB DESIGN
Author: ISRD GROUP
Price: 350
Enter details of book 4
Title: PRO HTML5PROGRAMMING
Author: PETER LUBBERS
Price: 670
Enter details of book 5
Title: COMPUTER FUNDAMENTAL
Author: RAJ MUKESH
Price: 450

Books in ascending order of price:


Title: INTERNET TECHNOLOGY AND WEB DESIGN, Author: ISRD GROUP, Price: 350.00
Title: DBMS, Author: RAMAKRISHNAN, Price: 354.00
Title: COMPUTER FUNDAMENTAL, Author: RAJ MUKESH, Price: 450.00
Title: ANSI C, Author: BALAGURUSAMY, Price: 629.00
Title: PRO HTML5PROGRAMMING, Author: PETER LUBBERS, Price: 670.00

________________________

22 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q22. Write a program to copy the contents of one file to another and also
print the no. of lines in the first file.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void copyFileAndCountLines(const char *sourceFile, const char *destFile) {
FILE *src, *dest;
char ch;
int lineCount = 0;
src = fopen(sourceFile, "r");
if (src == NULL) {
printf("Cannot open file %s \n", sourceFile);
exit(1);
}
dest = fopen(destFile, "w");
if (dest == NULL) {
printf("Cannot open file %s \n", destFile);
fclose(src);
exit(1);
}
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
if (ch == '\n') {
lineCount++;
}
}
printf("Number of lines in the first file: %d\n", lineCount);
fclose(src);
fclose(dest);
}
int main() {
char sourceFile[100], destFile[100];
printf("Enter the source file name: ");
scanf("%s", sourceFile);
printf("Enter the destination file name: ");
scanf("%s", destFile);
copyFileAndCountLines(sourceFile, destFile);
return 0;
}
OUTPUT:
Enter the source file name: PRIYANKA.txt
Enter the destination file name: RATHOD.txt
Number of lines in the first file: 3
_________________________

23 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q23. Write a function to read a file and count the no. of characters, spaces,
newlines and no. of words in a given text file.

PROGRAM:
#include <stdio.h>
#include <ctype.h>
void countFileContents(const char *filename) {
FILE *file;
char ch;
int chars = 0, spaces = 0, newlines = 0, words = 0;
int inWord = 0;

file = fopen(filename, "r");


if (file == NULL) {
printf("Cannot open file %s \n", filename);
return;
}
while ((ch = fgetc(file)) != EOF) {
chars++;

if (ch == ' ') {


spaces++;
inWord = 0;
} else if (ch == '\n') {
newlines++;
inWord = 0;
} else {
if (!inWord) {
words++;
inWord = 1;
}
}
}
fclose(file);
printf("Number of characters: %d\n", chars);
printf("Number of spaces: %d\n", spaces);
printf("Number of newlines: %d\n", newlines);
printf("Number of words: %d\n", words);
}
int main() {
char filename[100];
printf("Enter the filename: ");
scanf("%s", filename);
countFileContents(filename);
return 0;
}

24 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

OUTPUT:
Enter the filename: PRIYANKA.txt
Number of characters: 78
Number of spaces: 5
Number of newlines: 4
Number of words: 9
_________________________

25 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q24. Write an interactive menu driven program that will access the data file
created in the above problem to do one of the following tasks: a. Determine
the telephone number of a specific customers. b. Determine the customer
whose telephone no. is specified. c. Add a new record. d. Delete a record e.
Generate the listing of all the customers and their telephone numbers

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "PRIYANKA_22.txt"
struct Customer {
char name[50];
char phone[15];
};
void addCustomer() {
FILE *file = fopen(FILENAME, "a");
struct Customer cust;
if (file == NULL) {
printf("Unable to open file.\n");
return;
}
printf("Enter customer name: ");
scanf(" %[^\n]s", cust.name);
printf("Enter telephone number: ");
scanf(" %[^\n]s", cust.phone);
fprintf(file, "%s %s\n", cust.name, cust.phone);
fclose(file);
printf("Customer added successfully.\n");
}
void findPhoneByName() {
FILE *file = fopen(FILENAME, "r");
struct Customer cust;
char name[50];
int found = 0;
if (file == NULL) {
printf("Unable to open file.\n");
return;
}
printf("Enter customer name: ");
scanf(" %[^\n]s", name);
while (fscanf(file, "%s %s", cust.name, cust.phone) != EOF) {
if (strcmp(cust.name, name) == 0) {

26 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

printf("Telephone number of %s: %s\n", name, cust.phone);


found = 1;
break;
}
}
if (!found) {
printf("Customer not found.\n");
}
fclose(file);
}
void findNameByPhone() {
FILE *file = fopen(FILENAME, "r");
struct Customer cust;
char phone[15];
int found = 0;
if (file == NULL) {
printf("Unable to open file.\n");
return;
}
printf("Enter telephone number: ");
scanf(" %[^\n]s", phone);
while (fscanf(file, "%s %s", cust.name, cust.phone) != EOF) {
if (strcmp(cust.phone, phone) == 0) {
printf("Customer with telephone number %s: %s\n", phone, cust.name);
found = 1;
break;
}
}
if (!found) {
printf("Telephone number not found.\n");
}
fclose(file);
}
void deleteCustomer() {
FILE *file = fopen(FILENAME, "r");
FILE *temp = fopen("temp.txt", "w");
struct Customer cust;
char name[50];
int found = 0;
if (file == NULL || temp == NULL) {
printf("Unable to open file.\n");
return;
}
printf("Enter customer name to delete: ");
scanf(" %[^\n]s", name);
while (fscanf(file, "%s %s", cust.name, cust.phone) != EOF) {
if (strcmp(cust.name, name) != 0) {
fprintf(temp, "%s %s\n", cust.name, cust.phone);

27 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

} else {
found = 1;
}
}
fclose(file);
fclose(temp);
remove(FILENAME);
rename("temp.txt", FILENAME);
if (found) {
printf("Customer deleted successfully.\n");
} else {
printf("Customer not found.\n");
}
}
void listAllCustomers() {
FILE *file = fopen(FILENAME, "r");
struct Customer cust;
if (file == NULL) {
printf("Unable to open file.\n");
return;
}
printf("List of all customers and their telephone numbers:\n");
while (fscanf(file, "%s %s", cust.name, cust.phone) != EOF) {
printf("Name: %s, Phone: %s\n", cust.name, cust.phone);
}
fclose(file);
}
int main() {
int choice;
while (1) {
printf("\nMenu:\n");
printf("1. Determine the telephone number of a specific customer\n");
printf("2. Determine the customer whose telephone number is specified\n");
printf("3. Add a new record\n");
printf("4. Delete a record\n");
printf("5. Generate listing of all customers and their telephone numbers\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
findPhoneByName();
break;
case 2:
findNameByPhone();
break;
case 3:
addCustomer();

28 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

break;
case 4:
deleteCustomer();
break;
case 5:
listAllCustomers();
break;
case 6:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
OUTPUT:

Menu:
1. Determine the telephone number of a specific customer
2. Determine the customer whose telephone number is specified
3. Add a new record
4. Delete a record
5. Generate listing of all customers and their telephone numbers
6. Exit
Enter your choice: 1
Enter customer name: PRIYANKA
Telephone number of PRIYANKA: 9016825458

Menu:
1. Determine the telephone number of a specific customer
2. Determine the customer whose telephone number is specified
3. Add a new record
4. Delete a record
5. Generate listing of all customers and their telephone numbers
6. Exit
Enter your choice: 3
Enter customer name: SAARITA
Enter telephone number: 9328018240
Customer added successfully.

Menu:
1. Determine the telephone number of a specific customer
2. Determine the customer whose telephone number is specified
3. Add a new record
4. Delete a record
5. Generate listing of all customers and their telephone numbers
6. Exit
Enter your choice: 4

29 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Enter customer name to delete: HETAL


Customer deleted successfully.

Menu:
1. Determine the telephone number of a specific customer
2. Determine the customer whose telephone number is specified
3. Add a new record
4. Delete a record
5. Generate listing of all customers and their telephone numbers
6. Exit
Enter your choice: 5
List of all customers and their telephone numbers:
Name: PRIYANKA, Phone: 9016825458
Name: RIDDHI, Phone: 7778963327
Name: SHILPA, Phone: 9722423696
Name: SAARITA, Phone: 9328018240

Menu:
1. Determine the telephone number of a specific customer
2. Determine the customer whose telephone number is specified
3. Add a new record
4. Delete a record
5. Generate listing of all customers and their telephone numbers
6. Exit
Enter your choice: 6

_________________________________

30 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

Q25.Use a structure of Employee to write records of employee to a file.


Include a menu that will allow the user to select any of the following features
a. Add a new record. b. Delete a record. c. Modify an existing record. PGDCSA
– I FOP Pointers PraticalSheet-3 d. Retrieve and display an entire record for a
given ID/Name. e. Generate a complete list of all employee names, addresses
and telephone numbers. f. End of the computation/Exit.

PROGRAM:

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

#define MAX_EMPLOYEES 100


#define FILENAME "emp_22.dat"

struct Employee {
int id;
char name[50];
char address[100];
char phone[15];
};

void addRecord();
void deleteRecord();
void modifyRecord();
void retrieveRecord();
void listRecords();
void clearBuffer();

int main() {
int choice;

do {
printf("\nEmployee Management System\n");
printf("1. Add a new record\n");
printf("2. Delete a record\n");
printf("3. Modify an existing record\n");
printf("4. Retrieve and display a record\n");
printf("5. Generate a complete list of employees\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

31 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

clearBuffer();

switch (choice) {
case 1: addRecord(); break;
case 2: deleteRecord(); break;
case 3: modifyRecord(); break;
case 4: retrieveRecord(); break;
case 5: listRecords(); break;
case 6: printf("Exiting...\n"); break;
default: printf("Invalid choice! Please try again.\n");
}
} while (choice != 6);

return 0;
}

void clearBuffer() {
while (getchar() != '\n');
}

void addRecord() {
struct Employee emp;
FILE *file = fopen(FILENAME, "ab");

if (file == NULL) {
printf("Error opening file!\n");
return;
}

printf("Enter ID: ");


scanf("%d", &emp.id);
clearBuffer();
printf("Enter Name: ");
fgets(emp.name, sizeof(emp.name), stdin);
strtok(emp.name, "\n");
printf("Enter Address: ");
fgets(emp.address, sizeof(emp.address), stdin);
strtok(emp.address, "\n");
printf("Enter Phone: ");
fgets(emp.phone, sizeof(emp.phone), stdin);
strtok(emp.phone, "\n");

fwrite(&emp, sizeof(struct Employee), 1, file);


fclose(file);
printf("Record added successfully.\n");
}

void deleteRecord() {

32 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

int id;
struct Employee emp;
FILE *file = fopen(FILENAME, "rb");
FILE *tempFile = fopen("temp.dat", "wb");

if (file == NULL || tempFile == NULL) {


printf("Error opening file!\n");
return;
}

printf("Enter ID of the employee to delete: ");


scanf("%d", &id);

int found = 0;
while (fread(&emp, sizeof(struct Employee), 1, file)) {
if (emp.id != id) {
fwrite(&emp, sizeof(struct Employee), 1, tempFile);
} else {
found = 1;
}
}

fclose(file);
fclose(tempFile);
remove(FILENAME);
rename("priyanka10_22.dat", FILENAME);

if (found) {
printf("Record deleted successfully.\n");
} else {
printf("Record with ID %d not found.\n", id);
}
}

void modifyRecord() {
int id;
struct Employee emp;
FILE *file = fopen(FILENAME, "r+b");

if (file == NULL) {
printf("Error opening file!\n");
return;
}

printf("Enter ID of the employee to modify: ");


scanf("%d", &id);

int found = 0;

33 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

while (fread(&emp, sizeof(struct Employee), 1, file)) {


if (emp.id == id) {
found = 1;
printf("Enter new Name: ");
clearBuffer();
fgets(emp.name, sizeof(emp.name), stdin);
strtok(emp.name, "\n"); // Remove newline character
printf("Enter new Address: ");
fgets(emp.address, sizeof(emp.address), stdin);
strtok(emp.address, "\n"); // Remove newline character
printf("Enter new Phone: ");
fgets(emp.phone, sizeof(emp.phone), stdin);
strtok(emp.phone, "\n"); // Remove newline character

fseek(file, -sizeof(struct Employee), SEEK_CUR); // Move to the record's position


fwrite(&emp, sizeof(struct Employee), 1, file);
break;
}
}

fclose(file);

if (found) {
printf("Record modified successfully.\n");
} else {
printf("Record with ID %d not found.\n", id);
}
}

void retrieveRecord() {
int id;
struct Employee emp;
FILE *file = fopen(FILENAME, "rb");

if (file == NULL) {
printf("Error opening file!\n");
return;
}

printf("Enter ID of the employee to retrieve: ");


scanf("%d", &id);

int found = 0;
while (fread(&emp, sizeof(struct Employee), 1, file)) {
if (emp.id == id) {
found = 1;
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);

34 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

printf("Address: %s\n", emp.address);


printf("Phone: %s\n", emp.phone);
break;
}
}

fclose(file);

if (!found) {
printf("Record with ID %d not found.\n", id);
}
}

void listRecords() {
struct Employee emp;
FILE *file = fopen(FILENAME, "rb");

if (file == NULL) {
printf("Error opening file!\n");
return;
}

printf("\nList of Employees:\n");
while (fread(&emp, sizeof(struct Employee), 1, file)) {
printf("ID: %d, Name: %s, Address: %s, Phone: %s\n", emp.id, emp.name, emp.address,
emp.phone);
}

fclose(file);
}

OUTPUT:

Employee Management System


1. Add a new record
2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 1
Enter ID: 003
Enter Name: Saarita
Enter Address: Chandkheda
Enter Phone: 9328018240
Record added successfully.

Employee Management System

35 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

1. Add a new record


2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 2
Enter ID of the employee to delete: 003
Record deleted successfully.

Employee Management System


1. Add a new record
2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 3
Enter ID of the employee to modify: 001
Enter new Name: Priyanka
Enter new Address: Gandhinagar
Enter new Phone: 9016825458
Record modified successfully.

Employee Management System


1. Add a new record
2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 4
Enter ID of the employee to retrieve: 001
ID: 1
Name: Priyanka
Address: Gandhinagar
Phone: 9016825458

Employee Management System


1. Add a new record
2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 5

List of Employees:

36 | P a g e
NAME: PRIYANKA RATHOD
ROLL NO.: 22 FUNDAMENTALS OF PROGRAMMING COURSE: PGDCSA-1

ID: 1, Name: Priyanka, Address: Gandhinagar, Phone: 9016825458


ID: 2, Name: Hetal, Address: Jamnagar, Phone: 9426994681
ID: 4, Name: Riddhi, Address: Bapunagar, Phone: 77789633327

Employee Management System


1. Add a new record
2. Delete a record
3. Modify an existing record
4. Retrieve and display a record
5. Generate a complete list of employees
6. Exit
Enter your choice: 6
______________________________

37 | P a g e
NAME: PRIYANKA RATHOD

You might also like