[go: up one dir, main page]

0% found this document useful (0 votes)
226 views33 pages

CS25C01 C Programming LAB Manual Updated

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

CS25C01 C Programming LAB Manual Updated

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

Dr.

SIVANTHI ADITANAR COLLEGE OF ENGINEERING


TIRUCHENDUR

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

Semester I

CS25C01 Computer Programming: C LAB


LAB MANUAL
[As per Anna University, Chennai–Regulation 2025]

Faculty in-Charge HoD / Cse


SYLLABUS

PRACTICAL EXERCISES: 30 PERIODS

1.Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs.

2.Usage of conditional logics in programs.

3.Usage of functions in programs.

4.Programs using pointers, dynamic memory, pointer arithmetic, string manipulations, array
operations.

5.Program to use structures and unions.

6.Programs reading/writing data in text and binary files.

7.Use of standard and user-defined libraries in solving problems.).

8.Project (Minimum Two).


1.Create Problem Analysis Charts, Flowcharts &
Pseudocode for simple C programs (Minimum three).
Ex.No.1a Find Biggest Number Among Three Numbers.
Aim:
To Write a C Program for Finding Biggest Number among three Numbers.

Problem Analysis Chart (PAC)

Section Description
Input Three numbers N1, N2, N3.
Process Compare the three numbers to identify the largest one.
This can be done by initializing a Max variable with the first number N1 and then
comparing it with the subsequent numbers, N2 & N3 updating Max if a larger number is
found.
Output The Biggest of the three input numbers.

Flowchart
Pseudocode

START
READ N1, N2, N3
SET Max = N1
IF N2 > Max THEN
SET Max = N2
END IF
IF N3 > Max THEN
SET Max = N3
END IF
PRINT Max
END

Algorithm

1.Start the Program

2.Read three numbers, N1, N2, N3.

3.Initialize a variable Max with the value of N1.

4.Compare N2 with Max. If N2 is greater than Max, update Max to N2.

5.Compare N3 with Max. If N3 is greater than Max, update Max to N3.

6.Print the value of Max.

7. End the Program.

C Program

#include <stdio.h>
int main() {
int N1, N2, N3;
int Max;
printf("Enter three numbers: ");
scanf("%d %d %d", &N1, &N2, &N3);
Max = N1;
if (N2 > Max) {
Max = N2;
}
if (N3 > Max) {
Max = N3;
}
printf("The biggest number is: %d\n", Max);
return 0;
}
Output

Result:
Thus the C Program Written for finding Biggest number among Three Numbers is Executed
Successfully.
Ex.No.1.b Find the sum of three numbers & determine if the sum is Odd or Even.
Aim:
To Write a C Program for Finding the sum of three numbers & determine if the sum is
Odd or Even.

Problem Analysis Chart (PAC)

Section Description
Input Three numbers num1, num2, num3.
Process Add three num1, num2, num3 and store it in variable sum and sum is checked to find
even or odd.
Output The sum is odd or even.

Pseudocode

BEGIN
DECLARE num1, num2, num3, sum AS INTEGER

OUTPUT "Enter the first number: "


INPUT num1

OUTPUT "Enter the second number: "


INPUT num2

OUTPUT "Enter the third number: "


INPUT num3

sum = num1 + num2 + num3

OUTPUT "The sum of the three numbers is: ", sum

IF (sum MOD 2 == 0) THEN


OUTPUT "The sum is an EVEN number."
ELSE
OUTPUT "The sum is an ODD number."
END IF
END

Algorithm

1. Start.
2. Input: Obtain three integer numbers from the user. Let these be num1, num2, and num3.
3. Process: Calculate the sum of the three numbers: sum = num1 + num2 + num3.
4. Determine Odd/Even: Check if sum is divisible by 2.
a. If sum % 2 == 0, then the sum is Even.
b. Else (if sum % 2 != 0), then the sum is Odd.
5. Output: Display the calculated sum and whether it is "Odd" or "Even".
6. End.

Program

#include <stdio.h>
int main() {
int num1, num2, num3;
int sum;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter the third number: ");
scanf("%d", &num3);
sum = num1 + num2 + num3;
printf("The sum of the three numbers is: %d\n", sum);
if (sum % 2 == 0) {
printf("The sum is an EVEN number.\n");
} else {
printf("The sum is an ODD number.\n");
}
return 0;
}

Output

Result:
Thus the C Program Written for finding the sum of three numbers & determine if the sum is
Odd or Even is Executed Successfully.
Ex.No.1.c C Program to Perform Basic Arithmetic Operations
Aim:
To Write a C Program to Perform Basic Arithmetic Operations.

Pseudocode

BEGIN
DECLARE INTEGER num1, num2
DECLARE INTEGER sum, difference, product, quotient, remainder_val

DISPLAY "Enter the first number: "


READ num1
DISPLAY "Enter the second number: "
READ num2

sum = num1 + num2


difference = num1 - num2
product = num1 * num2
quotient = num1 / num2 // Warning: No division by zero check
remainder_val = num1 % num2 // Warning: No modulo by zero check

DISPLAY "Sum: ", sum


DISPLAY "Difference: ", difference
DISPLAY "Product: ", product
DISPLAY "Quotient: ", quotient
DISPLAY "Remainder: ", remainder_val
END

Algorithm

1. Start.
2. Declare integer variables num1, num2, sum, difference, product, quotient, remainder_val.
3. Prompt the user to enter the first number.
4. Read the first number into num1.
5. Prompt the user to enter the second number.
6. Read the second number into num2.
7. Calculate sum = num1 + num2.
8. Calculate difference = num1 - num2.
9. Calculate product = num1 * num2.
10. Calculate quotient = num1 / num2 (Note: Division by zero is not handled in this specific
constraint).
11. Calculate remainder_val = num1 % num2 (Note: Modulo by zero is not handled in this
specific constraint).
12. Print the value of sum.
13. Print the value of difference.
14. Print the value of product.
15. Print the value of quotient.
16. Print the value of remainder_val.
17. End.

Program

#include <stdio.h>
int main() {
int num1, num2;
int sum, difference, product, quotient, remainder_val;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
quotient = num1 / num2;
remainder_val = num1 % num2;
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder_val);
return 0;
}

Output

Result:
Thus the C Program Written for Performing Basic Arithmetic Operations is Executed
Successfully.
2.Usage of conditional logics in programs (Minimum three).
Ex.No.2a Perform Decision Making Statement
Aim:
To Write a C Program for Performing Decision Making Statements.

Algorithm

1. Start.
2. Declare Variables: Declare integer variables for demonstration.
3. If-Else Statement:
4. Initialize a variable.
5. Use an if statement to check a condition.
6. Execute a block of code if the condition is true.
7. Use an else statement to execute a different block of code if the condition is false.
8. Else-If Ladder:
9. Initialize a variable.
10. Use an if statement to check the first condition.
11. Use else if statements to check subsequent conditions sequentially.
12. Use a final else statement to handle cases where none of the preceding conditions are met.
13. Switch Statement:
14. Initialize a variable (often representing a choice or option).
15. Use a switch statement to evaluate the variable's value.
16. Define case labels for specific values.
17. Execute the code block associated with a matching case.
18. Use break to exit the switch statement after a match.
19. Include a default case to handle values that don't match any case.
20. End.

Program

#include <stdio.h>
int main() {
// 1. If-Else Statement
int number = 10;
printf("--- If-Else Statement ---\n");
if (number > 5) {
printf("%d is greater than 5.\n", number);
} else {
printf("%d is not greater than 5.\n", number);
}

// 2. Else-If Ladder
int score = 85;
printf("\n--- Else-If Ladder (Grading System) ---\n");
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}

// 3. Switch Statement
int day = 3; // 1 for Monday, 2 for Tuesday, etc.
printf("\n--- Switch Statement (Day of the Week) ---\n");
switch (day) {
case 1:
printf("It's Monday.\n");
break;
case 2:
printf("It's Tuesday.\n");
break;
case 3:
printf("It's Wednesday.\n");
break;
case 4:
printf("It's Thursday.\n");
break;
case 5:
printf("It's Friday.\n");
break;
default:
printf("It's a weekend or invalid day.\n");
break;
}

return 0;
}

Output

Result:
Thus the C Program Written for Performing Decision Making is Executed Successfully.
Ex.No.2b Demonstrating Looping Statement
Aim:
To Write a C Program for Demonstrating all Looping Statements.

Algorithm

1. Start.
2. 1. For Loop:
3. Initialize a counter variable (e.g., i) to a starting value.
4. Define a condition for the loop to continue (e.g., i < N).
5. Define an update expression for the counter (e.g., i++).
6. Execute the loop body for each iteration as long as the condition is true.
7. 2. While Loop:
8. Initialize a variable before the loop.
9. Define a condition for the loop to continue.
10. Execute the loop body as long as the condition is true.
11. Update the variable within the loop body to eventually make the condition false.
12. 3. Do-While Loop:
13. Execute the loop body at least once.
14. Define a condition for the loop to continue.
15. Execute the loop body again if the condition is true.
16. Update the variable within the loop body to eventually make the condition false.
17. 4. Nested Loop:
18. Implement an outer loop (e.g., for or while).
19. Implement an inner loop (e.g., for, while, or do-while) inside the outer loop's body.
20. The inner loop completes all its iterations for each single iteration of the outer loop.
21. End.

Program
#include <stdio.h>

int main() {
// 1. For Loop
printf("--- For Loop ---\n");
for (int i = 0; i < 5; i++) {
printf("For loop iteration: %d\n", i);
}
printf("\n");

// 2. While Loop
printf("--- While Loop ---\n");
int j = 0;
while (j < 5) {
printf("While loop iteration: %d\n", j);
j++;
}
printf("\n");

// 3. Do-While Loop
printf("--- Do-While Loop ---\n");
int k = 0;
do {
printf("Do-While loop iteration: %d\n", k);
k++;
} while (k < 5);
printf("\n");

// 4. Nested Loop (For loops example)


printf("--- Nested Loop ---\n");
for (int outer = 1; outer <= 3; outer++) {
printf("Outer loop iteration: %d\n", outer);
for (int inner = 1; inner <= 2; inner++) {
printf(" Inner loop iteration: %d\n", inner);
}
}

return 0;
}

Output

Result:
Thus the C Program Written for Demonstrating Looping Statement is Executed Successfully.
Ex.No.2c Demonstrating Jumping Statement
Aim:
To Write a C Program for Demonstrating all Jumping Statements.

Algorithm

1. Start.
2. Include Header: Include stdio.h for input/output functions.
3. Main Function: Define the main function, the program's entry point.
4. Break Statement:
5. Implement a for loop that iterates a certain number of times.
6. Inside the loop, use an if condition to check for a specific value.
7. If the condition is met, execute the break statement to terminate the loop prematurely.
8. Continue Statement:
9. Implement a while loop.
10. Inside the loop, use an if condition to check for a specific value.
11. If the condition is met, execute the continue statement to skip the rest of the current iteration
and proceed to the next iteration.
12. Goto Statement:
13. Implement a do-while loop.
14. Inside the loop, use an if condition to check for a specific value.
15. If the condition is met, use goto to jump to a predefined label outside the loop, effectively
exiting the loop.
16. Nested Loops:
17. Implement nested for loops.
18. Demonstrate break and continue within both the inner and outer loops to illustrate their
behavior in nested structures.
19. Output: Use printf statements to display messages indicating the execution flow and the
effects of the jump statements.
20. End.

Program
#include <stdio.h>

int main() {
int i, j;

// --- Demonstrating 'break' in a for loop ---


printf("--- Demonstrating 'break' ---\n");
for (i = 0; i < 10; i++) {
if (i == 5) {
printf("Breaking the loop at i = %d\n", i);
break; // Exits the for loop
}
printf("For loop iteration: %d\n", i);
}
printf("Loop after 'break' has terminated.\n\n");

// --- Demonstrating 'continue' in a while loop ---


printf("--- Demonstrating 'continue' ---\n");
i = 0;
while (i < 5) {
i++;
if (i == 3) {
printf("Continuing to next iteration, skipping print for i = %d\n", i);
continue; // Skips the rest of the current iteration
}
printf("While loop iteration: %d\n", i);
}
printf("While loop finished.\n\n");

// --- Demonstrating 'goto' in a do-while loop ---


printf("--- Demonstrating 'goto' ---\n");
i = 0;
do {
i++;
if (i == 4) {
printf("Using 'goto' to jump out of do-while loop at i = %d\n", i);
goto end_do_while; // Jumps to the specified label
}
printf("Do-while loop iteration: %d\n", i);
} while (i < 5);
end_do_while:
printf("Do-while loop exited using 'goto'.\n\n");

// --- Demonstrating 'break' and 'continue' in nested loops ---


printf("--- Demonstrating in Nested Loops ---\n");
for (i = 1; i <= 3; i++) {
printf("Outer loop iteration: %d\n", i);
for (j = 1; j <= 3; j++) {
if (j == 2) {
printf(" Inner loop: Continuing at j = %d\n", j);
continue; // Skips inner loop's printf for j=2
}
if (i == 2 && j == 3) {
printf(" Inner loop: Breaking inner loop at i=%d, j=%d\n", i, j);
break; // Exits the inner for loop
}
printf(" Inner loop iteration: %d, %d\n", i, j);
}
}
printf("Nested loops finished.\n");

return 0;
}
Output

Result:
Thus the C Program Written for Demonstrating Jumping Statement is Executed Successfully.
3. Usage of functions in programs. (Minimum three).
Ex.No.3 Calculating Area of Rectangle Using Function
Aim:
To Write a C Program for Calculating Area of Rectangle Using Function

Algorithm

1. Start.
2. Declare three integer variables: len, wid, and area.
3. Assign the value 10 to len (the length) and 5 to wid (the width).
4. Call a function named calculateArea, passing len and wid as arguments.
5. Receive the value returned by calculateArea and assign it to the variable area.
6. Print the value stored in area.
7. End.
Algorithm for the calculateArea function
8. Function Start (with two integer arguments: length and width).
9. Declare an integer variable named result.
10. Calculate the product of length and width, and store the result in the result variable.
11. Return the value stored in result.
12. Function End.

Program

#include <stdio.h>

// Function declaration (prototype)


int calculateArea(int length, int width);

// Main function
int main() {
int len = 10;
int wid = 5;
int area;

// Calling the calculateArea function


area = calculateArea(len, wid);

printf("The area of the rectangle is: %d\n", area);

return 0;
}

// Function definition
int calculateArea(int length, int width) {
int result = length * width;
return result; // Returning the calculated area
}
Output

Result:
Thus the C Program Written for Calculating Area of Rectangle Using Function is Executed
Successfully.
4. Programs using pointers, dynamic memory, pointer arithmetic,
string manipulations, array operations. (Minimum three)
Ex.No.4 Demonstrating Dynamic Array with Pointer Arithmetic and Array Operations
Aim:
To Write a C Program for Demonstrating Dynamic Array with Pointer Arithmetic and Array
Operations.

Algorithm

1. START

2. Declare an integer pointer `arr` and an integer variable `size`.

3. Prompt the user to enter the desired `size` of the array.

4. Read the `size` from the user input.

5. Dynamically allocate memory for `size` number of integers using `malloc`.


Assign the returned pointer to `arr`.
Check if `malloc` returned `NULL` (indicating memory allocation failure).
If `arr` is `NULL`, print an error message and exit with an error code.

6. Prompt the user to enter `size` integer elements.

7. Loop from `i = 0` to `size - 1`:


Read an integer from the user and store it at the memory location pointed to by `(arr + i)`
(using pointer arithmetic).

8. Print a message indicating the array elements.

9. Loop from `i = 0` to `size - 1`:


Print the integer value stored at the memory location pointed to by `(arr + i)` (dereferencing
with `*`).

10. Free the dynamically allocated memory pointed to by `arr` using `free(arr)`.

11. Set `arr` to `NULL` to prevent dangling pointers.

12. END

Program

#include <stdio.h>
#include <stdlib.h> // For malloc, free

int main() {
int *arr;
int size;

printf("Enter the size of the array: ");


scanf("%d", &size);
// Dynamically allocate memory for the array
arr = (int *)malloc(size * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Indicate an error
}

printf("Enter %d integer elements:\n", size);


for (int i = 0; i < size; i++) {
scanf("%d", (arr + i)); // Using pointer arithmetic to access elements
}

printf("Array elements are: ");


for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i)); // Using pointer arithmetic to dereference
}
printf("\n");

// Free the dynamically allocated memory


free(arr);
arr = NULL; // Set pointer to NULL after freeing

return 0;
}

Output

Result:
Thus the C Program Written for Demonstrating Dynamic Array with Pointer Arithmetic and
Array Operations is Executed Successfully.
5.Program to use structures and unions.
Ex.No.5 Demonstrating structures and unions
Aim:
To Write a C Program for demonstrating structures and unions.

Algorithm

1. Start.
2. Declare a struct named Student with the following members:
3. int roll_no
4. char name
5. float marks
6. Declare a union named Data with the following members:
7. int i_val
8. float f_val
9. char s_val
10. Main Function Execution:
11. Demonstrating Structures:
12. Declare a struct Student variable s1.
13. Assign values to s1's members:
14. s1.roll_no = 101
15. strcpy(s1.name, "Alice Smith")
16. s1.marks = 85.5
17. Print the assigned values of s1's members using printf.
18. Demonstrating Unions:
19. Declare a union Data variable d1.
20. Integer Value:
21. Assign d1.i_val = 123.
22. Print d1.i_val.
23. Float Value:
24. Assign d1.f_val = 45.67 (this overwrites the previous i_val in the shared memory).
25. Print d1.f_val.
26. String Value:
27. Assign strcpy(d1.s_val, "Hello Union!") (this overwrites the previous f_val in the shared
memory).
28. Print d1.s_val.
29. Illustrating Memory Sharing:
30. Attempt to access and print d1.i_val and d1.f_val after d1.s_val has been assigned,
demonstrating that these values will likely be corrupted or unexpected due to memory
overlap.
31. Print Sizes:
32. Print the size of struct Student using sizeof(struct Student).
33. Print the size of union Data using sizeof(union Data).
34. Return:
35. Return 0 to indicate successful program execution.
36. End.
Program

#include <stdio.h>
#include <string.h> // For strcpy

// Define a structure
struct Student {
int roll_no;
char name[50];
float marks;
};

// Define a union
union Data {
int i_val;
float f_val;
char s_val[20];
};

int main() {
// Demonstrating Structures
struct Student s1; // Declare a structure variable

// Assign values to structure members


s1.roll_no = 101;
strcpy(s1.name, "Alice Smith");
s1.marks = 85.5;

// Access and print structure members


printf("--- Student Information (Structure) ---\n");
printf("Roll No: %d\n", s1.roll_no);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n\n", s1.marks);

// Demonstrating Unions
union Data d1; // Declare a union variable

// Assign and access integer value


d1.i_val = 123;
printf("--- Data (Union) ---\n");
printf("Integer value: %d\n", d1.i_val); // Only this value is valid here

// Assign and access float value (overwrites previous)


d1.f_val = 45.67;
printf("Float value: %.2f\n", d1.f_val); // Only this value is valid here

// Assign and access string value (overwrites previous)


strcpy(d1.s_val, "Hello Union!");
printf("String value: %s\n", d1.s_val); // Only this value is valid here
// Illustrating memory sharing in union (accessing other members after string assignment)
printf("\nAccessing other members after string assignment (will show garbage/unexpected
values):\n");
printf("Integer value (after string): %d\n", d1.i_val);
printf("Float value (after string): %.2f\n", d1.f_val);

// Print sizes to demonstrate memory allocation difference


printf("\nSize of Student structure: %lu bytes\n", sizeof(struct Student));
printf("Size of Data union: %lu bytes\n", sizeof(union Data));

return 0;
}

Output

Result:
Thus the C Program Written for demonstrating structures and unions is Executed
Successfully.
6.Programs reading/writing data in text and binary files
(Minimum three).

Ex.No.6 Text File Operations (Reading and Writing) & Binary File Operations (Reading and
Writing)
Aim:

To Write a C Program for demonstrating Text File Operations (Reading and Writing) &
Binary File Operations (Reading and Writing)
Algorithm

1. Start.
2. Include Headers:
3. stdio.h: Provides standard input/output functions like fopen, fclose, fprintf, fgets, printf.
4. stdlib.h: Provides general utility functions, including exit for program termination in case of
errors.
5. File Writing:
6. Open File for Writing: Use fopen("example.txt", "w").
7. "example.txt" is the name of the file to be created or overwritten.
8. "w" specifies write mode, meaning if the file exists, its content will be erased; otherwise, a
new file will be created.
9. Error Handling: Check if fptr (the file pointer) is NULL. If so, an error occurred during file
opening, and the program exits with an error message.
10. Write Data: Use fprintf(fptr, "...") to write formatted strings to the file.
11. Close File: Use fclose(fptr) to release the file resources after writing is complete.
12. File Reading:
13. Open File for Reading: Use fopen("example.txt", "r").
14. "r" specifies read mode.
15. Error Handling: Similar to writing, check fptr for NULL to handle potential errors during file
opening.
16. Read Data Line by Line: Use a while loop with fgets(text_data, sizeof(text_data), fptr).
17. fgets reads a line of text from the file until a newline character or sizeof(text_data) characters
are read, storing it in text_data.
18. The loop continues as long as fgets successfully reads a line (returns a non-NULL value).
19. Print Data: Print the read text_data to the console using printf("%s", text_data).
20. Close File: Use fclose(fptr) to close the file after reading.
21. Program Termination: Return 0 from main to indicate successful execution.
22. This algorithm provides a robust way to interact with text files in C, ensuring proper file
handling and error management.
23. End.

Program

Text File Operations (Reading and Writing)


#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *fptr;
char text_data[100];

// Writing to a text file


fptr = fopen("example.txt", "w"); // "w" for write mode (creates or overwrites)
if (fptr == NULL) {
printf("Error opening file for writing!\n");
exit(1);
}
fprintf(fptr, "Hello, this is a text file.\n");
fprintf(fptr, "This is the second line.\n");
fclose(fptr);
printf("Text data written to example.txt\n");

// Reading from a text file


fptr = fopen("example.txt", "r"); // "r" for read mode
if (fptr == NULL) {
printf("Error opening file for reading!\n");
exit(1);
}
printf("\nReading from example.txt:\n");
while (fgets(text_data, sizeof(text_data), fptr) != NULL) {
printf("%s", text_data);
}
fclose(fptr);

return 0;
}

Output

Binary File Operations (Reading and Writing)

#include <stdio.h>
#include <stdlib.h> // For exit()

typedef struct {
int id;
char name[20];
float score;
} Student;

int main() {
FILE *fptr;
Student s1 = {101, "Alice", 85.5};
Student s2; // To store data read from file

// Writing to a binary file


fptr = fopen("students.bin", "wb"); // "wb" for write binary mode
if (fptr == NULL) {
printf("Error opening file for writing!\n");
exit(1);
}
fwrite(&s1, sizeof(Student), 1, fptr); // Write one Student structure
fclose(fptr);
printf("Student data written to students.bin\n");

// Reading from a binary file


fptr = fopen("students.bin", "rb"); // "rb" for read binary mode
if (fptr == NULL) {
printf("Error opening file for reading!\n");
exit(1);
}
fread(&s2, sizeof(Student), 1, fptr); // Read one Student structure
printf("\nReading from students.bin:\n");
printf("ID: %d, Name: %s, Score: %.2f\n", s2.id, s2.name, s2.score);
fclose(fptr);

return 0;
}

Output

Result:

Thus the C Program Written for demonstrating Text File Operations (Reading and Writing) & Binary
File Operations (Reading and Writing) is Executed Successfully.
7.Use of standard and user-defined libraries in solving problems.
(Minimum
three).

Ex.No.7 Calculating Area of a Circle


Aim:
To Write a C Program for finding Area of a Circle Use of standard and user-defined libraries
in solving problems.

Algorithm

1. Start.
2. math.h: Provides mathematical functions like sqrt (for square root) and the M_PI constant (for
pi).
3. Declare Function Prototype:
4. float calculateCircleArea(float radius);: Declares a user-defined function named
calculateCircleArea that takes a float (radius) as input and returns a float (area).
5. Main Function (main):
6. Declare Variables:
7. float radius: To store the radius entered by the user.
8. float area: To store the calculated area of the circle.
9. float squareRootOfArea: To store the square root of the calculated area.
10. Get Input:
11. printf("Enter the radius of the circle: ");: Prompts the user to enter the radius.
12. scanf("%f", &radius);: Reads the floating-point value entered by the user and stores it in the
radius variable.
13. Calculate Area:
14. area = calculateCircleArea(radius);: Calls the calculateCircleArea function with the entered
radius and stores the returned area in the area variable.
15. Calculate Square Root:
16. squareRootOfArea = sqrt(area);: Calls the sqrt function (from math.h) to calculate the square
root of the area and stores the result in squareRootOfArea.
17. Display Results:
18. printf("The area of the circle with radius %.2f is %.2f\n", radius, area);: Prints the calculated
area, formatted to two decimal places.
19. printf("The square root of the area is %.2f\n", squareRootOfArea);: Prints the calculated
square root of the area, formatted to two decimal places.
20. Return:
21. return 0;: Indicates successful program execution.
22. User-Defined Function (calculateCircleArea):
23. Definition:
24. float calculateCircleArea(float radius) { ... }: Defines the function to calculate the area.
25. Calculation:
26. return M_PI * radius * radius;: Calculates the area using the formula πr² (where M_PI is the
constant for pi from math.h) and returns the result.
27. End.
Program
#include <stdio.h> // Standard library for input/output functions like printf and scanf
#include <math.h> // Standard library for mathematical functions like sqrt
// User-defined function prototype: calculates the area of a circle
float calculateCircleArea(float radius);
int main() {
float radius, area, squareRootOfArea;
// Using a standard library function (printf) for output
printf("Enter the radius of the circle: ");
// Using a standard library function (scanf) for input
scanf("%f", &radius);

// Calling the user-defined function to calculate area


area = calculateCircleArea(radius);

// Using a standard library function (sqrt) to find the square root


squareRootOfArea = sqrt(area);

// Using a standard library function (printf) for output


printf("The area of the circle with radius %.2f is %.2f\n", radius, area);
printf("The square root of the area is %.2f\n", squareRootOfArea);

return 0;
}

// User-defined function definition: calculates the area of a circle


float calculateCircleArea(float radius) {
// Using a standard library constant (M_PI from math.h)
return M_PI * radius * radius;
}

Output

Result:
Thus the C Program Written for finding Area of a Circle Use of standard and user-defined
libraries in solving problems.is Executed Successfully.
8.Project (Minimum Two).

Ex.No.8 Contact Management System Structure


Aim:
To Create a Project in contact Management System Structure using C Program.

Program

Creating a C program as a "project" typically implies building a more substantial application than a
single-file script, often involving multiple source files, data structures, and potentially file handling.

Here's an example of a simple C project: a Contact Management System. This project involves
storing, adding, viewing, updating, and deleting contact information.

Key Components of a C Project:

 Header Files (.h): These define data structures, function prototypes, and macros. They are
included in source files to provide necessary declarations.
 Source Files (.c): These contain the actual implementation of functions.
 Main Function: The entry point of the program, typically in a main.c file, which orchestrates
the project's functions.
 File Handling: For projects that need to persist data, file I/O operations are crucial.

Example: Contact Management System Structure

1. contact.h (Header File):


#ifndef CONTACT_H
#define CONTACT_H

// Structure to hold contact information


typedef struct {
char firstName[50];
char lastName[50];
char mobileNumber[15]; // Unique identifier
char workNumber[15];
char homeNumber[15];
} Contact;

// Function prototypes
void addContact(Contact *c);
void viewContacts();
void updateContact(const char *mobileNum);
void deleteContact(const char *mobileNum);
void saveContactsToFile(const char *filename);
void loadContactsFromFile(const char *filename);

#endif // CONTACT_H
2. contact.c (Source File for Contact Operations):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contact.h"

// Global array to store contacts (for simplicity, in a real project, dynamic allocation or a linked list
would be better)
Contact contacts[100];
int contactCount = 0;

void addContact(Contact *c) {


if (contactCount < 100) {
strcpy(contacts[contactCount].firstName, c->firstName);
strcpy(contacts[contactCount].lastName, c->lastName);
strcpy(contacts[contactCount].mobileNumber, c->mobileNumber);
strcpy(contacts[contactCount].workNumber, c->workNumber);
strcpy(contacts[contactCount].homeNumber, c->homeNumber);
contactCount++;
printf("Contact added successfully.\n");
} else {
printf("Contact list is full.\n");
}
}

void viewContacts() {
if (contactCount == 0) {
printf("No contacts to display.\n");
return;
}
printf("\n--- Contact List ---\n");
for (int i = 0; i < contactCount; i++) {
printf("Name: %s %s\n", contacts[i].firstName, contacts[i].lastName);
printf("Mobile: %s\n", contacts[i].mobileNumber);
printf("Work: %s\n", contacts[i].workNumber);
printf("Home: %s\n", contacts[i].homeNumber);
printf("--------------------\n");
}
}

// ... (Implement updateContact, deleteContact, saveContactsToFile, loadContactsFromFile)


// For example, saveContactsToFile might look like this:
void saveContactsToFile(const char *filename) {
FILE *fp = fopen(filename, "wb"); // "wb" for binary write
if (fp == NULL) {
perror("Error opening file for writing");
return;
}
fwrite(&contactCount, sizeof(int), 1, fp); // Save count first
fwrite(contacts, sizeof(Contact), contactCount, fp); // Save all contacts
fclose(fp);
printf("Contacts saved to %s.\n", filename);
}
3. main.c (Main Program Logic):
#include <stdio.h>
#include <string.h>
#include "contact.h" // Include our contact header

int main() {
char choice;
char mobileToSearch[15];
Contact newContact;

loadContactsFromFile("contacts.dat"); // Load contacts on startup

do {
printf("\n--- Contact Management Menu ---\n");
printf("1. Add Contact\n");
printf("2. View Contacts\n");
printf("3. Update Contact\n");
printf("4. Delete Contact\n");
printf("5. Save & Exit\n");
printf("Enter your choice: ");
scanf(" %c", &choice);

switch (choice) {
case '1':
printf("Enter First Name: "); scanf("%s", newContact.firstName);
printf("Enter Last Name: "); scanf("%s", newContact.lastName);
printf("Enter Mobile Number: "); scanf("%s", newContact.mobileNumber);
printf("Enter Work Number: "); scanf("%s", newContact.workNumber);
printf("Enter Home Number: "); scanf("%s", newContact.homeNumber);
addContact(&newContact);
break;
case '2':
viewContacts();
break;
case '3':
printf("Enter Mobile Number of contact to update: "); scanf("%s", mobileToSearch);
updateContact(mobileToSearch); // You'd implement this in contact.c
break;
case '4':
printf("Enter Mobile Number of contact to delete: "); scanf("%s", mobileToSearch);
deleteContact(mobileToSearch); // You'd implement this in contact.c
break;
case '5':
saveContactsToFile("contacts.dat");
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != '5');

return 0;
}
Compilation:

To compile this project, you would typically use a C compiler like GCC:

gcc main.c contact.c -o contact_manager

Then, you can run the executable:

./contact_manager

Result:
Thus the Project in contact Management System Structure created using C Program.is Executed
Successfully.

You might also like