0% found this document useful (0 votes)
5 views67 pages

C Lab Manual

The document contains a series of C programming exercises aimed at performing various tasks such as finding the sum of digits, checking for Armstrong numbers, determining prime numbers, generating Fibonacci series, checking for Adam numbers, reversing numbers and strings, finding minimum and maximum values in an array, sorting numbers, and performing matrix operations. Each exercise includes an aim, algorithm, program code, and output examples. The programs were successfully executed as per the results provided.

Uploaded by

ksathishkm
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)
5 views67 pages

C Lab Manual

The document contains a series of C programming exercises aimed at performing various tasks such as finding the sum of digits, checking for Armstrong numbers, determining prime numbers, generating Fibonacci series, checking for Adam numbers, reversing numbers and strings, finding minimum and maximum values in an array, sorting numbers, and performing matrix operations. Each exercise includes an aim, algorithm, program code, and output examples. The programs were successfully executed as per the results provided.

Uploaded by

ksathishkm
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/ 67

Ex. No.:01 Write a C program to find sum of digits.

Date:

Aim:
To write a c program to find sum of digits.
Algorithm:
1. Input a number from user. Store it in some variable say num.
2. Find last digit of the number. To get last digit modulo division the number by 10
i.e. lastDigit = num % 10.
3. Add last digit found above to sum i.e. sum = sum + lastDigit.
4. Remove last digit from number by dividing the number by 10 i.e. num = num / 10.
5. Repeat step 2-4 till number becomes 0. Finally you will be left with the sum of
digits in sum.
Program:
/**
* C program to find sum of its digits of a number
*/

#include <stdio.h>

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

/* Input a number from user */


printf("Enter any number to find sum of its digit: ");
scanf("%d", &num);

/* Repeat till num becomes 0 */


while(num!=0)
{
/* Find last digit of num and add to sum */
sum += num % 10;

/* Remove last digit from num */


num = num / 10;
}

printf("Sum of digits = %d", sum);

return 0;
}

Output:
Enter any number to find sum of its digits: 1234
Sum of digits: 10

Result:
Thus the C program to find sum of digits was successfully executed.
Ex no.: 2. Write a C program to check whether a given number is
Armstrong or not.
Date:

Aim :
To write a C program to check whether a given number is Armstrong or not.

Algorithm :
1. Input a number from user. Store it in some variable say num. Make a temporary copy of the
value to some another variable for calculation purposes, say original Num = num.
2. Count total digits in the given number, store result in a variable say digits.
3. Initialize another variable to store the sum of power of its digits ,say sum = 0.
4. Run a loop till num > 0. The loop structure should look like while(num > 0).
5. Inside the loop, find last digit of num. Store it in a variable say last Digit = num % 10.
6. Now comes the real calculation to find sum of power of digits. Perform sum = sum + pow
(lastDigit, digits).
7. Since the last digit of num is processed. Hence, remove last digit by performing num = num
/ 10.
8. After loop check if(originalNum == sum), then it is Armstrong number otherwise not.
Program:
/**
* C program to check Armstrong number
*/
#include <stdio.h>
#include <math.h>

int main()
{
int originalNum, num, lastDigit, digits, sum;

/* Input number from user */


printf("Enter any number to check Armstrong number: ");
scanf("%d", &num);

sum = 0;

/* Copy the value of num for processing */


originalNum = num;

/* Find total digits in num */


digits = (int) log10(num) + 1;

/* Calculate sum of power of digits */


while(num > 0)
{
/* Extract the last digit */
lastDigit = num % 10;

/* Compute sum of power of last digit */


sum = sum + round(pow(lastDigit, digits));

/* Remove the last digit */


num = num / 10;
}
/* Check for Armstrong number */
if(originalNum == sum)
{
printf("%d is ARMSTRONG NUMBER", originalNum);
}
else
{
printf("%d is NOT ARMSTRONG NUMBER", originalNum);
}

return 0;
}

Output:
Enter any number to check Armstrong number: 371
371 is Armstrong Number

Result:
Thus the C program check whether the number is Armstrong or not program was
successfully executed.
Ex No..: 3 Write a C program to check whether a given number is
Prime or not.
Date:

Aim:
To write a C program to check whether a given number is Prime or not.

Algorithm:
1. First give a meaningful name to our prime checking function say isPrime() function will
check a number for prime.

2. Next, since our function checks a number for prime condition. Hence, it must accept a
number, say isPrime(int num);.

3. Finally, the function should return a value to the caller, so that the caller can know whether
the integer passed to the function is prime or not. For this we must return
boolean true or false depending on the prime check result. Therefore return an integer from
function either 1 or 0.
Program:
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

// 0 and 1 are not prime numbers


// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;

for (i = 2; i <= n / 2; ++i) {

// if n is divisible by i, then n is not prime


// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}

// flag is 0 for prime numbers


if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);

return 0;
}
Output:
Enter a positive integer: 29
29 is a prime number.
Result:
Thus the C program check whether the given number is prime or not program was
successfully executed.
Ex No.: 04 Write a C program to generate the Fibonacci series
Date:

Aim:
To write a C program to generate Fibonacci series.
Algorithm:
1. Input number of Fibonacci terms to print from user. Store it in a variable say terms.
2. Declare and initialize three variables, I call it as Fibonacci magic
initialization. a=0, b=1 and c=0.
Here c is the current term, b is the n-1th term and a is n-2th term.

3. Run a loop from 1 to terms, increment loop counter by 1. The loop structure should look
like for(i=1; i<=term; i++). It will iterate through n terms
4. Inside the loop copy the value of n-1th term to n-2th term i.e. a = b.
Next, copy the value of nth to n-1th term b = c.

Finally compute the new term by adding previous two terms i.e. c = a + b.

5. Print the value of current Fibonacci term i.e. c.


Program:
/**
* C program to print Fibonacci series up to n terms
*/
#include <stdio.h>
int main()
{ int a, b, c, i, terms;
/* Input number from user */
printf("Enter number of terms: ");
scanf("%d", &terms);
/* Fibonacci magic initialization */
a = 0;
b = 1;
c = 0;
printf("Fibonacci terms: \n");
/* Iterate through n terms */
for(i=1; i<=terms; i++)
{
printf("%d, ", c);
a = b; // Copy n-1 to n-2
b = c; // Copy current to n-1
c = a + b; // New term
}
return 0; }
Output:
Enter number of terms: 10
Fibonacci terms:
0,1,1,2,3,5,8,13,21,34.
Result:
Thus the C program to generate Fibonacci series program was successfully executed.
Ex No.: 05 Write a C program to display the given number is Adam
number or not.
Date:

Aim:
To write a C program to display the given number is Adam number or not.
Algorithm:

Step1 :Read an integer number n from the user.

Step2: Square the input number n and store the result in square.

Step3: Reverse the Square:

 Initialize a variable reverse_square to 0.


 While square is greater than 0:
o Extract the last digit of square using the modulo operator (%).
o Multiply reverse_square by 10 and add the extracted digit.
o Divide square by 10 to remove the last digit.

Step4: Calculate the square root of reverse_square and store it in


sqrt_reverse_square.

Step5: Reverse the Square Root:

 Initialize a variable reverse_sqrt to 0.


 While sqrt_reverse_square is greater than 0:
o Extract the last digit of sqrt_reverse_square using the modulo operator (%).
o Multiply reverse_sqrt by 10 and add the extracted digit.
o Divide sqrt_reverse_square by 10 to remove the last digit.

Step6: Check for Adam Number:

 If reverse_sqrt is equal to the original input n, then n is an Adam number.


 Otherwise, n is not an Adam number.

Step7: Output:

 Print the result: "n is an Adam number" or "n is not an Adam number".
Program:
#include <stdio.h>
#include <math.h>

int reverse(int num)


{
int rev = 0;
while(num > 0)
{
rev = rev * 10 + num % 10;
num = num / 10;
}
return rev;
}

int isAdamNumber(int num)


{
int sq = num * num;
int rev = reverse(num);
int rev_sq = rev * rev;
int rev_rev_sq = reverse(rev_sq);
if(sq == rev_rev_sq)
return 1;
else
return 0;
}

int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(isAdamNumber(num))
printf("%d is an Adam number\n", num);
else
printf("%d is not an Adam number\n", num);
return 0;
}

Output:
12
Adam Number
5
Not an Adam Number

Result: Thus the C program to check whether the given number is Adam or not
program was successfully executed.
EX:No:06 Write a C program to print reverse of the given number
and string.
Date:

Aim:
To write a C program to print reverse o the given number and string.
Algorithm:

Step1: Input: Read an integer number from the user.

Step2: Initialization: Create a variable reversed_num and initialize it to 0.

Step3: Reversal Loop:

 While the number is greater than 0:


o Extract the last digit of the number using the modulo operator (%).
o Multiply reversed_num by 10 and add the extracted digit to it.
o Divide the number by 10 using integer division (/).

Step4: Output:

 Print the reversed_num.


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

int main() {
int num, reversed_num = 0, remainder;
char str[100];

// Input a number
printf("Enter an integer: ");
scanf("%d", &num);

// Reverse the number


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

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

// Input a string
printf("Enter a string: ");
scanf("%s", str);

// Reverse the string


int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("Reversed string: %s\n", str);
return 1 0;
}
Output:
Enter an integer: 12345
Reversed number: 54321
Enter a string: hello world
Reversed string: dlrow olleh
Result: Thus the C program to print reverse of the given number and string was
successfully executed.
EX:No: 07 Write a C Program to find minimum and maximum of ‘n’
numbers using array.
Date:

Aim:
To Write a C Program to find minimum and maximum of ‘n’ numbers using array.
Algorithm:

Step1: Initialization:

 Declare and initialize two variables: min and max to the first element of the array.

Step2: Iteration:

 Iterate through the array starting from the second element.


 For each element:
o Compare the current element with min.
 If the current element is smaller, update min.
o Compare the current element with max.
 If the current element is larger, update max.

Step3: Return Result:

 After the loop, min will hold the minimum value, and max will hold the maximum value.

Program
#include <stdio.h>

void findMinMax(int arr[], int n, int *max, int *min) {


// Initialize max and min with the first element
*max = arr[0];
*min = arr[0];

// Iterate through the array, updating max and min if necessary


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

int main() {
int arr[] = {12, 15, 1, 10, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int max, min;

findMinMax(arr, n, &max, &min);

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


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

return 0;
}

Output:
Maximum element is: 15
Minimum element is: 1

Result: Thus the C Program to find minimum and maximum of ‘n’ numbers using
array was successfully executed.
EX:No: 08 Write a program in C that arranges a set of
numbers in ascending order
Date:

Aim:

To write a program in C that arranges a set of numbers in ascending order using a sorting
algorithm.

Algorithm:

We’ll use the Bubble Sort algorithm for simplicity.

1. Start.
2. Input the total number of elements, n.
3. Input the elements into an array, arr[n].
4. Repeat the following steps for i from 0 to n-2:
o Repeat for j from 0 to n-i-2:
 If arr[j] > arr[j+1], swap arr[j] and arr[j+1].
5. Print the sorted array.
6. Stop.

C Program:

#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

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

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

bubbleSort(arr, n);

printf("Sorted numbers in ascending order: ");


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

return 0;
}

Input and Output:

Input:

Enter the number of elements: 5


Enter 5 numbers: 34 7 23 32 5

Output:

csharp

Sorted numbers in ascending order: 5 7 23 32 34

Result:

The program successfully arranges the given numbers in ascending order.


Ex.No.: 9 Write a C program that performs addition and
multiplication of two matrices.
Date:

Aim

To write a C program that performs addition and multiplication of two matrices.

Algorithm

1. Start.
2. Input Dimensions: Accept the number of rows and columns for the matrices.
3. Input Matrices: Enter elements for Matrix A and Matrix B.
4. Matrix Addition:
o If the dimensions of both matrices are the same:
 Perform element-wise addition and store the result in a new matrix.
o Else, display an error message.
5. Matrix Multiplication:
o If the number of columns in Matrix A equals the number of rows in Matrix B:
 Perform matrix multiplication and store the result in another matrix.
o Else, display an error message.
6. Output Results:
o Display the results of addition and multiplication if valid.
7. End.

C Program

#include <stdio.h>

int main() {
int rows1, cols1, rows2, cols2;

// Input dimensions of the matrices


printf("Enter the number of rows and columns of Matrix A: ");
scanf("%d %d", &rows1, &cols1);
printf("Enter the number of rows and columns of Matrix B: ");
scanf("%d %d", &rows2, &cols2);

// Declare matrices
int matrixA[rows1][cols1], matrixB[rows2][cols2];
int sum[rows1][cols1], product[rows1][cols2];

// Input Matrix A
printf("Enter elements of Matrix A:\n");
for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols1; j++)
scanf("%d", &matrixA[i][j]);

// Input Matrix B
printf("Enter elements of Matrix B:\n");
for (int i = 0; i < rows2; i++)
for (int j = 0; j < cols2; j++)
scanf("%d", &matrixB[i][j]);

// Matrix Addition
if (rows1 == rows2 && cols1 == cols2) {
printf("Matrix Addition Result:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
sum[i][j] = matrixA[i][j] + matrixB[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
} else {
printf("Matrix addition not possible. Dimensions must
match.\n");
}

// Matrix Multiplication
if (cols1 == rows2) {
printf("Matrix Multiplication Result:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
product[i][j] = 0;
for (int k = 0; k < cols1; k++)
product[i][j] += matrixA[i][k] * matrixB[k]
[j];
printf("%d ", product[i][j]);
}
printf("\n");
}
} else {
printf("Matrix multiplication not possible. Columns of A
must equal rows of B.\n");
}

return 0;
}
Input/Output Example

Input:

less

Enter the number of rows and columns of Matrix A: 2 2


Enter the number of rows and columns of Matrix B: 2 2
Enter elements of Matrix A:
1 2
3 4
Enter elements of Matrix B:
5 6
7 8

Output:

rust

Matrix Addition Result:


6 8
10 12

Matrix Multiplication Result:


19 22
43 50

Result

The program successfully performs addition and multiplication of two matrices if their dimensions
satisfy the required conditions.
Ex.No. 10. Write a C Program to calculate NCR and NPR.
Date:

Aim:

To write a C program to calculate nCrnCrnCr (combination) and nPrnPrnPr (permutation) for


given values of nnn and rrr.

Algorithm:

1. Input:
o Read values for nnn and rrr.
2. Check validity:
o Ensure r≤nr \leq nr≤n (otherwise, combinations and permutations are not defined).
3. Factorial Function:
o Define a function factorial() that computes the factorial of a given number using a
loop.
4. Calculate nCrnCrnCr:
o Use the formula nCr=n!r!⋅(n−r)!nCr = \frac{n!}{r! \cdot (n - r)!}nCr=r!⋅(n−r)!n!.
5. Calculate nPrnPrnPr:
o Use the formula nPr=n!(n−r)!nPr = \frac{n!}{(n - r)!}nPr=(n−r)!n!.
6. Display the Results:
o Print the values of nCrnCrnCr and nPrnPrnPr.

C Program:

#include <stdio.h>

// Function to calculate factorial


long long factorial(int n) {
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

int main() {
int n, r;
long long nCr, nPr;

// Input values for n and r


printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter the value of r: ");
scanf("%d", &r);

// Validate input
if (r > n || n < 0 || r < 0) {
printf("Invalid input! Ensure that 0 <= r <= n.\n");
return 1;
}

// Calculate nCr and nPr


nCr = factorial(n) / (factorial(r) * factorial(n - r));
nPr = factorial(n) / factorial(n - r);

// Output results
printf("nCr (Combination) = %lld\n", nCr);
printf("nPr (Permutation) = %lld\n", nPr);

return 0;
}

Example Output:

Input:

Enter the value of n: 5


Enter the value of r: 2

Output:
scss

nCr (Combination) = 10
nPr (Permutation) = 20

Result:

The C program successfully calculates the combination (nCrnCrnCr) and permutation (nPrnPrnPr)
for the given values of nnn and rrr.
Ex. No. : 11. Write a C program to count the total number of vowels and consonants in a
given string.
Date:

Aim:

To write a C program to count the total number of vowels and consonants in a given string.

Algorithm:

1. Start
2. Input a string from the user.
3. Initialize two counters, one for vowels and one for consonants, to zero.
4. Loop through each character of the string:
o Check if the character is an alphabet:
 If the character is a vowel (a, e, i, o, u or A, E, I, O, U),
increment the vowel counter.
 Otherwise, increment the consonant counter.
5. Display the total counts of vowels and consonants.
6. End

C Program:

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

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

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Iterate through the string


for (i = 0; str[i] != '\0'; i++) {
// Convert character to lowercase for easy comparison
char ch = tolower(str[i]);

// Check if the character is a vowel or consonant


if (ch >= 'a' && ch <= 'z') { // Ensure it is a letter
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
|| ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}

// Output the result


printf("Total number of vowels: %d\n", vowels);
printf("Total number of consonants: %d\n", consonants);

return 0;
}

Input:

Enter a string: Hello World

Output:

Total number of vowels: 3


Total number of consonants: 7

Result:

The program successfully counts the total number of vowels and consonants in the input string.
Ex. No. 12: Write a C program that reads a sentence and replaces lowercase characters with
uppercase characters and vice versa.
Date:

Aim

To write a C program that reads a sentence and replaces lowercase characters with uppercase
characters and vice versa.

Algorithm

1. Start
2. Read a sentence from the user.
3. Traverse each character of the sentence:
o If the character is a lowercase letter ('a' to 'z'), convert it to uppercase by subtracting
32 or using the toupper() function.
o If the character is an uppercase letter ('A' to 'Z'), convert it to lowercase by adding
32 or using the tolower() function.
o Leave non-alphabetical characters unchanged.
4. Store the modified characters in the output string.
5. Display the resulting sentence.
6. End

C Program

#include <stdio.h>
#include <ctype.h> // For toupper() and tolower()

int main() {
char sentence[1000], modified[1000];
int i;

// Input sentence
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);

// Process each character


for (i = 0; sentence[i] != '\0'; i++) {
if (islower(sentence[i])) {
modified[i] = toupper(sentence[i]); // Convert to
uppercase
} else if (isupper(sentence[i])) {
modified[i] = tolower(sentence[i]); // Convert to
lowercase
} else {
modified[i] = sentence[i]; // Copy non-alphabetic
characters
}
}
modified[i] = '\0'; // Null terminate the modified string

// Output result
printf("Modified sentence: %s", modified);

return 0;
}

Sample Input and Output

Input:

css

Enter a sentence: Hello World!

Output:

yaml

Modified sentence: hELLO wORLD!

Result

The program successfully reads a sentence and converts lowercase characters to uppercase and
vice versa while leaving non-alphabetical characters unchanged.
Group B
Ex.No. 1. Write a C Program to find the grade of a student using else if ladder.
Date:

Aim

To write a C program that calculates and displays the grade of a student based on their marks using
the else-if ladder.

Algorithm

1. Start.
2. Declare variables for marks and grade.
3. Take input for the student's marks.
4. Use an else-if ladder to determine the grade:
o If marks >= 90, grade is 'A'.
o Else if marks >= 80, grade is 'B'.
o Else if marks >= 70, grade is 'C'.
o Else if marks >= 60, grade is 'D'.
o Else, grade is 'F'.
5. Display the grade.
6. Stop.

C Program

#include <stdio.h>

int main() {
int marks;
char grade;

// Input student marks


printf("Enter marks (0-100): ");
scanf("%d", &marks);

// Determine grade using else-if ladder


if (marks >= 90) {
grade = 'A';
} else if (marks >= 80) {
grade = 'B';
} else if (marks >= 70) {
grade = 'C';
} else if (marks >= 60) {
grade = 'D';
} else {
grade = 'F';
}

// Output the result


printf("The grade is: %c\n", grade);

return 0;
}

Output

Example 1:

scss

Enter marks (0-100): 85


The grade is: B

Example 2:

scss

Enter marks (0-100): 56


The grade is: F

Result

The program successfully determines the grade of a student based on their marks using the else-if
ladder.
Ex.No.
2. Write a C Program to implement the various string handling function.
Date:

Aim

To implement and demonstrate various string handling functions in C, including strlen,


strcpy, strcat, and strcmp.

Algorithm

1. Start
2. Include the stdio.h and string.h libraries.
3. Declare two string variables for demonstration.
4. Input two strings from the user.
5. Demonstrate each string function:
o Calculate string length using strlen().
o Copy one string to another using strcpy().
o Concatenate strings using strcat().
o Compare two strings using strcmp().
6. Display the results of each operation.
7. End

C Program

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

int main() {
char str1[100], str2[100], result[200];
int comparison;

// Input two strings from the user


printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0'; // Remove trailing newline
character

printf("Enter the second string: ");


fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0'; // Remove trailing newline
character
// Demonstrating strlen()
printf("\nLength of first string: %lu", strlen(str1));
printf("\nLength of second string: %lu", strlen(str2));

// Demonstrating strcpy()
strcpy(result, str1);
printf("\nAfter copying, result: %s", result);

// Demonstrating strcat()
strcat(result, str2);
printf("\nAfter concatenation, result: %s", result);

// Demonstrating strcmp()
comparison = strcmp(str1, str2);
if (comparison == 0) {
printf("\nThe two strings are equal.");
} else if (comparison < 0) {
printf("\nThe first string is lexicographically
smaller.");
} else {
printf("\nThe first string is lexicographically larger.");
}

return 0;
}

Sample Input and Output

Input

Enter the first string: Hello


Enter the second string: World

Output
sql

Length of first string: 5


Length of second string: 5
After copying, result: Hello
After concatenation, result: HelloWorld
The first string is lexicographically smaller.

Result
The program successfully demonstrates the use of various string handling functions in C, including
strlen(), strcpy(), strcat(), and strcmp().

Ex.No. 3. Write a C Program to create an integer file and displaying the even numbers only
Date:

Aim

To write a C program that creates a file containing integers, reads the file, and displays only the
even numbers.

Algorithm

1. Start
2. Open a file in write mode and input integers from the user to store in the file.
3. Close the file after writing the integers.
4. Open the file in read mode.
5. Read integers one by one from the file.
6. Check if the integer is even:
o If even, display it on the screen.
7. Close the file.
8. Stop

C Program

#include <stdio.h>

int main() {
FILE *file;
int n, num, i;

// Step 1: Create a file and write integers


file = fopen("numbers.txt", "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}

printf("Enter the number of integers to store in the file: ");


scanf("%d", &n);

printf("Enter %d integers:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &num);
fprintf(file, "%d ", num); // Write the integer to the
file
}

fclose(file); // Close the file after writing

// Step 2: Read the file and display even numbers


file = fopen("numbers.txt", "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}

printf("Even numbers from the file are:\n");


while (fscanf(file, "%d", &num) != EOF) {
if (num % 2 == 0) {
printf("%d ", num);
}
}

fclose(file); // Close the file after reading

return 0;
}

Sample Input/Output

Input

Enter the number of integers to store in the file: 5


Enter 5 integers:
10
15
20
25
30

Output
sql

Even numbers from the file are:


10 20 30

Result
The program successfully creates a file with integers, reads the integers from the file, and displays
only the even numbers.

Ex.No. 4. Write a C Program to calculate quadratic equation using switch-case.


Date:

Aim

To write a C program to calculate the roots of a quadratic equation ax2+bx+c=0ax^2 + bx + c =


0ax2+bx+c=0 using the switch-case statement.

Algorithm

1. Start
2. Input the coefficients aaa, bbb, and ccc of the quadratic equation.
3. Calculate the discriminant D=b2−4acD = b^2 - 4acD=b2−4ac.
4. Use a switch-case structure to evaluate the type of roots based on the value of DDD:
o Case 1 (D>0D > 0D>0): Two distinct real roots.
o Case 2 (D==0D == 0D==0): Two equal real roots.
o Case 3 (D<0D < 0D<0): Two complex roots.
5. Compute and display the roots for each case.
6. End

C Program

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

int main() {
double a, b, c, discriminant, root1, root2, realPart,
imaginaryPart;

// Input coefficients
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);

// Calculate discriminant
discriminant = b * b - 4 * a * c;

switch (discriminant > 0 ? 1 : (discriminant == 0 ? 2 : 3)) {


case 1: // D > 0
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: %.2lf, %.2lf\n",
root1, root2);
break;
case 2: // D == 0
root1 = -b / (2 * a);
printf("Roots are real and equal: %.2lf\n", root1);
break;
case 3: // D < 0
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex: %.2lf + %.2lfi, %.2lf -
%.2lfi\n",
realPart, imaginaryPart, realPart,
imaginaryPart);
break;
default:
printf("Error in computation.\n");
}

return 0;
}

Sample Output

Example 1 (Distinct Real Roots):

Input:

css

Enter coefficients a, b and c: 1 -3 2

Output:

sql

Roots are real and distinct: 2.00, 1.00

Example 2 (Equal Real Roots):

Input:

css

Enter coefficients a, b and c: 1 -2 1

Output:

sql
Roots are real and equal: 1.00

Example 3 (Complex Roots):

Input:

css

Enter coefficients a, b and c: 1 2 5

Output:

go

Roots are complex: -1.00 + 2.00i, -1.00 - 2.00i

Result
The program successfully calculates the roots of a quadratic equation using the switch-case
structure based on the discriminant value.

Ex.No.: 5. Write a C Program to count number of characters, words and lines in a text file.
Date:

Aim:

To write a C program to count the number of characters, words, and lines in a given text file.

Algorithm:

1. Start.
2. Open the file in read mode.
3. Initialize counters for characters, words, and lines (charCount, wordCount, and
lineCount) to zero.
4. Read each character from the file using a loop until the end of the file.
o Increment charCount for each character read.
o Check for a newline character ('\n'), and increment lineCount.
o Check for space (' ') or newline ('\n') or tab ('\t') after a sequence of non-
whitespace characters to increment wordCount.
5. Print the values of charCount, wordCount, and lineCount.
6. Close the file.
7. Stop.

C Program:

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

int main() {
FILE *file;
char filename[100], ch;
int charCount = 0, wordCount = 0, lineCount = 0;
int inWord = 0;

// Get the file name from the user


printf("Enter the name of the file: ");
scanf("%s", filename);

// Open the file


file = fopen(filename, "r");

// Check if the file exists


if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1;
}

// Read each character from the file


while ((ch = fgetc(file)) != EOF) {
charCount++;

// Check for new line


if (ch == '\n') {
lineCount++;
}

// Check for word boundaries


if (isspace(ch)) {
inWord = 0;
} else if (!inWord) {
inWord = 1;
wordCount++;
}
}

// Close the file


fclose(file);

// Print the results


printf("Number of characters: %d\n", charCount);
printf("Number of words: %d\n", wordCount);
printf("Number of lines: %d\n", lineCount);

return 0;
}

Output:

Input: A text file sample.txt with the following content:

bash

Hello world!
This is a test file.
It contains multiple lines and words.
Execution:

Enter the name of the file: sample.txt


Number of characters: 65
Number of words: 11
Number of lines: 3

Result:
The program successfully counts and displays the number of characters, words, and lines in the
given text file.

Ex.No. 6. Write a C Program to generate student mark list using array of structures.
Date:

Aim:

To generate a student mark list using an array of structures in C, where the structure contains
student details like name, roll number, and marks for various subjects.

Algorithm:

1. Define a structure Student to store student details: name, roll number, and marks for
each subject.
2. Declare an array of structures to hold multiple student records.
3. Take input for each student's name, roll number, and marks in the subjects.
4. Calculate the total marks and percentage for each student.
5. Display the student details, including name, roll number, marks, total, and percentage.

C Program:

#include <stdio.h>

struct Student {
char name[50];
int roll_no;
float marks[5]; // Assuming 5 subjects
float total;
float percentage;
};

void calculate(struct Student* s) {


s->total = 0;
for (int i = 0; i < 5; i++) {
s->total += s->marks[i];
}
s->percentage = (s->total / 500) * 100; // Total marks = 500
}

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

struct Student students[n];


// Input details for each student
for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Enter Name: ");
scanf(" %[^\n]", students[i].name); // To read string
with spaces
printf("Enter Roll Number: ");
scanf("%d", &students[i].roll_no);
printf("Enter marks for 5 subjects: ");
for (int j = 0; j < 5; j++) {
scanf("%f", &students[i].marks[j]);
}
calculate(&students[i]);
}

// Displaying the mark list


printf("\nStudent Mark List:\n");
printf("Name\tRoll No\tMarks\t\tTotal\tPercentage\n");

printf("--------------------------------------------------------\
n");
for (int i = 0; i < n; i++) {
printf("%s\t%d\t", students[i].name, students[i].roll_no);
for (int j = 0; j < 5; j++) {
printf("%.2f ", students[i].marks[j]);
}
printf("\t%.2f\t%.2f%%\n", students[i].total,
students[i].percentage);
}

return 0;
}

Sample Output:

Enter the number of students: 2

Enter details for student 1:


Enter Name: John Doe
Enter Roll Number: 101
Enter marks for 5 subjects: 85 90 78 92 88

Enter details for student 2:


Enter Name: Jane Smith
Enter Roll Number: 102
Enter marks for 5 subjects: 75 80 85 90 78
Student Mark List:
Name Roll No Marks Total Percentage
--------------------------------------------------------
John Doe 101 85.00 90.00 78.00 92.00 88.00 433.00
86.60%
Jane Smith 102 75.00 80.00 85.00 90.00 78.00 408.00
81.60%
Result:

The program successfully generates a mark list for multiple students using an array of structures. It
calculates the total and percentage for each student and displays their details in a structured format.

Ex.No. 7. Write a C Program to create and process the student mark list using file.
Date:

Aim:

To create and process a student mark list using files in C. The program will allow the user to input
student details (name, roll number, and marks) into a file and then read the file to display the
student information and process the marks.

Algorithm:

1. Open File for Writing:


o Open a file in write mode to store student details.
2. Input Student Data:
o Take student details (name, roll number, marks) from the user.
o Write these details to the file.
3. Close the File:
o Close the file after writing the data.
4. Open File for Reading:
o Open the file in read mode to fetch the stored student details.
5. Display Data:
o Read and display the student details from the file.
6. Processing the Marks:
o Calculate and display the total and average marks of all students.
7. Close the File:
o Close the file after reading the data.

C Program:

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

struct Student {
char name[50];
int rollNo;
float marks[5]; // Array to store marks of 5 subjects
float totalMarks;
float avgMarks;
};
void writeToFile(FILE *file, int n) {
struct Student student;
for (int i = 0; i < n; i++) {
printf("Enter details for student %d\n", i + 1);
printf("Enter Name: ");
getchar(); // To consume newline character from previous
input
fgets(student.name, sizeof(student.name), stdin);
student.name[strcspn(student.name, "\n")] = '\0'; //
Remove newline character

printf("Enter Roll Number: ");


scanf("%d", &student.rollNo);

student.totalMarks = 0;
for (int j = 0; j < 5; j++) {
printf("Enter marks for subject %d: ", j + 1);
scanf("%f", &student.marks[j]);
student.totalMarks += student.marks[j];
}

student.avgMarks = student.totalMarks / 5;
fwrite(&student, sizeof(struct Student), 1, file);
}
}

void readFromFile(FILE *file, int n) {


struct Student student;
fseek(file, 0, SEEK_SET); // Go to the beginning of the file

printf("\nStudent Details:\n");
for (int i = 0; i < n; i++) {
fread(&student, sizeof(struct Student), 1, file);
printf("\nStudent %d\n", i + 1);
printf("Name: %s\n", student.name);
printf("Roll Number: %d\n", student.rollNo);
printf("Marks: ");
for (int j = 0; j < 5; j++) {
printf("%.2f ", student.marks[j]);
}
printf("\nTotal Marks: %.2f\n", student.totalMarks);
printf("Average Marks: %.2f\n", student.avgMarks);
}
}

int main() {
int n;
FILE *file;

printf("Enter number of students: ");


scanf("%d", &n);

file = fopen("student_marks.dat", "wb");


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

// Write student details to file


writeToFile(file, n);

fclose(file);

// Read and process student details from the file


file = fopen("student_marks.dat", "rb");
if (file == NULL) {
printf("Error opening file!\n");
return -1;
}

readFromFile(file, n);

fclose(file);

return 0;
}

Sample Output:

Enter number of students: 2


Enter details for student 1
Enter Name: John Doe
Enter Roll Number: 101
Enter marks for subject 1: 85
Enter marks for subject 2: 90
Enter marks for subject 3: 78
Enter marks for subject 4: 88
Enter marks for subject 5: 92

Enter details for student 2


Enter Name: Jane Smith
Enter Roll Number: 102
Enter marks for subject 1: 80
Enter marks for subject 2: 85
Enter marks for subject 3: 91
Enter marks for subject 4: 79
Enter marks for subject 5: 88

Student Details:

Student 1
Name: John Doe
Roll Number: 101
Marks: 85.00 90.00 78.00 88.00 92.00
Total Marks: 433.00
Average Marks: 86.60

Student 2
Name: Jane Smith
Roll Number: 102
Marks: 80.00 85.00 91.00 79.00 88.00
Total Marks: 423.00
Average Marks: 84.60

Result:
The program successfully stores student marks into a file, reads them back, and displays the data.
It also calculates the total and average marks for each student. The use of file handling allows the
program to persist student data beyond the program's runtime.

Ex.No. 8. Write a C Program to create and process pay bill using file
Date:

Aim:

The aim of this program is to create and process a pay bill using files in C. The program will store
employee details like employee ID, name, hours worked, and pay rate in a file, and then calculate
the pay based on those details. The program will allow the user to input new records and display
the pay bill for each employee from the file.

Algorithm:

1. Create a file paybill.dat for storing employee details.


2. Define a structure Employee with fields like ID, Name, HoursWorked, and PayRate.
3. Use functions to:
o Add employee records to the file.
o Read employee data from the file.
o Calculate and display the total pay.
4. Display the pay bill of each employee, including the calculated pay.

C Program:

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

struct Employee {
int id;
char name[50];
float hoursWorked;
float payRate;
};

// Function to add employee record


void addEmployee(FILE *file) {
struct Employee emp;
printf("Enter employee ID: ");
scanf("%d", &emp.id);
printf("Enter employee name: ");
getchar(); // to clear the newline character from input
buffer
fgets(emp.name, 50, stdin);
printf("Enter hours worked: ");
scanf("%f", &emp.hoursWorked);
printf("Enter pay rate: ");
scanf("%f", &emp.payRate);

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


printf("Employee record added successfully!\n");
}

// Function to display pay bill from the file


void displayPayBill(FILE *file) {
struct Employee emp;
printf("\nPay Bill:\n");
printf("--------------------------------------------------\
n");
printf("ID\tName\t\tHours Worked\tPay Rate\tTotal Pay\n");
printf("--------------------------------------------------\
n");

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


float totalPay = emp.hoursWorked * emp.payRate;
printf("%d\t%s\t%.2f\t\t%.2f\t\t%.2f\n", emp.id, emp.name,
emp.hoursWorked, emp.payRate, totalPay);
}
}

int main() {
FILE *file;
int choice;

file = fopen("paybill.dat", "ab+");


if (file == NULL) {
printf("Unable to open file!\n");
return 1;
}

while (1) {
printf("\nMenu:\n");
printf("1. Add employee record\n");
printf("2. Display pay bill\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
addEmployee(file);
break;
case 2:
fseek(file, 0, SEEK_SET); // Rewind file pointer
to the beginning
displayPayBill(file);
break;
case 3:
fclose(file);
printf("Exiting the program...\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

Sample Output:

Menu:
1. Add employee record
2. Display pay bill
3. Exit
Enter your choice: 1
Enter employee ID: 101
Enter employee name: John Doe
Enter hours worked: 40
Enter pay rate: 20

Employee record added successfully!

Menu:
1. Add employee record
2. Display pay bill
3. Exit
Enter your choice: 1
Enter employee ID: 102
Enter employee name: Alice Smith
Enter hours worked: 35
Enter pay rate: 22

Employee record added successfully!

Menu:
1. Add employee record
2. Display pay bill
3. Exit
Enter your choice: 2

Bill:
--------------------------------------------------
ID Name Hours Worked Pay Rate Total Pay
--------------------------------------------------
101 John Doe 40.00 20.00 800.00
102 Alice Smith 35.00 22.00 770.00

Menu:
1. Add employee record
2. Display pay bill
3. Exit
Enter your choice: 3
Exiting the program...

Result:
 The program successfully stores employee details and calculates their total pay. It provides
an interactive menu to add records, display the pay bill, and exit. The output correctly
displays the pay bill with the calculated total pay for each employee based on hours worked
and pay rate.

Ex.No. 9. Write a C Program to create and process inventory control using file

Date:

Aim:

The aim of this program is to create and process an inventory control system using files in C. The
program allows the user to add, display, and manage inventory items (products) stored in a file.

Algorithm:

1. Create File:
o Create or open a file to store inventory data.
2. Menu-Driven Interface:
o Provide a menu with options to:
 Add new inventory items.
 Display all items.
 Search for a specific item.
 Update an item.
 Delete an item.
 Exit the program.
3. Add Item:
o Collect data (item code, name, quantity, price) from the user and write it to the file.
4. Display Items:
o Read and display the data from the file.
5. Search Item:
o Search for an item by its code and display its details.
6. Update Item:
o Update an existing item’s details.
7. Delete Item:
o Delete an item from the file.
8. Exit Program:
o Close the file and exit.
C Program:

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

struct Item {
int code;
char name[50];
int quantity;
float price;
};

void addItem(FILE *file) {


struct Item item;
printf("\nEnter Item Code: ");
scanf("%d", &item.code);
getchar(); // To consume newline character
printf("Enter Item Name: ");
fgets(item.name, sizeof(item.name), stdin);
item.name[strcspn(item.name, "\n")] = '\0'; // Remove
trailing newline
printf("Enter Item Quantity: ");
scanf("%d", &item.quantity);
printf("Enter Item Price: ");
scanf("%f", &item.price);

fseek(file, 0, SEEK_END);
fwrite(&item, sizeof(struct Item), 1, file);
printf("\nItem added successfully!\n");
}

void displayItems(FILE *file) {


struct Item item;
fseek(file, 0, SEEK_SET);
printf("\nInventory List:\n");
while(fread(&item, sizeof(struct Item), 1, file)) {
printf("\nItem Code: %d\n", item.code);
printf("Item Name: %s\n", item.name);
printf("Quantity: %d\n", item.quantity);
printf("Price: %.2f\n", item.price);
}
}
void searchItem(FILE *file) {
int code;
struct Item item;
printf("\nEnter Item Code to Search: ");
scanf("%d", &code);

fseek(file, 0, SEEK_SET);
while(fread(&item, sizeof(struct Item), 1, file)) {
if(item.code == code) {
printf("\nItem Code: %d\n", item.code);
printf("Item Name: %s\n", item.name);
printf("Quantity: %d\n", item.quantity);
printf("Price: %.2f\n", item.price);
return;
}
}
printf("\nItem not found.\n");
}

void updateItem(FILE *file) {


int code;
struct Item item;
printf("\nEnter Item Code to Update: ");
scanf("%d", &code);

fseek(file, 0, SEEK_SET);
while(fread(&item, sizeof(struct Item), 1, file)) {
if(item.code == code) {
printf("\nEnter New Item Name: ");
getchar(); // To consume newline character
fgets(item.name, sizeof(item.name), stdin);
item.name[strcspn(item.name, "\n")] = '\0'; // Remove
trailing newline
printf("Enter New Item Quantity: ");
scanf("%d", &item.quantity);
printf("Enter New Item Price: ");
scanf("%f", &item.price);

fseek(file, -sizeof(struct Item), SEEK_CUR);


fwrite(&item, sizeof(struct Item), 1, file);
printf("\nItem updated successfully!\n");
return;
}
}
printf("\nItem not found.\n");
}
void deleteItem(FILE *file) {
int code;
FILE *tempFile = fopen("temp.dat", "wb");
struct Item item;
printf("\nEnter Item Code to Delete: ");
scanf("%d", &code);

fseek(file, 0, SEEK_SET);
int found = 0;
while(fread(&item, sizeof(struct Item), 1, file)) {
if(item.code == code) {
found = 1;
} else {
fwrite(&item, sizeof(struct Item), 1, tempFile);
}
}

if(found) {
fclose(file);
fclose(tempFile);
remove("inventory.dat");
rename("temp.dat", "inventory.dat");
printf("\nItem deleted successfully!\n");
} else {
fclose(tempFile);
printf("\nItem not found.\n");
}
}

int main() {
FILE *file = fopen("inventory.dat", "r+b");
if(file == NULL) {
file = fopen("inventory.dat", "wb");
if(file == NULL) {
printf("Unable to open file!\n");
return 1;
}
}

int choice;
do {
printf("\nMenu:\n");
printf("1. Add Item\n");
printf("2. Display Items\n");
printf("3. Search Item\n");
printf("4. Update Item\n");
printf("5. Delete Item\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
addItem(file);
break;
case 2:
displayItems(file);
break;
case 3:
searchItem(file);
break;
case 4:
updateItem(file);
break;
case 5:
deleteItem(file);
break;
case 6:
printf("\nExiting...\n");
break;
default:
printf("\nInvalid choice, please try again.\n");
}
} while(choice != 6);

fclose(file);
return 0;
}

Output:

Menu:
1. Add Item
2. Display Items
3. Search Item
4. Update Item
5. Delete Item
6. Exit
Enter your choice: 1

Enter Item Code: 101


Enter Item Name: Apple
Enter Item Quantity: 50
Enter Item Price: 2.5
Item added successfully!

Menu:
1. Add Item
2. Display Items
3. Search Item
4. Update Item
5. Delete Item
6. Exit
Enter your choice: 2

Inventory List:

Item Code: 101


Item Name: Apple
Quantity: 50
Price: 2.50

Result:
The program successfully manages an inventory control system using a file. The user can add,
display, search, update, and delete items in the inventory, and all data is stored persistently in the
file

Ex.No.: 10. Write a C Program to create and process electricity bill using file
Date:

Aim:

To create a C program that processes electricity bills by reading customer data from a file,
calculating the bill based on usage, and saving the results in an output file.

Algorithm:

1. Start.
2. Open the input file for reading customer data (name, meter number, units consumed).
3. Open the output file to write the processed bill data.
4. For each customer:
o Read the customer details.
o Calculate the bill based on the units consumed.
 Define a price structure (for example, 0-100 units = $1/unit, 101-200 units =
$1.5/unit, etc.).
o Store the customer name, meter number, and total bill in the output file.
5. Close the files.
6. End.

C Program:

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

struct Customer {
char name[50];
int meter_number;
int units;
float bill;
};

// Function to calculate the bill based on units consumed


float calculate_bill(int units) {
float amount = 0;
if (units <= 100) {
amount = units * 1.0;
} else if (units <= 200) {
amount = 100 * 1.0 + (units - 100) * 1.5;
} else if (units <= 300) {
amount = 100 * 1.0 + 100 * 1.5 + (units - 200) * 2.0;
} else {
amount = 100 * 1.0 + 100 * 1.5 + 100 * 2.0 + (units - 300)
* 2.5;
}
return amount;
}

int main() {
FILE *input_file, *output_file;
struct Customer customer;

// Open the input file for reading customer data


input_file = fopen("input.txt", "r");
if (input_file == NULL) {
printf("Error opening input file.\n");
return 1;
}

// Open the output file to write processed data


output_file = fopen("output.txt", "w");
if (output_file == NULL) {
printf("Error opening output file.\n");
fclose(input_file);
return 1;
}

// Write header to output file


fprintf(output_file, "Customer Name\tMeter Number\tUnits
Consumed\tBill Amount\n");

// Process each customer data from input file


while (fscanf(input_file, "%s %d %d", customer.name,
&customer.meter_number, &customer.units) != EOF) {
customer.bill = calculate_bill(customer.units);

// Write the customer bill details to the output file


fprintf(output_file, "%s\t%d\t%d\t%.2f\n", customer.name,
customer.meter_number, customer.units, customer.bill);
}

// Close the files


fclose(input_file);
fclose(output_file);

printf("Bill processing complete. Check the output file for


results.\n");
return 0;
}

Input File (input.txt):

John 101 150


Alice 102 250
Bob 103 90

Output File (output.txt):

javascript

Customer Name Meter Number Units Consumed Bill Amount


John 101 150 175.00
Alice 102 250 275.00
Bob 103 90 90.00

Sample Output:

lua

Bill processing complete. Check the output file for results.


Result:

The program reads customer data from the input file, processes it to calculate the electricity bill,
and writes the results to the output file. The calculations are based on predefined pricing tiers.

Ex.No:. 11. Write a C Program to illustrate how a file stored on the disk is read.
Date:

Aim:

The aim of this program is to demonstrate how to read a file stored on a disk using the C
programming language.

Algorithm:

1. Open the file in read mode using fopen().


2. Check if the file opened successfully.
3. Read the contents of the file using fgetc() or fgets().
4. Display the contents on the console.
5. Close the file using fclose().

C Program:

#include <stdio.h>

int main() {
FILE *file;
char ch;

// Open the file in read mode


file = fopen("example.txt", "r");

// Check if the file opened successfully


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

// Read and display the contents of the file


printf("Contents of the file are:\n");
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
// Close the file
fclose(file);

return 0;
}

Output:

Assuming example.txt contains the following text:

Hello, this is a test file.


It is used to demonstrate file reading in C.

The output on the console would be:

Contents of the file are:


Hello, this is a test file.
It is used to demonstrate file reading in C.
Result:

The program successfully demonstrates how to read the contents of a file stored on the disk. It
reads the file character by character and displays the output on the console.

Ex.No.: 12. Write a C program to read the file and store the lines in an array.
Date:

Aim:

The aim of this program is to read the contents of a file line by line and store each line in an array
of strings. The program will display the lines from the file on the screen.

Algorithm:

1. Open the file in read mode.


2. Read each line of the file using the fgets() function.
3. Store each line in an array of strings (array of character pointers).
4. After reading all lines, close the file.
5. Display the lines stored in the array.

C Program:

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

#define MAX_LINES 100


#define MAX_LENGTH 1000

int main() {
FILE *file;
char *filename = "sample.txt"; // Name of the file to be read
char lines[MAX_LINES][MAX_LENGTH]; // Array to store lines
int i = 0;

// Open the file in read mode


file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open the file %s\n", filename);
return 1;
}

// Read each line from the file and store in the array
while (fgets(lines[i], sizeof(lines[i]), file)) {
i++;
if (i >= MAX_LINES) {
printf("Exceeded maximum number of lines in file\n");
break;
}
}

// Close the file


fclose(file);

// Display the lines stored in the array


printf("\nContents of the file:\n");
for (int j = 0; j < i; j++) {
printf("%s", lines[j]);
}

return 0;
}

Example File Content (sample.txt):

Hello, this is line 1.


This is line 2.
This is line 3.
End of file.

Output:

Contents of the file:


Hello, this is line 1.
This is line 2.
This is line 3.
End of file.
Result:

The program successfully reads the file sample.txt and displays each line stored in the array. It
stores the lines in a 2D character array and outputs them in the same sequence they appear in the
file.

You might also like