C Lab Manual
C Lab Manual
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;
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;
sum = 0;
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);
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.
Aim:
To write a C program to display the given number is Adam number or not.
Algorithm:
Step2: Square the input number n and store the result in square.
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 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:
Step4: Output:
int main() {
int num, reversed_num = 0, remainder;
char str[100];
// Input a number
printf("Enter an integer: ");
scanf("%d", &num);
// Input a string
printf("Enter a string: ");
scanf("%s", str);
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:
After the loop, min will hold the minimum value, and max will hold the maximum value.
Program
#include <stdio.h>
int main() {
int arr[] = {12, 15, 1, 10, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int max, 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:
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>
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);
return 0;
}
Input:
Output:
csharp
Result:
Aim
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;
// 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
Output:
rust
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:
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>
int main() {
int n, r;
long long nCr, nPr;
// Validate input
if (r > n || n < 0 || r < 0) {
printf("Invalid input! Ensure that 0 <= r <= n.\n");
return 1;
}
// Output results
printf("nCr (Combination) = %lld\n", nCr);
printf("nPr (Permutation) = %lld\n", nPr);
return 0;
}
Example Output:
Input:
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;
return 0;
}
Input:
Output:
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);
// Output result
printf("Modified sentence: %s", modified);
return 0;
}
Input:
css
Output:
yaml
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;
return 0;
}
Output
Example 1:
scss
Example 2:
scss
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
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;
// 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;
}
Input
Output
sql
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;
return 0;
}
Sample Input/Output
Input
Output
sql
Result
The program successfully creates a file with integers, reads the integers from the file, and displays
only the even numbers.
Aim
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;
return 0;
}
Sample Output
Input:
css
Output:
sql
Input:
css
Output:
sql
Roots are real and equal: 1.00
Input:
css
Output:
go
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;
return 0;
}
Output:
bash
Hello world!
This is a test file.
It contains multiple lines and words.
Execution:
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;
};
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &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:
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:
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
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);
}
}
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;
fclose(file);
readFromFile(file, n);
fclose(file);
return 0;
}
Sample Output:
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:
C Program:
#include <stdio.h>
#include <stdlib.h>
struct Employee {
int id;
char name[50];
float hoursWorked;
float payRate;
};
int main() {
FILE *file;
int choice;
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
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
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;
};
fseek(file, 0, SEEK_END);
fwrite(&item, sizeof(struct Item), 1, file);
printf("\nItem added successfully!\n");
}
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");
}
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, 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
Menu:
1. Add Item
2. Display Items
3. Search Item
4. Update Item
5. Delete Item
6. Exit
Enter your choice: 2
Inventory List:
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;
};
int main() {
FILE *input_file, *output_file;
struct Customer customer;
javascript
Sample Output:
lua
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:
C Program:
#include <stdio.h>
int main() {
FILE *file;
char ch;
return 0;
}
Output:
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:
C Program:
#include <stdio.h>
#include <stdlib.h>
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;
// 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;
}
}
return 0;
}
Output:
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.