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

C PROGRAMMING LAB

The document contains a series of C programming exercises, including implementations of arithmetic operations, formatted I/O, decision-making constructs, and loops. Each exercise includes an aim, algorithm, program code, output, and result confirming successful execution. The exercises cover various programming concepts such as using if-else statements, switch-case, and loops to perform tasks like calculating areas, factorials, and printing multiplication tables.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C PROGRAMMING LAB

The document contains a series of C programming exercises, including implementations of arithmetic operations, formatted I/O, decision-making constructs, and loops. Each exercise includes an aim, algorithm, program code, output, and result confirming successful execution. The exercises cover various programming concepts such as using if-else statements, switch-case, and loops to perform tasks like calculating areas, factorials, and printing multiplication tables.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

1

CONTENTS
S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks
No.

2
CONTENTS
S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks
No.

3
CONTENTS
S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks
No.

4
EX.NO:1
I/O STATEMENTS, OPERATORS, EXPRESSIONS

1A) C PROGRAM TO IMPLEMENT ARITHMETIC OPERATORS.

AIM:

To write C program to implement Arithmetic Operators.

ALGORITHM:

Step 1: Declare integer variables.


Step 2: Read all variables at runtime.
Step 3: Perform arithmetic
operations.
i. a+b
ii. a-b
iii. a*b
iv. b/a
v. a**b
Step 4: Print all computed values.
PROGRAM:
#include<stdio.h>
int main()
{
int a, b;
printf("Enter a,b:\n");
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("b/a=%d\n", b / a);
printf("a**b=%d\n", a % b);
return 0;
}

1
OUTPUT:

Enter a,b:
40 60
a+b=100
a-b=-20
a*b=2400
b/a=1
a**b=40

RESULT:
Thus the C Program to perform Arithmetic operators has been successfully executed and
verified.

2
1B) C PROGRAM TO IMPLEMENT FORMATTED I/O STATEMENTS.

AIM:

To write C program to demonstrate the uses of various formatted and unformatted input and
output functions

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables and initialize them.
STEP 3: Get input values from the user for arithmetic
operation.
STEP 4: Use input function scanf() and output function printf()to display the output after the
calculation.
STEP 5:Stop the program.

PROGRAM:

#include<stdio.h>
int main()
{
char alphabh = 'A';
int number1 = 55;
float number2 = 22.34;
printf("char = %c\n", alphabh);
printf("int = %d\n", number1);
printf("float = %f\n", number2);
return 0;
}

OUTPUT:

char = A
int = 55
float = 22.340000

RESULT:

Thus the C program to demonstrate the uses of various formatted and unformatted input and
output functions has been successfully executed.

3
1C) PROGRAM TO ACCEPT CHARACTERS AND DISPLAY USING UNFORMATTED I/O
STATEMENTS

AIM:
To implement a C program to accept characters and display using unformatted I/O function.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables ch and character array str for storage
STEP 3: Read the string in ‘str’ using gets().
STEP 4: Print the string character.
STEP 5: Stop the program.

PROGRAM:

#include <stdio.h>
int main()
{
char x, y, z;
printf("Enter 1st character: ");
x = getchar(); // Using getchar() to read input
getchar(); // To consume the newline character left by getchar() when pressing Enter
printf("Enter 2nd character: ");
y = getchar();
getchar(); // Again consuming the newline
printf("\n Enter 3rd character: ");
z = getchar();
// Printing the characters
printf("\n First character is: ");
putchar(x);
printf("\n Second character is: ");
putchar(y);
printf("\n Third character is: ");
putchar(z);
return 0;
}

4
OUTPUT:

Enter 1st character: a


Enter 2nd character: v
Enter 3rd character: x

First character is: a


Second character is: v
Third character is: x

RESULT:
Thus the C program to accept characters and display using unformatted I/O function has
been successfully executed and verified.

5
1D) PROGRAM TO EVALUATE THE EXPRESSIONS

AIM:
To implement a C program to evaluate the expression using datatypes.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables data types.
STEP 3: Read the values of integer, float values
STEP 4: calculate the values using given arithmetic function and print the
values STEP 5: Stop the program.

PROGRAM:
#include<stdio.h>
main()
{
int a=9,b=13,c=3;
float x,y,z;
x = a-b/3.0+c*2-1;
y = a-(float)b/(3+c)*(2-1);
z = a-((float)b/(3+c)*2)-1;
printf("x = %f\t\t y = %f\t\t z =
%f",x,y,z); getch();
}

OUTPUT:

x = 9.666667
y = 6.833333
z = 3.666667

RESULT:
Thus the C program to evaluate the expression using datatypes has been successfully
executed and verified.

6
EX.NO:2 DECISION-MAKING CONSTRUCTS: IF-ELSE, GOTO, SWITCH-
CASE, BREAK-CONTINUE

2A) PROGRAM TO FIND THE GREATER NUMBER BETWEEN TWO NUMBERS USING IF-
ELSE STATEMENT

AIM:
To implement the C Program to find the greater number between two numbers.

ALGORITHM:
Step 1: Start.
Step 2: Take two inputs (a and b) from the user.
Step 3: If a is greater than b then go to step 4 otherwise go to step 5
Step 4: Print a greater than b
Step 5: Print b greater than a
Step 6: Stop.

PROGRAM:
#include <stdio.h>
int main()
{
int a, b;
// Taking input for two integers
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Comparing the numbers and printing the greater one
if (a > b)
printf("%d is greater", a);
else
printf("%d is greater", b);
return 0; // Return statement to indicate successful execution
}

OUTPUT:
Enter two numbers: 4 5
5 is greater
RESULT:
Thus the C Program to find the greater number between two numbers has been
successfully executed and verified.

7
2B) PROGRAM USING SWITCH CASE STATEMENT

AIM:

To implement the c program to calculate the area of a rectangle or circle or triangle by taking the
user’s choice.

ALGORITHM:

Step 1: Start

Step 2: Initialize variables

Step 3: Take input for choice and then for area variables from the user

Step 4: Case 1: Circle: 3.14*3.14*r

Case 2: Rectangle: ar=a*b

Case 3: Triangle: at=0.5*a*b

Step 5: Display output according to case

Step 6: Stop

PROGRAM:

#include <stdio.h>
int main()
{
float area, r, a, b; // Change area to float for correct decimal calculations
char choice;
// Display options to the user
printf("Enter your choice:\n");
printf("A for area of circle\n");
printf("B for area of rectangle\n");
printf("C for area of triangle\n");
// Take user's choice
scanf("%c", &choice); // Read the user's choice
// Switch case based on user's choice
switch(choice)
{

8
case 'A': // For circle area
printf("Enter radius: ");
scanf("%f", &r); // Use %f for floating-point input
area = 3.14 * r * r; // Formula for area of circle
printf("Area of circle is: %.2f\n", area); // Use %.2f for floating-point numbers
break;
case 'B': // For rectangle area
printf("Enter length and breadth: ");
scanf("%f %f", &a, &b); // Use %f for floating-point input
area = a * b; // Formula for area of rectangle
printf("Area of rectangle is: %.2f\n", area);
break;
case 'C': // For triangle area
printf("Enter base and height: ");
scanf("%f %f", &a, &b); // Use %f for floating-point input
area = 0.5 * a * b; // Formula for area of triangle
printf("Area of triangle is: %.2f\n", area); // Use %.2f for floating-point results
break;
default:
printf("Invalid choice!\n");
}
return 0; // Return to indicate successful execution
}

OUTPUT:
Enter your choice
A for area of circle
B for area of rectangle
C for area of triangle
A
Enter radius: 4
Area of circle is:
50.24

RESULT:

Thus the C program to calculate the area of a rectangle or circle or triangle by taking the
user’s choice has been successfully executed and verified.

9
2C) PROGRAM TO FIND SQUARES OF THE POSITIVE NUMBERS USING CONTINUE
STATEMENT

AIM:
To implement the C Program to find squares of the positive numbers.

ALGORITHM:
Step 1: Start.

Step 2: Take input from the user.

Step 3: Check the condition and take only positive numbers.

Step 4: Print the square number

Step 5: Stop

PROGRAM:

#include <stdio.h>
int main()
{
int i, n, a, sq;
// Taking input for how many numbers the user wants to enter
printf("\nHow many numbers you want to enter: ");
scanf("%d", &n);
// Loop to process each number
for (i = 1; i <= n; i++)
{
printf("\nEnter number: ");
scanf("%d", &a);
// Skip if the number is negative
if (a < 0) continue;
// Calculate the square and print it
sq = a * a;
printf("\nSquare = %d\n", sq);
}
return 0;
}

10
OUTPUT:

How many numbers you want to enter: 3

Enter number: 2

Square = 4

Enter number: 4

Square = 16

Enter number: 8

Square = 64

RESULT:

Thus the program finds square of positive numbers only has been successfully executed and
verified.

11
2E) PROGRAM TO PRINT MULTIPLICATION TABLE USING GOTO STATEMENT

AIM:

To implement the C Program to print Multiplication Table using GOTO statements.

ALGORITHM:

Step 1: Start.

Step 2: Take input from the user.

Step 3: Declare the variable and Check the condition.

Step 4: print the multiplication table give value

Step 5: Stop

PROGRAM:

#include <stdio.h>
int main()
{
int a, i;
// Taking input for the value of a
printf("Enter the value of a: ");
scanf("%d", &a);
// Displaying the multiplication table for a
printf("\nMultiplication Table for %d\n",
a);
// Loop for printing the multiplication table
for (i = 1; i <= 10; i++)
{
printf("%d x %d = %d\n", a, i, a * i);
}
return 0;
}

12
OUTPUT:

Enter the value of a: 5

Multiplication Table for 5


5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

RESULT:

Thus the C Program to print Multiplication Table using GOTO statements has been
successfully executed and verified.

13
2F) PROGRAM TO IMPLEMENT BREAK STATEMENT

AIM:

To implement the C program using break statement.

ALGORITHM:

Step 1: Start.
Step 2: local variable definition.
Step 3: while loop execution
Step 4: terminate the loop using break statement
Step 5: Stop

PROGRAM:

#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20
)
{
printf("value of a: %d\n",
a); a++;

if( a > 15)


{
break;
}
}
return 0;
}

OUTPUT:

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15

RESULT:

Thus the C program using break statement has been successfully executed and verified.

14
EX.NO:3
LOOPS: FOR,WHILE, DO-WHILE

3A) PROGRAM TO FIND THE FACTORIAL OF A NUMBER USING FOR LOOP

AIM:
To implement the c program to find the factorial of a number.

ALGORITHM:

Step 1: Start.

Step 2: Initialize variables.

Step 3: Check FOR condition.

Step 4: If the condition is true, then go to step 5 otherwise go to step 7.

Step 5: f = f * i.

Step 6: Go to step 3.

Step 7: Print value of factorial.

PROGRAM:

int main()
{
int i, a;
long long f = 1; // Use long long to handle larger factorial values
printf("Enter a number: ");
scanf("%d", &a);
// Calculate factorial using a for loop
for (i = 1; i <= a; i++)
{
f = f * i;
}
printf("Factorial of %d is %lld\n", a, f); // Use %lld to print long long int
return 0;
}

15
OUTPUT:
Enter factorial number 5
Factorial of 5 is 120

RESULT:

Thus the C program to find the factorial of a number has been successfully executed and
verified.

16
3B) PROGRAM TO FIND THE SUM OF 1 TO 10 USING DO-WHILE LOOP

AIM:

To implement the C program to find sum of 1 to 10 using the do-while loop statements.

ALGORITHM:

Step 1: Start.
Step 2: initializing the variable
Step 3: do-while loop execution
Step 4: incrementing operation of given variable
Step 5: Print the sum of the values
Step 6: Stop

PROGRAM:

#include <stdio.h>
int main()
{
int i = 1, a = 0;
// Using a do-while loop to calculate the sum
do {
a = a + i; // Add i to the sum
i++; // Increment i
}
while (i <= 10); // Continue until i is greater than 10
// Print the result
printf("Sum of 1 to 10 is %d", a);
return 0;
}

OUTPUT:

Sum of 1 to 10 is 55

RESULT:

Thus the C program to find sum of 1 to 10 using the do-while loop statements has been
successfully executed and verified.

17
3C) PROGRAM TO PRINT 1 TO 10 NUMBERS USING WHILE STATEMENT

AIM:
To implement the C program to print 1 to 10 numbers using while statement.

ALGORITHM:

Step 1: Start.
Step 2: initializing the
variable Step 3: while loop
execution
Step 4: incrementing operation of given variable
Step 5: Print the sum of the values
Step 6: Stop

PROGRAM:

#include <stdio.h>
int main()
{
int n = 1;
// Loop to print numbers from 1 to 10
while (n <= 10) {
printf("%d\n", n); // Print the number followed by a new line
n++; // Increment n
}
return 0; // Return 0 to indicate successful execution
}

OUTPUT:

1
2
3
4
5
6
7
8
9
10

RESULT:
Thus the C program to print 1 to 10 numbers using while statement has been successfully
executed and verified.

18
EX.NO:4 ARRAYS: 1D AND 2D, MULTI-DIMENSIONAL ARRAYS,
TRAVERSAL

4A ) PROGRAM USING ONE-DIMENSIONAL ARRAY

AIM :
To implement a C program to populate an array with height of persons and finding how
many persons are above the average height.

ALGORITHM :

1. Define a symbolic constant MAX_SIZE with the value 100.


2. Declare the floating point variables avg, sum=0.0 and array ‘arr’ with MAX_SIZE.
3. Declare the integer variables i , n and count and initialize the count to zero.
4. Read the number of persons in ‘n’.
5. Read ‘n’ numbers of heights in the array ‘arr’.
6. Compute the sum of heights and avg by sum/n.
7. Compare n number of heights in the array with the avg height. If it is greater than
the avg height then increment the count value by 1.
8. Print the number of persons who are above the average height using count.

PROGRAM :

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
float arr[MAX_SIZE];
int i, n, count = 0;
float sum = 0.0, avg;
// Taking input for the number of persons
printf("Enter the number of persons: ");
scanf("%d", &n);
// Taking input for the heights of persons
printf("\nEnter %d heights in the array: ", n);
for (i = 0; i < n; i++)
{
scanf("%f", &arr[i]);
sum = sum + arr[i];
}

19
// Calculate the average height
avg = sum / n;
// Count the number of persons above the average height
for (i = 0; i < n; i++)
{
if (arr[i] > avg) count++;
}
// Print the average height and the number of persons above the average
printf("The average height is %.2f\n", avg);
printf("Number of persons who are above the average height: %d\n", count);
return 0;
}

OUTPUT :

Enter the number of persons: 3

Enter 3 heights in the array: 156


123
147
The average height is 142.00
Number of persons who are above the average height: 2

RESULT:

Thus the implementation of a C program to populate an array with height of persons and
finding how many persons are above the average height has been successfully executed and verified.

20
4B) BODY MASS INDEX OF THE INDIVIDUALS

AIM :

To implement a C program to multiply two matrices.

ALGORITHM :

STEP 1.Start
STEP 2. Declare the necessary variables and arrays.
STEP 3. Get the values for the two arrays
STEP 4. Multiply the matrices
STEP5. Print the result
STEP 6:Stop.

PROGRAM :

#include<st
dio.h>
#include<stdl
ib.h> int
main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\
n"); for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
21
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;
k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

OUTPUT :

enter the number of


row=3 enter the number
of column=3 enter the
first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the
matrix= 6 6 6
12 12 12
18 18 18

RESULT:
Thus the implementation of a C program to multiply two matrices is executed successfully.

22
4C) WRITE A C PROGRAM TO PERFORM TRAVERSE OPERATION ON AN ARRAY.

AIM:
To implement the C program to traverse operation on an array

ALGORITHM:
Step 01: Start
Step 02: [Initialize counter variable. ] Set i = LB.
Step 03: Repeat for i = LB to UB.
Step 04: Apply process to
arr[i]. Step 05: [End of loop. ]
Step 06: Stop

PROGRAM:

#include<stdio.h>
int main()
{
int i, size;
int arr[] = {1, -9, 17, 4, -3};
// Calculate the size of the array
size = sizeof(arr) / sizeof(arr[0]);
// Print the array elements
printf("The array elements are:\n");
for (i = 0; i < size; i++)
{
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0; // Return 0 to indicate successful execution
}

23
OUTPUT:
The array elements are:
arr[0]= 1
arr[1]= -9
arr[2]= 17
arr[3]= 4
arr[4]= -3

RESULT:
Thus the C program to perform traverse operation on an array has been successfully
executed and verified.

24
EX.NO:5
STRINGS: OPERATIONS

5A) C PROGRAM TO REVERSE THE STRING

AIM :
To implement a C program to reverse the given string without changing the position of
special characters.

ALGORITHM :

STEP 1: Define a function reverse with an argument character array.


STEP 2: Create a temporary character variable say temp.
STEP 3: Find the l and r values as 0 and string length of str respectively.
STEP 4: Reverse only the alphabets from left end to right end using temp in the while loop by
taking the copy of the string ‘str’. Check the symbol is an alphabet or not using isAlphabet()
function.
STEP 5: Main() reads the actual input string and calls the reverse() function with ‘str’ as
argument.

PROGRAM :

#include <stdio.h>
#include <string.h>
int isAlphabet(char);
void reverse(char str[]);
int main()
{
char str[20];
printf("Enter the Input string:\n");
scanf("%s", str);
reverse(str);
printf("Reversed string: %s", str);
return 0;
}
int isAlphabet(char x)
{
return ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z'));
}
void reverse(char str[])

25
{

int r = strlen(str) - 1, l = 0;
char temp;
while (l < r)
{
if (!isAlphabet(str[l]))
l++;
else if (!isAlphabet(str[r]))
r--;
else
{
temp = str[l];
str[l] = str[r];
str[r] = temp;
l++;
r--;
}
}
}

OUTPUT:

Enter the Input string:

wel%come@

Reversed string: emo%clew@

RESULT:

Thus the implementation of a C program to reverse the given string has been successfully
executed and verified.

26
5B) C PROGRAM TO FIND THE TOTAL NUMBER OF WORDS IN A STRING.

AIM :
To implement a C program to find the total number of words in a string.

ALGORITHM :

1. Declare the character variable ‘ch’ and an array s with a size 200.
2. Declare the integer variables i, n and count. Initialize count to 0.
3. Read a string as input and store it in the arrays[].
4. Using for loop search for a space ‘ ‘ in the string and consecutively increment a
variable count.
5. Repeat the step-2 until the end of the string.
6. Increment the variable count by 1 and then print the variable count as output.

PROGRAM :

#include <stdio.h>
#include <string.h>
int main()
{
char s[200], ch;
int count = 0, i, n;
printf("\nEnter the string\n");
// Using getchar to read each character until newline
for(i = 0; (ch = getchar()) != '\n'; i++)
{
s[i] = ch;
}
s[i] = '\0'; // null-terminate the string
n = strlen(s); // Length of the string
// Count spaces to determine the number of words
for (i = 0; i < n; i++)
{
if (s[i] == ' ')
{
count++;
}
}
// Since words are space-separated, we count the spaces and add 1 for the last word
printf("\n Number of words in the given string is: %d\n", count + 1);
return 0;
}

27
OUTPUT :

Enter the string


welcome to c programming

Number of words in the given string is: 4

RESULT:

Thus the implementation of a C programs to find the total number of words in a string has
been successfully executed and verified.

28
5C) C PROGRAM TO CAPITALIZE THE FIRST WORD OF EACH SENTENCE.

AIM :
To implement a C program to capitalize the first word of each sentence.

ALGORITHM :

1. Declare an array variable ‘sentence ‘.


2. Read the sentence in the array ‘sentence ‘.\
3. Convert the first letter of the sentence by toupper(sentence[0]).
4. Using for loop, capitalize all the first word of other sentences by toupper().
5. Print the output string .

PROGRAM :

#include <stdio.h>
#include <string.h>
#include <ctype.h> // For toupper()
#define SIZE 100
int main()
{
char sentence[SIZE];
int i;
printf("\nPlease enter a sentence..\n");
// Using fgets instead of gets to avoid buffer overflow
if (fgets(sentence, SIZE, stdin) != NULL)
{
// Remove the newline character if it's read by fgets
sentence[strcspn(sentence, "\n")] = '\0';
// Capitalize the first character
sentence[0] = toupper(sentence[0]);
// Capitalize letters that follow a period '.'
for (i = 1; i < strlen(sentence); i++)
{
if (sentence[i - 1] == '.')
{
sentence[i] = toupper(sentence[i]);
}
}

29
// Print the output string
printf("\nOutput String: %s\n", sentence);
}
else
{
printf("Error reading input.\n");
}
return 0;
}

OUTPUT :

Please enter a sentence..


this is computer science

Output String: This is computer science

RESULT:
Thus the C program to capitalize the first word of each sentence has been
successfully executed and verified.

30
5D) C PROGRAM TO REPLACE A GIVEN WORD WITH ANOTHER WORD IN THE
STRING.

AIM :

To implement a C program to replace a given word with another word in the string.

ALGORITHM :

1. Define a function replaceWord() with three arguments the input string, oldWord
and newWord and performs as follows:
a) Compute the length of both the words.
b) Count the number of times old word occur in the input string by using for loop
and strstr() function. Count is stored in ‘cnt’.
c) Allocate a memory for the output string as result[ ].
d) Compare the substring with the result and copy the newWord in the place of
oldWord in the result[ ].
e) Print the result[ ].
2. Read the sentence in str[ ].
3. Read the word to be replaced in c[ ].
4. Read the word with which it is to be replaced in d[ ].
5. Call the replaceWord() function from the main() by passing the arguments str[ ], c[ ]
and d[ ].

PROGRAM :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to replace oldWord with newWord in the string s
char *replaceWord(const char *s, const char *oldW, const char *newW)
{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
// Count occurrences of oldW in s
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
i += oldWlen - 1; // Skip the old word in the string
}

31
}
// Allocate enough memory for the new string
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;
// Replace occurrences of oldW with newW
while (*s)
{
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
{
result[i++] = *s++;
}
}
result[i] = '\0'; // Null-terminate the new string
return result;
}
int main()
{
char str[100];
char c[25];
char d[50];
char *result = NULL;
printf("Enter the sentence:\n");
fgets(str, sizeof(str), stdin); // Using fgets instead of gets
// Remove the newline character if fgets reads it
str[strcspn(str, "\n")] = '\0';
printf("\nEnter the word to be replaced:\n");
fgets(c, sizeof(c), stdin);
c[strcspn(c, "\n")] = '\0'; // Removing newline from word to be replaced
printf("\nEnter the word with which it is to be replaced:\n");
fgets(d, sizeof(d), stdin);
d[strcspn(d, "\n")] = '\0'; // Removing newline from new word
printf("\nGiven string: %s\n", str);
result = replaceWord(str, c, d);
printf("\nNew String: %s\n", result);
free(result); // Free the allocated memory
return 0;
}

32
OUTPUT :

Enter the sentence:


Cross compiler is a type of compiler.

Enter the word to be replaced:


compiler

Enter the word with which it is to be replaced.


platform

Given string: cross compiler is a type of


compiler. New String: cross platform is a type of
platform.

RESULT:

Thus the implementation of C programs to replace a given word with another word
has been successfully executed and verified.

33
FUNCTIONS: CALL, RETURN, PASSING PARAMETERS BY
EX.NO:6
(VALUE, REFERENCE), PASSING ARRAYS TO FUNCTION.

6A) C PROGRAM TO SWAP THE VALUES USING FUNCTION CALL

AIM:
To implement the C program to swap the values using function call.

ALORITHM:
STEP1.Start
STEP2. Declare the function and local
variable. STEP3. Read the function call to
swap function. STEP4. Compute the value and
print the value. STEP 5:Stop.
PROGRAM:

#include <stdio.h>
// Function to swap two integers using pointers
void swap(int *x, int *y)
{
int temp;
temp = *x; // Save the value of x
*x = *y; // Put the value of y into x
*y = temp; // Put the saved value of x into y
}
int main()
{
int a = 100;
int b = 200;
printf("Before swap, value of a: %d\n", a);
printf("Before swap, value of b: %d\n", b);
// Pass the addresses of a and b to the swap function
swap(&a, &b);
printf("After swap, value of a: %d\n", a);
printf("After swap, value of b: %d\n", b);
return 0;
}

34
OUTPUT:

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

RESULT:
Thus the C program to swap the values using function call has been successfully executed
and verified.

35
6B) C PROGRAM TO SORT LIST OF NUMBERS USING PASS BY REFERENCE

AIM :
To implement a C program to sort list of numbers using pass by reference.

ALGORITHM :

1. Define a function sort(int m, int x[]) , where m is the number of elements and x is the
m number of array elements to be sorted.
2. The function sort() will compare the nearby elements and sort the elements by
swapping them using a temporary variable ‘t’.
3. Read the number of elements in ‘n’ and also read ‘n’ number of array elements in arr[ ]
from main() function.
4. Print the actual array elements before sorting.
5. Call the sort(n, arr) function by passing the number of elements(n) and array elements
(arr[ ]). Here the reference of the array arr[ ] is automatically passed to the function
sort().
6. Print the sorted array elements after sorting.

PROGRAM :

#include <stdio.h>
// Function to perform bubble sort on an array
void sort(int m, int x[])
{
int i, j, t;
for(i = 0; i < m - 1; i++)
{
for(j = 0; j < m - i - 1; j++)
{
// Compare adjacent elements
if(x[j] > x[j + 1])
{
// Swap if they are in the wrong order
t = x[j];
x[j] = x[j + 1];
x[j + 1] = t;
}
}
}

36
}
int main()
{
int arr[100], i, n;
// Get the number of elements
printf("\n Enter the number of elements in the array: ");
scanf("%d", &n);
// Get the elements of the array
printf("\n Enter the elements of the array:\n");
for(i = 0; i < n; i++)
{
printf("arr[%d] = ", i);
scanf("%d", &arr[i]);
}
// Print elements before sorting
printf("\n Elements before sorting:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", arr[i]);
}
printf("\n");
// Sort the array
sort(n, arr);
// Print elements after sorting
printf("\n Elements after sorting:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", arr[i]);
}
printf("\n");
return 0;
}

OUTPUT:
Enter the number of elements in the array: 5
Enter the elements of the array:
arr[0] = 12
arr[1] = 65
arr[2] = 78
arr[3] = 32

37
arr[4] = 47

Elements before sorting:


12 65 78 32 47

Elements after sorting:


12 32 47 65 78

RESULT:
Thus the implementation of a C program to sort list of numbers using pass by reference has

38
been successfully executed and verified.

39
EX.NO:7
RECURSION

7A) PROGRAM FOR TOWER OF HANOI PROBLEM USING RECURSION PROBLEM.

AIM :
To implement a C program to solve the Tower of Hanoi problem using Recursion.

ALGORITHM :

1. Define function TOH() with 4 arguments as number of disks(n) and 3 towers .


2. Declare variable n.
3. Read the number of disc in ‘n’.
4. Call the function TOH() bypassing n and three towers.
a) if n=1, print Move disc 1 from fr to tr
b) Call the function with n-1, fr, ar, tr
c) Move disc n from fr to tr
d) Call function with n-1, ar, tr, fr

PROGRAM :

#include <stdio.h>

// Function to solve Tower of Hanoi

void TOH(int n, char fr, char tr, char ar)

if (n == 1)

// Base case: Move a single disk from the source rod to the target rod

printf("\nMove disk 1 from rod %c to rod %c", fr, tr);

return;

// Move n-1 disks from the source rod to the auxiliary rod

TOH(n - 1, fr, ar, tr);

// Move the nth disk from the source rod to the target rod

40
printf("\nMove disk %d from rod %c to rod %c", n, fr, tr);

// Move the n-1 disks from the auxiliary rod to the target rod

TOH(n - 1, ar, tr, fr);

int main()

int n;

// Get the number of disks from the user

printf("Enter the number of disks: ");

scanf("%d", &n);

// Print the sequence of moves for solving Tower of Hanoi

printf("The sequence of moves involved in the Tower of Hanoi are:\n");

TOH(n, 'A', 'C', 'B'); // A, B, C are the rods (Source, Target, Auxiliary)

return 0;

OUTPUT:

Enter the number of disks : 3

The sequence of moves involved in the Tower of Hanoi are :

Move disk 1 from rod A to rod C


Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

RESULT:

Thus the implementation of a C program to solve the Tower of Hanoi problem using
recursion has been successfully executed and verified.

41
POINTERS: POINTERS TO FUNCTIONS, ARRAYS, STRINGS,
EX.NO:8
POINTERS TO POINTERS, ARRAY OF POINTERS

8A) C PROGRAM USING POINTER TO FUNCTIONS

AIM:
To implement a C program using pointer to functions.

ALGORITHM:
STEP1:Start
STEP2: Declare the function and local variable.
STEP3: Call the swap () function by passing the address of the two
Variables.
STEP4: Save the content of the first variable pointed by ‘a’ in the
Temporary variable.
STEP 5: Update the second variable (pointed by b) by the value
STEP 6: Stop.

PROGRAM:

#include <stdio.h>
// Function to swap two integers using pointers
void swap(int *a, int *b)
{
int temp;
temp = *a; // Save the value of a
*a = *b; // Assign the value of b to a
*b = temp; // Assign the saved value of a to b
}
int main()
{
int m = 25;
int n = 100;
// Before swap
printf("Before swap, m is %d, n is %d\n", m, n);
// Swap the values of m and n
swap(&m, &n);
// After swap
printf("After swap, m is %d, n is %d\n", m, n);
return 0;
}
41
OUTPUT:
Before swap, m is 25, n is 100
After swap, m is 100, n is 25

RESULT:
Thus the implementation of a C program to swap the value using Pointer to
function has been successfully executed and verified.
8B ) C PROGRAM TO AN ARRAY OF POINTERS TO STRING.

AIM:
To implement a C program to an array of pointers to string.

ALGORITHM:

STEP1.Start
STEP2. Declaring the string pointer array as well as a char
array
STEP3. Taking inputs in char array as well.
STEP4. As copying them to the string pointer array.
STEP 5: used malloc to allocate dynamic memory. l+1 to
Store "\0".
STEP 6: Stop.

PROGRAM:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *names[5]; // Array of pointers to store dynamically allocated strings
char a[100]; // Temporary array to store each input string
int l, i;
char *x;
printf("Enter 5 strings:\n");
for(i = 0; i < 5; i++) {
scanf("%s", a); // Read a string
l = strlen(a); // Get the length of the string
x = (char *)malloc(l + 1); // Allocate memory for the string
if (x == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit the program if memory allocation fails
}
strcpy(x, a); // Copy the input string to the allocated memory
names[i] = x; // Store the pointer in the names array
}
printf("The strings are:\n");

44
for (i = 0; i < 5; i++)
{
printf("%s\n", names[i]); // Print each string
}
// Free the allocated memory
for (i = 0; i < 5; i++) {
free(names[i]);
}
return 0;
}

OUTPUT:

Enter 5 strings:
Tree
Bowl
Hat
Mice
Toon

The strings are:


Tree
Bowl
Hat
Mice
Toon

RESULT:

Thus the implementation of C program to an array of pointers to string has been successfully
executed and verified.

45
EX.NO:9 STRUCTURES: NESTED STRUCTURES, POINTERS TO
STRUCTURES, ARRAYS OF STRUCTURES AND UNIONS.

9A) PROGRAM TO GENERATE SALARY SLIP OF EMPLOYEES USING STRUCTURES


AND POINTERS

AIM :

To implement a C program to generate salary slip of employees using structures and


pointers.

ALGORITHM :

1. Define a structure ‘employee’ with empId, name[ ], basic, hra, da, ma, pf, insurance,
gross and net members.
2. Read the number of employees in ‘num’.
3. Allocate the memory for the ‘num’ number of structure variable
4. Read the structure members values for empId, name[ ], basic, hra, da, ma, pf, insurance.
5. Compute the gross and net salary and deduction amount.
6. Call the printSalary() function to print the salary slip of employees.

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

struct employee {
int empId;
char name[32];
int basic, hra, da, ma;
int pf, insurance;
float gross, net;
};

// Function to print salary slip


void printSalary(struct employee e1) {
printf("Salary Slip of %s:\n", e1.name);
printf("Employee ID: %d\n", e1.empId);

46
printf("Basic Salary: %d\n", e1.basic);
printf("House Rent Allowance: %d\n", e1.hra);
printf("Dearness Allowance: %d\n", e1.da);
printf("Medical Allowance: %d\n", e1.ma);
printf("Gross Salary: %.2f Rupees\n", e1.gross);
printf("\nDeductions:\n");
printf("Provident Fund: %d\n", e1.pf);
printf("Insurance: %d\n", e1.insurance);
printf("\nNet Salary: %.2f Rupees\n\n", e1.net);
}

int main() {
int i, ch, num, flag, empID;
struct employee *e1;

// Get the number of employees


printf("Enter the number of employees: ");
scanf("%d", &num);
e1 = (struct employee *)malloc(sizeof(struct employee) * num);

// Input data for each employee


printf("Enter your input for every employee:\n");
for (i = 0; i < num; i++) {
printf("Employee ID: ");
scanf("%d", &(e1[i].empId));
getchar(); // Consume the newline character left by scanf
printf("Employee Name: ");
fgets(e1[i].name, 32, stdin);
e1[i].name[strlen(e1[i].name) - 1] = '\0'; // Remove newline character at the end

printf("Basic Salary, HRA: ");


scanf("%d%d", &(e1[i].basic), &(e1[i].hra));
printf("DA, Medical Allowance: ");
scanf("%d%d", &(e1[i].da), &(e1[i].ma));
printf("PF and Insurance: ");
scanf("%d%d", &(e1[i].pf), &(e1[i].insurance));
printf("\n");
}

47
// Calculate gross and net salary for each employee
for (i = 0; i < num; i++) {
e1[i].gross = e1[i].basic + (e1[i].hra * e1[i].basic) / 100 +
(e1[i].da * e1[i].basic) / 100 + (e1[i].ma * e1[i].basic) / 100;
e1[i].net = e1[i].gross - (e1[i].pf + e1[i].insurance);
}

// Loop to allow fetching payslip by employee ID


while (1) {
printf("Enter employee ID to get payslip: ");
scanf("%d", &empID);
flag = 0;

// Search for the employee by ID


for (i = 0; i < num; i++) {
if (empID == e1[i].empId) {
printSalary(e1[i]);
flag = 1;
break; // Exit the loop as the record is found
}
}

if (!flag) {
printf("No Record Found!!\n");
}

// Ask user if they want to continue


printf("Do You Want To Continue(1/0): ");
scanf("%d", &ch);
if (!ch) {
break; // Exit if user enters 0
}
}

// Free allocated memory for employee data


free(e1);

return 0;
}

48
OUTPUT :

Enter the number of employees:


2
Enter your input for everyemployee:
Employee ID:
1001
Employee Name: Vignesh
Basic Salary, HRA: 30000 3000
DA, Medical Allowance: 500 700
PF and Insurance: 2500 2000

Employee ID:
1002
Employee Name: Hari
Basic Salary, HRA: 32000 3200
DA, Medical Allowance: 550 760
PF and Insurance: 3000 2400

Enter employee ID to get payslip: 1002


Salary Slip of Hari:
Employee ID: 1002
Basic Salary: 32000
House Rent Allowance: 3200
Dearness Allowance: 550
Medical Allowance: 760
Gross Salary: 31443.00 Rupees

Deductions:
Provident fund: 3000
Insurance: 2400

Net Salary: 26043.00 Rupees

Do You Want To Continue(1/0): 0

RESULT:

Thus the implementation of a C program to generate salary slip of employees using


structures and pointers has been successfully executed and verified.

49
50
9B) NESTED STRUCTURES: PRINTING EMPLOYEE PERSONAL DETAILS

AIM:

To write a C program to calculate the gross salary using structure within structure.

ALGORITHM:

1. Start
2. Struct employee e_code[4]=char e_name[20]=char e_bp=float
struct e_da=float e_hra=floatallo e_pf=float end struct.
3. Read the employee code, name, basic pay, da, hra, pf.
4. Print the employee code, name, basic pay, da, hra, pf.
5. Calculate gross salary=emp1.e_bp+emp1.allo.e_da+emp1.allo.e_hra+emp1.e_pf. Print the
gross salary.
6. Stop.

PROGRAM:
#include <stdio.h>
#include <string.h>
void main() {
// Define the structure for employee details
struct employee {
char e_code[10]; // Employee code (increase size for better flexibility)
char e_name[20]; // Employee name
float e_bp; // Basic pay
struct {
float e_da; // Dearness allowance
float e_hra; // House Rent allowance
} allo;
float e_pf; // Provident fund
};
struct employee emp1;
float gross;
// Input data for employee
printf("\nEnter the code: ");
fgets(emp1.e_code, sizeof(emp1.e_code), stdin); // safer than gets()
emp1.e_code[strcspn(emp1.e_code, "\n")] = '\0'; // Remove newline character added by fgets
printf("\nEnter the name: ");
fgets(emp1.e_name, sizeof(emp1.e_name), stdin); // safer than gets()
emp1.e_name[strcspn(emp1.e_name, "\n")] = '\0'; // Remove newline character
printf("\nEnter the basic pay: ");
scanf("%f", &emp1.e_bp);
printf("\nEnter the dearness allowance: ");
scanf("%f", &emp1.allo.e_da);
printf("\nEnter the house rent allowance: ");
scanf("%f", &emp1.allo.e_hra);
printf("\nEnter the provident fund: ");
scanf("%f", &emp1.e_pf);

51
// Printing employee details
printf("\nCode: %s", emp1.e_code);
printf("\nName: %s", emp1.e_name);
printf("\nBasic pay: %.2f", emp1.e_bp);
printf("\nDearness allowance: %.2f", emp1.allo.e_da);
printf("\nHouse rent allowance: %.2f", emp1.allo.e_hra);
printf("\nProvident fund: %.2f", emp1.e_pf);
// Calculate and print the gross salary
gross = emp1.e_bp + emp1.allo.e_da + emp1.allo.e_hra + emp1.e_pf;
printf("\nNet pay: %.2f", gross);
}

OUTPUT:
Enter the code: 1990

Enter the name: Harish

Enter the basic pay: 15000

Enter the dearness allowance: 1500

Enter the house rent allowance: 800

Enter the provident fund: 1000

Code: 1990
Name: Harish
Basic pay: 15000.00
Dearness allowance: 1500.00
House rent allowance: 800.00
Provident fund: 1000.00
Net pay: 18300.00

RESULT:

Thus the C program to calculate the gross salary using structure within structure was executed
successfully executed and output is verified.

52
9C) POINTERS TO STRUCTURES: PRINTING STUDENT DETAILS

AIM:

To write a C program to print student details using pointers and structures.

ALGORITHM:

1. Start
2. Declare student structure
3. Read student roll number, student name, branch, marks.
4. Print student roll number, student name, branch, marks.
5. Stop.

PROGRAM:

#include <stdio.h>
#include <stdlib.h> // For malloc function
void main()
{
// Define structure to store student details
struct student
{
int rollno;
char name[30];
char branch[4];
int marks;
};
// Pointer to the student structure
struct student *stud;
// Dynamically allocate memory for the student structure
stud = (struct student *)malloc(sizeof(struct student));
if (stud == NULL)
{
printf("Memory allocation failed!\n");
return;
}
// Input student details
printf("\nEnter Rollno: ");
scanf("%d", &stud->rollno);
printf("\nEnter Name: ");
scanf("%s", stud->name); // Input name
printf("\nEnter Branch: ");
scanf("%s", stud->branch); // Input branch
printf("\nEnter Marks: ");
scanf("%d", &stud->marks);
// Output student details
printf("\nRoll Number: %d", stud->rollno);
printf("\nName: %s", stud->name);

printf("\nBranch: %s", stud->branch);

53
printf("\nMarks: %d", stud->marks);
// Free allocated memory (good practice)
free(stud);
}

OUTPUT:
Enter Rollno: 1000

Enter Name: ALICE

Enter Branch: CSE

Enter Marks: 98

Roll Number: 1000


Name: ALICE
Branch: CSE
Marks: 98

RESULT:

Thus the C program to print student details using pointers and structures was executed successfully
executed and output is verified.

54
9D) ARRAY OF STRUCTURES:CALCULATING STUDENT MARK DETAILS

AIM:

To write a C program to calculate the total marks using array of structures.

ALGORITHM:

1. Start
2. Declare the structure with members.
3. Initialize the marks of the students
4. Calculate the subject total by adding
student
[i].sub1+student[i].sub2+student[i].sub3.
5. Print the total marks of the students
6. Stop.

PROGRAM:

#include<stdio.h>
struct marks
{
int sub1;
int sub2;
int sub3;
int total;
};
int main()
{
int i;
struct marks student[3] = { {45, 67, 81, 0}, {75, 53, 69, 0}, {57, 36, 71, 0}};
// Calculate total marks for each student
for(i = 0; i < 3; i++)
{
student[i].total = student[i].sub1 + student[i].sub2 + student[i].sub3;
}
// Print total marks for each student
printf("TOTAL MARKS\n\n");
for(i = 0; i < 3; i++) {
printf("student[%d]: %d\n", i + 1, student[i].total);
}
return 0; // This is to wait for user input before the program closes
}

55
OUTPUT:
TOTAL MARKS
student[1]: 193
student[2]: 197
student[3]: 164

RESULT:

Thus the C program to calculate the total marks using array of structures was executed successfully
executed and output is verified.

56
FILES: READING AND WRITING, FILE POINTERS, FILE
EX.NO:10
OPERATIONS, RANDOM ACCESS, AND PROCESSOR
DIRECTIVES.

10A) PROGRAM TO COUNT THE NUMBER OF CHARACTERS AND NUMBER OF


LINES IN A FILE USING FILE POINTERS

AIM:
To write a C program to count number of characters and number of lines in a
file using file pointer.

57
ALGORITHM:

1. Start
2. Create file pointers
3. Enter the file name
4. Open the file with read mode
5. Till the end of file reached read one character at a time
(a) If it is newline character „\n‟, then increment no_of_lines countvalue by one.
(b) if it is a character then increment no_of_characters count value byone.
6. Print no_of_lines and no_of_characters values
7. Stop.

PROGRAM:

#include <stdio.h>
#include <stdlib.h> // Required for exit()
#include <string.h> // Required for string functions
int main()
{
FILE *fp;
int ch, no_of_characters = 0, no_of_lines = 1;
char filename[20];
// Get the filename from user input
printf("\nEnter the filename: ");
scanf("%s", filename); // Taking input for the filename
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("\nError opening the file");
exit(1); // Exit if the file cannot be opened
}
// Read characters from the file
ch = fgetc(fp);
while (ch != EOF)
{
if (ch == '\n')
{
no_of_lines++; // Increment line count if newline character is found
}

no_of_characters++; // Increment the character count for every character read


ch = fgetc(fp); // Read next character
}
// Print result based on file content
if (no_of_characters > 0)
{
printf("\nIn the file %s, there are %d lines and %d characters", filename, no_of_lines,
no_of_characters);
} else {
printf("\nFile is empty");

58
}
fclose(fp); // Close the file after reading
return 0;
}

OUTPUT:

Enter the filename: Letter.txt

In the file Letter. txt, there is 1 line and 18 characters

RESULT:

Thus the C program to count number of characters and number of lines in a file using file pointer
was executed successfully executed and output is verified.

59
10B) PROGRAM TO COPY ONE FILE TO ANOTHER

AIM:

To write a C program to copy one file to another.

ALGORITHM:

1. Start

2. Create file pointers

3. Read two file names

4. Open first file with read mode

5. Open second file with write mode

6. Read first file character by character and write the characters in the second file till end of
file reached.

7. Close both file pointers

8. Stop.

PROGRAM:

#include <stdio.h>
#include <stdlib.h> // For exit() function
#include <string.h> // For strcspn()
int main()
{
FILE *fp1, *fp2;
char filename1[256], filename2[256], str[256]; // Increased buffer size for filenames and lines
// Input filenames
printf("\nEnter the name of the first filename: ");
if (fgets(filename1, sizeof(filename1), stdin) == NULL)
{
fprintf(stderr, "\nError reading input for the first filename.\n");
exit(1);
}
filename1[strcspn(filename1, "\n")] = '\0'; // Remove newline character
printf("\nEnter the name of the second filename: ");
if (fgets(filename2, sizeof(filename2), stdin) == NULL)
{
fprintf(stderr, "\nError reading input for the second filename.\n");
exit(1);
}
filename2[strcspn(filename2, "\n")] = '\0'; // Remove newline character

60
// Open the first file for reading
if ((fp1 = fopen(filename1, "r")) == NULL)
{
fprintf(stderr, "\nError opening the first file: %s\n", filename1);
exit(1); // Exit if file can't be opened
}
// Open the second file for writing
if ((fp2 = fopen(filename2, "w")) == NULL)
{
fprintf(stderr, "\nError opening the second file: %s\n", filename2);
fclose(fp1); // Close the first file before exiting
exit(1); // Exit if file can't be opened
}
// Read content from fp1 and write it to fp2
while (fgets(str, sizeof(str), fp1) != NULL)
{
fputs(str, fp2); // Write each line from fp1 to fp2
}
// Close the files after operation
fclose(fp1);
fclose(fp2);
printf("\nContents copied successfully from %s to %s\n", filename1, filename2);
return 0;
}

OUTPUT:

Enter the name of the first filename:a.txt


Enter the name of the second filename:b.txt
FILE COPIED

RESULT:

Thus the C program to copy one file to another was executed successfully executed and output is
verified.

61
10C) PROGRAM TO RANDOMLY READ THE NTH RECORD OF A FILE

AIM:

To read nth record in file using random access method.

ALGORITHM:

1. Start

2. Create employee structure with variables

3. Read the file name with „rb‟ mode

4. Read the record number to read

5. From the file pointed by fp read a record of the specified record starting fromthe beginning
of the file

6. Print the record values

7. Stop.

PROGRAM:
#include <stdio.h>
#include <stdlib.h> // For exit()
struct employee
{
int emp_code;
char name[20];
int hra;
int da;
int ta;
};
int main() {
FILE *fp;
struct employee e;
int result, rec_no;
// Open the file for reading
fp = fopen("employee.txt", "r");
if (fp == NULL)
{
printf("\nError opening file.");
exit(1);
}
// Prompt the user for the record number
printf("\n\nEnter the record number you want to read: ");
scanf("%d", &rec_no);

62
// Validate the record number
if (rec_no > 0)
{
// Move the file pointer to the desired record
fseek(fp, (rec_no - 1) * sizeof(e), SEEK_SET);
// Read the record
result = fread(&e, sizeof(e), 1, fp);
if (result == 1)
{
// Display the record details
printf("\nEMPLOYEE CODE: %d", e.emp_code);
printf("\nName: %s", e.name);
printf("\nHRA, TA, and DA: %d %d %d", e.hra, e.ta, e.da);
}
else
{
printf("\nRecord Not Found.");
}
}
else
{
printf("\nInvalid record number.");
}
// Close the file
fclose(fp);
// Wait for user input before exiting (portable alternative to getch())
printf("\nPress Enter to exit...");
getchar(); // Clear the newline character left by scanf
getchar(); // Wait for user input
return 0;
}

OUTPUT:

Enter the rec_no you want to read: 06


Employee CODE: 06
Name : Tanya
HRA, DA and TA: 20000 10000 3000

RESULT:

Thus the C program to read nth record in file using random access method was executed
successfully executed and output is verified.

63
10D) PROGRAM TO COMPUTE AREA OF A CIRCLE USING PREPROCESSOR DIRECTIVES

AIM:

To write a C program to compute area of a circle using pre-processor

directives.

ALGORITHM:

1. Start

2. Define pi as 3.1415

3. Define circle_area (or) as pi*r*r

4. Read radius

5. Call circle area function radius with to calculate area of a circle.

6. Print area

7. Stop.

PROGRAM:

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI * (r) * (r)) // Properly define the macro
int main()
{
float radius, area;
// Prompt the user for the radius
printf("Enter the radius: ");
scanf("%f", &radius);
// Calculate the area using the macro
area = circleArea(radius);
// Display the area
printf("Area = %.2f\n", area);
return 0; // Correct return statement
}

64
OUTPUT:

Enter the radius: 24


Area = 1809.50

RESULT:

Thus the C program to compute area of a circle using pre-processor directives was executed
successfully executed and output is verified.

65

You might also like