CS25C01 C Programming LAB Manual Updated
CS25C01 C Programming LAB Manual Updated
Semester I
1.Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs.
4.Programs using pointers, dynamic memory, pointer arithmetic, string manipulations, array
operations.
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
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.
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
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
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");
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;
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>
// Main function
int main() {
int len = 10;
int wid = 5;
int 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
10. Free the dynamically allocated memory pointed to by `arr` using `free(arr)`.
12. END
Program
#include <stdio.h>
#include <stdlib.h> // For malloc, free
int main() {
int *arr;
int size;
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Indicate an error
}
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
// Demonstrating Unions
union Data d1; // Declare a union variable
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
return 0;
}
Output
#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
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).
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);
return 0;
}
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).
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.
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.
// 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 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");
}
}
int main() {
char choice;
char mobileToSearch[15];
Contact newContact;
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:
./contact_manager
Result:
Thus the Project in contact Management System Structure created using C Program.is Executed
Successfully.