CS25C01-COMPUTER - PROGRAMMING-C LAB MANUAL
CS25C01-COMPUTER - PROGRAMMING-C LAB MANUAL
UNIT TITLES
Output Sum
ALGORITHM:
1. Start
2. Declare three variables: num1, num2, and sum.
3. Read the value of num1.
4. Read the value of num2.
5. Compute sum = num1 + num2.
6. Display the value of sum.
7. Stop
PSEUDOCODE:
BEGIN
DECLARE num1, num2, sum AS INTEGER
PRINT "Enter first number:"
READ num1
PRINT "Enter second number:"
READ num2
sum ← num1 + num2
PRINT "Sum = ", sum
END
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main() {
int num1, num2, sum;
return 0;
}
OUTPUT:
Enter first number: 5
Enter second number: 6
Sum = 11
RESULT:
Thus, the C program to add two numbers was executed successfully.
EX.NO DATE
TO CONVERT TEMPERATURE FROM CELSIUS TO
1B
FAHRENHEIT
AIM:
To create problem analysis charts, flowcharts and pseudocode to convert
temperature from celsius to Fahrenheit C programs.
PROBLEM ANALYSIS CHARTS:
Required Results
Given Data (Input) Processing (Formula/Steps)
(Output)
1. Read the temperature
value in Celsius.
2. Calculate the Fahrenheit
The equivalent value using the formula:
A temperature value
temperature value in F=C×95+32cap F equals
in Celsius (°C).
Fahrenheit (°F). cap C cross nine-fifths plus
𝐹=𝐶×95+32
32
fahrenheit ← (celsius * 9 / 5) + 32
PROGRAM:
#include <stdio.h>
int main() {
float celsius, fahrenheit;
return 0;
}
OUTPUT:
Enter temperature in Celsius: 20
Temperature in Fahrenheit = 68.00
RESULT:
Thus, the C program to convert temperature from Celsius to
Fahrenheit was executed successfully.
EX.NO DATE
TO SWAP TWO NUMBERS
1C
AIM:
To create problem analysis charts, flowcharts and pseudocode to Swap Two
Numbers using C program.
PROBLEM ANALYSIS CHARTS:
ALGORITHM:
Step-1 Start
Step-2 Input Two Numbers Say NUM1,NUM2
Step-3 Display Before Swap Values NUM1, NUM2
Step-4 TEMP = NUM1
Step-5 NUM1 = NUM2
Step-6 NUM2 = NUM1
Step-7 Display After Swap Values NUM1,NUM
Step-8 Stop
PSEUDOCODE:
BEGIN
DECLARE A, B, temp AS INTEGER
PRINT "Enter two numbers:"
READ A, B
temp ← A
A←B
B ← temp
PRINT "After swapping: A =", A, " B =", B
END
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main() {
int A, B, C;
printf("Enter two numbers: ");
scanf("%d %d", &A, &B);
C = A;
A = B;
B = C;
printf("After swapping: A = %d, B = %d\n", A, B);
return 0;
}
OUTPUT:
Enter two numbers: 55 25
After swapping: A = 25, B = 55
RESULT:
Thus, the C program to swap two numbers was executed successfully.
USAGE OF CONDITIONAL LOGICS IN PROGRAMS.
EX.NO DATE
CHECK IF A NUMBER IS POSITIVE,
2A
NEGATIVE, OR ZERO
AIM:
To check if a number is positive, negative, or zero using conditionals
statements.
PROBLEM ANALYSIS CHARTS:
IF n > 0 THEN
PRINT "Number is Positive"
ELSE IF n < 0 THEN
PRINT "Number is Negative"
ELSE
PRINT "Number is Zero"
END IF
END
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n > 0) {
printf("Number is Positive\n");
}
else if (n < 0) {
printf("Number is Negative\n");
}
else {
printf("Number is Zero\n");
}
return 0;
}
OUTPUT:
Enter a number: 50
Number is Positive
Enter a number: -23
Number is Negative
Enter a number: 00
Number is Zero
RESULT:
Thus, the C program to check whether a given number is positive,
negative, or zero using conditional statements was executed successfully.
EX.NO DATE
2B TO CHECK FOR ODD OR EVEN NUMBER
AIM:
To check for odd or even number using conditionals statements.
PROBLEM ANALYSIS CHART:
Input Output Processing Logic
A number n A message stating 1. Divide the number n by 2
whether the number using the modulus operator %
is Odd or Even
2. If n % 2 == 0, then the number is
Even
3. Else, the number is Odd
ALGORITHM:
1. Start
2. Input a number n
3. Check if n % 2 == 0
If true, then the number is Even
If false, then the number is Odd
4. Display the result (Odd or Even)
5. Stop
PSEUDOCODE:
START
READ n
IF n % 2 == 0 THEN
PRINT "Even number"
ELSE
PRINT "Odd number"
ENDIF
STOP
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num % 2 == 0)
printf("%d is Even\n", num);
else
printf("%d is Odd\n", num);
return 0;
}
OUTPUT:
Enter a number: 10
10 is Even
Enter a number: 5
5 is Odd
RESULT:
Thus, the C program to check whether a number is odd or even using
conditional statements was designed, implemented, and executed successfully
EX.NO DATE
2c TO CHECK ARMSTRONG NUMBER
AIM:
To Check Armstrong Number using conditionals statements.
PROBLEM ANALYSIS CHART:
Input Output Processing Logic
1. Copy the number into a temporary
variable.
2. Count the number of digits in
A message stating the number.
whether the number is 3. Extract each digit, raise it to the
A number n
Armstrong or Not power of the number of digits, and
Armstrong add to sum.
4. After processing all digits:
If sum == original number →
Armstrong Number
Else → Not Armstrong Number
ALGORITHM:
1. Start
2. Input a number n
3. Store the number in a temporary variable temp
4. Count the number of digits in n → digits
5. Initialize sum = 0
6. Repeat until n becomes 0:
Extract the last digit → digit = n % 10
Compute digit^digits and add to sum
Remove the last digit → n = n / 10
7. If sum == temp, then the number is an Armstrong number
Else, it is not an Armstrong number
8. Stop
PSEUDOCODE:
START
READ n
SET temp = n
SET sum = 0
FIND number of digits = digits
WHILE n > 0 DO
digit = n % 10
sum = sum + (digit ^ digits)
n = n / 10
END WHILE
IF sum == temp THEN
PRINT "Armstrong
number"
ELSE
PRINT "Not Armstrong number"
END IF
STOP
FLOWCHART:
PROGRAM:
#include <stdio.h>
#include <math.h>
int main() {
int num, temp, digit, digits = 0;
double sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
// Count digits
int n = num;
while(n > 0) {
n /= 10;
digits++;
}
n = num;
while(n > 0) {
digit = n % 10;
sum += pow(digit, digits);
n /= 10;
}
if((int)sum == temp)
printf("%d is an Armstrong number.\n", temp);
else
printf("%d is not an Armstrong number.\n", temp);
return 0;
}
OUTPUT:
Enter a number: 153
153 is an Armstrong number.
RESULT:
ALGORITHM:
1. Start
2. Display the menu of operations (Addition, Subtraction,
Multiplication, Division, Modulus, Power, Square Root, etc.)
3. Input user's choice
4. Use switch statement to perform the selected operation
5. For each case:
Input required numbers
Perform operation
Display result
6. If invalid choice → display error message
7. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
#include <math.h>
int main()
{ int
choice;
double num1, num2, result;
printf("Scientific Calculator\n");
printf("1. Addition (+)\n");
printf("2. Subtraction (-)\n");
printf("3. Multiplication (*)\n");
printf("4. Division (/)\n");
printf("5. Modulus (%%)\n");
printf("6. Power (^)\n");
printf("7. Square Root (√)\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{ case 1: //
Addition
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case 2: // Subtraction
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case 3: // Multiplication
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case 4: // Division
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
if(num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
} else {
printf("Error: Division by zero!\n");
}
break;
case 5: // Modulus
{
int a, b, res;
printf("Enter two integers:
"); scanf("%d %d", &a, &b);
if(b != 0) {
res = a % b;
printf("Result: %d\n", res);
} else {
printf("Error: Division by zero!\n");
}
}
break;
case 6: // Power
printf("Enter base and exponent: ");
scanf("%lf %lf", &num1, &num2);
result = pow(num1, num2);
printf("Result: %.2lf\n", result);
break;
case 7: // Square Root
printf("Enter a number: ");
scanf("%lf", &num1);
if(num1 >= 0) {
result = sqrt(num1);
printf("Result: %.2lf\n", result);
} else {
printf("Error: Negative number cannot have real square root!\n");
}
break;
default:
printf("Invalid choice!\n");
}
return 0;
}
OUTPUT:
Scientific Calculator
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
6. Power (^)
7. Square Root (√)
Enter your choice: 1
Enter two numbers: 78
50
Result: 128.00
Scientific Calculator
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
6. Power (^)
7. Square Root (√)
Enter your choice: 7
Enter a number: 49
Result: 7.00
RESULT:
Thus, the C program to design a scientific calculator using switch case was
executed successfully.
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
TO DISPLAY PRIME NUMBERS BETWEEN TWO
3A INTERVALS USING FUNCTIONS
AIM:
To Display Prime Numbers between Two Intervals Using
Functions.
ALGORITHM:
1. Start
2. Input two numbers: lower and upper (interval)
3. For each number n from lower to upper:
o Call a function isPrime(n) to check if n is prime
o If isPrime(n) returns true → print n
4. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
#include <math.h>
// Function to check prime
int isPrime(int num) {
if (num <= 1)
return 0; // Not prime
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0)
return 0; // Not prime
}
return 1; // Prime
}
int main() {
int lower, upper;
printf("Enter the lower and upper limits: ");
scanf("%d %d", &lower, &upper);
return 0;
}
OUTPUT:
Enter the lower and upper limits: 1 100
Prime numbers between 1 and 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
RESULT:
Thus, the C program to display prime numbers between two intervals
using functions was executed successfully.
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
TO CHECK QUADRATIC EQUATION ROOTS USING
3b FUNCTIONS
AIM:
To check quadratic equation roots using functions.
ALGORITHM:
1. Start
2. Input coefficients a, b, and c of the quadratic equation ax² + bx + c = 0
3. Call a function findRoots(a, b, c) to determine the roots
4. Inside findRoots function:
o Calculate the discriminant D = b² - 4ac
o If D > 0, roots are real and distinct
o If D == 0, roots are real and equal
o If D < 0, roots are complex
o Display the roots
5. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
#include <math.h>
// Function to find roots of quadratic equation
void findRoots(int a, int b, int c) {
float D = b*b - 4*a*c;
float root1, root2, realPart, imagPart;
if (D > 0) {
root1 = (-b + sqrt(D)) / (2*a);
root2 = (-b - sqrt(D)) / (2*a);
printf("Roots are real and distinct: %.2f and %.2f\n", root1, root2);
} else if (D == 0) {
root1 = root2 = -b / (2.0*a);
printf("Roots are real and equal: %.2f and %.2f\n", root1, root2);
} else {
realPart = -b / (2.0*a);
imagPart = sqrt(-D) / (2.0*a);
printf("Roots are complex: %.2f + %.2fi and %.2f - %.2fi\n", realPart,
imagPart, realPart, imagPart);
}
}
int main()
{ int a, b,
c;
printf("Enter coefficients a, b, and c: ");
scanf("%d %d %d", &a, &b, &c);
findRoots(a, b, c);
return 0;
}
OUTPUT:
Enter coefficients a, b, and c: 2 1 3
Roots are complex: -0.25 + 1.20i and -0.25 - 1.20i
RESULT:
Thus, the C program to find the roots of a quadratic equation using functions
was executed successfully.
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
3C
SWAPPING TWO NUMBERS USING CALL BY
VALUE AND CALL BY REFERENCE IN C
AIM:
To check swapping two numbers using call by value and call by reference
in c
ALGORITHM
Call by Value
1. Start
2. Input two numbers a and b
3. Call a function swap(a, b)
4. Inside the function, swap the values using a temporary variable
5. Return to main function (values of a and b in main remain unchanged)
6. End
Call by Reference
1. Start
2. Input two numbers a and b
3. Call a function swap(&a, &b) (pass addresses)
4. Inside the function, swap the values using a temporary variable
5. Values of a and b in main function are swapped
6. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
// Call by Value
void swapByValue(int x, int y) {
int temp = x;
x = y;
y = temp;
printf("Inside swapByValue function: a = %d, b = %d\n", x, y);
}
// Call by Reference
void swapByReference(int *x, int *y)
{ int temp = *x;
*x = *y;
*y = temp;
}
int main()
{ int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("\n---Using Call by Value---\n");
printf("Before swapping: a = %d, b = %d\n", a, b);
swapByValue(a, b);
printf("After function call: a = %d, b = %d\n", a, b); // Values unchanged
printf("\n---Using Call by Reference---\n");
printf("Before swapping: a = %d, b = %d\n", a, b);
swapByReference(&a, &b);
printf("After function call: a = %d, b = %d\n", a, b); // Values swapped
return 0;
}
OUTPUT:
Enter two numbers: 45 78
---Using Call by Value---
Before swapping: a = 45, b = 78
Inside swapByValue function: a = 78, b = 45
After function call: a = 45, b = 78
---Using Call by Reference---
Before swapping: a = 45, b = 78
After function call: a = 78, b = 45
RESULT:
Thus, the C program to swap two numbers using Call by Value and Call by
Reference was executed successfully.
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
3d
TO FIND SUM OF NATURAL NUMBERS
USING RECURSION
AIM:
To find sum of natural numbers using recursion
ALGORITHM:
1. Start
2. Input a positive integer n
3. Call a recursive function sum(n)
o If n == 0 → return 0
o Else → return n + sum(n-1)
4. Display the sum returned by the function
5. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
// Function to calculate sum of natural numbers recursively
int sum(int n) {
if(n == 0)
return 0;
else
return n + sum(n-1);
}
int main()
{ int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
return 0;
}
OUTPUT:
Enter a positive integer: 5
Sum of first 5 natural numbers is 15
RESULT:
Thus, the C program to find the sum of natural numbers using
recursion was executed successfully.
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO WRITE A PROGRAM TO ENTER MARKS OF 5 DATE
3e SUBJECTS AND CALCULATE PERCENTAGE
USING FUNCTION PROTOTYPE
AIM:
To write a program to enter marks of 5 subjects and calculate percentage
using function prototype
ALGORITHM:
1. Start
2. Input marks of 5 subjects
3. Call a function calculatePercentage(totalMarks) to calculate percentage
4. Call a function determineGrade(percentage) to determine grade based on
percentage
90–100 → A
80–89 → B
70–79 → C
60–69 → D
<60 → F
5. Display percentage and grade
6. End
FLOWCHART:
PROGRAM:
#include <stdio.h>
// Function prototypes
float calculatePercentage(int totalMarks);
char determineGrade(float percentage);
int main() {
int marks[5], total = 0;
float percentage;
char grade;
printf("Enter marks of 5 subjects: ");
for(int i = 0; i < 5; i++) {
scanf("%d", &marks[i]);
total += marks[i];
}
percentage = calculatePercentage(total);
grade = determineGrade(percentage);
printf("Percentage: %.2f%%\n", percentage);
printf("Grade: %c\n", grade);
return 0;
}
// Function to calculate percentage
float calculatePercentage(int totalMarks)
{ return (totalMarks / 500.0) * 100;
}
// Function to determine grade
char determineGrade(float percentage)
{ if(percentage >= 90)
return 'A';
else if(percentage >= 80)
return 'B';
else if(percentage >= 70)
return 'C';
else if(percentage >= 60)
return 'D';
else
return 'F';
}
OUTPUT:
Enter marks of 5 subjects: 98 95 96 94 96
Percentage: 95.80%
Grade: A
RESULT:
Thus, the C program to calculate percentage and grade for 5 subjects
using function prototypes was executed successfully.
PROGRAMS USING POINTERS
EX.NO DATE
4A EMPLOYEE DETAILS
AIM:
To storing and displaying Employee Details using Pointers in C
Algorithm
1. Start
2. Declare a structure Employee with members: EmpID, Name, Age, Salary
3. Declare a pointer to the structure
4. Input employee details using the pointer
5. Display employee details using the pointer
6. End
PROGRAM:
#include <stdio.h>
struct Employee {
int EmpID;
char
Name[50]; int
Age;
float Salary;
};
int main() {
struct Employee e;
struct Employee *ptr;
return 0;
}
OUTPUT:
Enter Employee ID: 9523
Enter Employee Name: RAJAN
Enter Employee Age: 28
Enter Employee Salary: 15800
---Employee Details---
Employee ID: 9523
Employee Name: RAJAN
Employee Age: 28
Employee Salary: 15800.00
RESULT:
Thus, the C program to store and display employee details using pointers
was executed successfully.
PROGRAMS USING DYNAMIC MEMORY
EX.NO DATE
4B TOWER OF HANOI
AIM:
To solve the tower of Hanoi using dynamic memory (pointers)
ALGORITHM:
Algorithm (Tower of Hanoi)
1. Start
2. Input the number of disks n
3. Use dynamic memory allocation to store disk information (optional
for demonstration)
4. Call recursive function towerOfHanoi(n, source, auxiliary, destination)
o If n == 1 → move disk from source to destination
o Else →
1. Move n-1 disks from source to auxiliary
2. Move the nth disk from source to destination
3. Move n-1 disks from auxiliary to destination
5. Display the moves
6. Free dynamically allocated memory
7. End
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
// Function to solve Tower of Hanoi
void towerOfHanoi(int n, char source, char auxiliary, char destination)
{ if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}
towerOfHanoi(n - 1, source, destination, auxiliary);
printf("Move disk %d from %c to %c\n", n, source,
destination); towerOfHanoi(n - 1, auxiliary, source,
destination);
}
int main()
{ int *n;
n = (int *)malloc(sizeof(int)); // Dynamic memory allocation
if (n == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
OUTPUT:
Enter the number of disks: 3
The sequence of moves are:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
RESULT:
Thus, the C program to solve the Tower of Hanoi problem using dynamic
memory was executed successfully.
PROGRAMS USING POINTER ARITHMETIC
EX.NO DATE
4C POINTER ARITHMETIC
AIM
To understand and demonstrate pointer arithmetic in C by performing
operations such as increment, decrement, addition, subtraction, and finding the
difference between pointers.
ALGORITHM
1. Start
2. Declare an array of elements (e.g., integers)
3. Declare a pointer and initialize it to point to the first element of the array
4. Perform pointer arithmetic operations:
o Increment pointer (ptr++) → move to next element
o Decrement pointer (ptr--) → move to previous element
o Addition (ptr + n) → move n elements forward
o Subtraction (ptr - n) → move n elements backward
o Difference between two pointers (ptr1 - ptr2) → number of
elements between them
5. Access and display the value of elements using pointer after each
operation
6. End
PROGRAM:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer to first element
int *ptr2;
// Increment
ptr++;
printf("After ptr++ -> Address: %p, Value: %d\n", ptr, *ptr);
//
Decrement
ptr--;
printf("After ptr-- -> Address: %p, Value: %d\n", ptr, *ptr);
// Addition
ptr = ptr + 3;
printf("After ptr + 3 -> Address: %p, Value: %d\n", ptr, *ptr);
// Subtraction
ptr = ptr - 2;
printf("After ptr - 2 -> Address: %p, Value: %d\n", ptr, *ptr);
return 0;
}
OUTPUT:
Pointer Arithmetic Demonstration:
RESULT:
Thus, the C program to demonstrate pointer arithmetic was executed
successfully.
PROGRAMS USING STRING MANIPULATION
EX.NO DATE
4D STRING MANIPULATION
AIM
To understand and demonstrate string manipulation in C using built-in
functions and basic operations like copy, concatenate, compare, length, and
reverse.
ALGORITHM
1. Start
2. Declare string variables.
3. Input strings from the user using scanf() or gets().
4. Perform string operations:
o Copy one string to another using strcpy()
o Concatenate two strings using strcat()
o Compare two strings using strcmp()
o Find length of a string using strlen()
o Reverse a string manually or using a function
5. Display results of all operations.
6. End
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50], str2[50], str3[50];
int result, len, i;
char temp;
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string:
"); scanf("%s", str2);
// Copy
strcpy(str3, str1);
printf("Copied string: %s\n", str3);
// Concatenate
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
// Compare
result = strcmp(str1, str2);
if(result == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");
// Length
len = strlen(str2);
printf("Length of second string: %d\n", len);
// Reverse str2 manually
int n = strlen(str2);
for(i = 0; i < n/2; i++)
{ temp = str2[i];
str2[i] = str2[n-i-1];
str2[n-i-1] = temp;
}
printf("Reversed second string: %s\n", str2);
return 0;
}
OUTPUT:
Enter first string: RAJAN
Enter second string:
RAM Copied string:
RAJAN
Concatenated string: RAJANRAM
Strings are not equal.
Length of second string: 3
Reversed second string: MAR
RESULT:
Thus, the C program to demonstrate string manipulations was executed
successfully.
PROGRAMS USING ARRAY OPERATIONS
EX.NO DATE
4E ARRAY OPERATIONS
AIM
To understand and demonstrate basic array operations in C, including
traversing, inserting, deleting, searching, and sorting elements of an array.
ALGORITHM
1. Start
2. Declare an array of suitable size.
3. Input elements into the array using a loop.
4. Perform required array operations:
o Traversal: Access and display all elements.
o Insertion: Insert an element at a given position.
o Deletion: Delete an element from a given position.
o Searching: Find a given element using linear or binary search.
o Sorting: Sort the array in ascending or descending order.
5. Display the results after each operation.
6. End
PROGRAM:
#include <stdio.h>
int main() {
int arr[100], n, i, pos, value, search, found=0, j, temp;
// Input array
printf("Enter number of elements: ");
scanf("%d", &n);
// Traversal
printf("Array elements are: ");
for(i=0; i<n; i++)
printf("%d ", arr[i]);
printf("\n");
// Insertion
printf("Enter position to insert element (1 to %d): ", n+1);
scanf("%d", &pos);
printf("Enter value to insert: ");
scanf("%d", &value);
for(i=n; i>=pos; i--)
arr[i] = arr[i-1];
arr[pos-1] =
value; n++;
printf("Array after insertion:
"); for(i=0; i<n; i++)
printf("%d ",
arr[i]); printf("\n");
// Deletion
printf("Enter position to delete element (1 to %d): ", n);
scanf("%d", &pos);
for(i=pos-1; i<n-1; i++)
arr[i] = arr[i+1];
n--;
printf("Array after deletion: ");
for(i=0; i<n; i++)
printf("%d ", arr[i]);
printf("\n");
// Searching
printf("Enter element to search: ");
scanf("%d", &search);
for(i=0; i<n; i++)
{ if(arr[i] == search)
{
found = 1;
break;
}
}
if(found)
printf("Element %d found at position %d\n", search, i+1);
else
printf("Element not found\n");
// Sorting
(Ascending) for(i=0;
i<n-1; i++) {
for(j=i+1; j<n; j++)
{ if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] =
arr[j]; arr[j]
= temp;
}
}
}
printf("Array after sorting: ");
for(i=0; i<n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
OUTPUT:
Enter number of elements: 5
Enter 5 elements:
42
45
78
96
23
Array elements are: 42 45 78 96 23
Enter position to insert element (1 to 6): 4
Enter value to insert: 8
Array after insertion: 42 45 78 8 96 23
Enter position to delete element (1 to 6): 4
Array after deletion: 42 45 78 96
23 Enter element to search: 96
Element 96 found at position 4
Array after sorting: 23 42 45 78 96
RESULT:
Thus, the C program to perform array operations was executed
successfully.
PROGRAMS USING ARRAY OPERATIONS
EX.NO DATE
4F MATRIX OPERATION
AIM:
To understand and perform array operations including matrix addition,
subtraction, and multiplication using C programming.
ALGORITHM:
Matrix Addition/Subtraction
1. Start
2. Input number of rows r and columns c
3. Input elements of first matrix A[r][c]
4. Input elements of second matrix B[r][c]
5. For each element (i, j) in matrices:
o Addition: C[i][j] = A[i][j] + B[i][j]
o Subtraction: C[i][j] = A[i][j] - B[i][j]
6. Display the resultant matrix C
7. End
Matrix Multiplication
1. Start
2. Input number of rows and columns for both matrices (columns of first =
rows of second)
3. Input elements of first matrix A and second matrix B
4. Initialize resultant matrix C with zeros
5. For each element (i, j) in C:
o Compute C[i][j] = sum of A[i][k] * B[k][j] for all k
6. Display resultant matrix C
7. End
PROGRAM:
#include <stdio.h>
int main() {
int r, c, i, j, k;
printf("Enter number of rows and columns: ");
scanf("%d %d", &r, &c);
printf("Sum of matrices:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
printf("%d ", sum[i][j]);
printf("\n");
}
printf("Difference of matrices:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
printf("%d ", diff[i][j]);
printf("\n");
}
// Matrix Multiplication
// Assuming square matrices for simplicity
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
{ prod[i][j] = 0;
for(k = 0; k < c; k++)
prod[i][j] += A[i][k] * B[k][j];
}
printf("Product of matrices:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
printf("%d ", prod[i][j]);
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows and columns:
2 2
Enter elements of first matrix:
4564
Enter elements of second matrix:
8963
Sum of matrices:
12 14
12 7
Difference of matrices:
-4 -4
01
Product of matrices:
62 51
72 66
RESULT:
Thus, the C program to perform array operations including matrix
addition, subtraction, and multiplication was executed successfully.
PROGRAM TO USE STRUCTURES AND UNIONS
EX.NO DATE
5A STUDENT INFORMATION USING STRUCTURES
AIM
To understand and demonstrate the use of structures in C by storing and
displaying student information such as name, roll number, marks, and grade.
ALGORITHM
1. Start
2. Declare a struct named Student with fields: name, roll, marks, grade
3. Input the number of students n
4. For each student:
o Input name, roll, and marks
o Calculate grade based on marks:
90–100 → A
80–89 → B
70–79 → C
60–69 → D
<60 → F
5. Store the information in the structure array
6. Display the student records
7. End
PROGRAM:
#include <stdio.h>
// Structure definition
struct Student {
char name[50];
int roll;
float marks;
char grade;
};
int main()
{ int n;
printf("Enter number of students: ");
scanf("%d", &n);
students[i].grade = calculateGrade(students[i].marks);
}
return 0;
}
OUTPUT:
Enter number of students: 2
Student Records:
Name Roll Marks Grade
ARUN 1 96.00 A
RAJAN 2 99.00 A
RESULT:
Thus, the C program to store and display student information using
structures was executed successfully.
PROGRAM TO USE STRUCTURES AND UNIONS
EX.NO DATE
5B BOOK DETAILS USING NESTED STRUCTURES
AIM
To understand and demonstrate the use of nested structures in C by
storing and displaying details of books, including author information.
ALGORITHM
1. Start
2. Define a structure Author with fields: name, email
3. Define a structure Book with fields: title, price, Author author
(nested structure)
4. Input the number of books n
5. For each book:
o Input title, price
o Input author details: name, email
6. Store the information in a structure array
7. Display the book details along with author information
8. End
PROGRAM:
#include <stdio.h>
// Author structure
struct Author {
char name[50];
char email[50];
};
// Book structure with nested Author structure
struct Book {
char title[50];
float price;
struct Author author;
};
int main()
{ int n;
printf("Enter number of books: ");
scanf("%d", &n);
OUTPUT:
Enter number of books: 1
Enter details for book 1:
Book Title: JAVA
Price: 450
Author Name: RAJAN
Author Email: rajan@gmail.com
Book Details:
RESULT:
Thus, the C program to store and display book details using nested
structures was executed successfully.
PROGRAM TO USE STRUCTURES AND UNIONS
EX.NO DATE
5C EMPLOYEE DETAILS USING UNIONS
AIM
To understand and demonstrate the use of unions in C by storing and
displaying employee information such as ID, Name, and Salary efficiently.
ALGORITHM
1. Start
2. Define a union named Employee with fields:
o id (integer)
o name (string)
o salary (float)
3. Input the number of employees n
4. For each employee:
o Input one of the union members (since union stores one value at
a time)
5. Display the stored employee information
6. End
PROGRAM:
#include <stdio.h>
#include <string.h>
// Union definition
union Employee {
int id;
char name[50];
float salary;
};
int main() {
int n, choice;
printf("Enter number of employees: ");
scanf("%d", &n);
switch(choice)
{ case 1:
printf("Enter ID: ");
scanf("%d", &emp[i].id);
break;
case 2:
printf("Enter Name: ");
scanf(" %[^\n]s", emp[i].name); // Read string with spaces
break;
case 3:
printf("Enter Salary: ");
scanf("%f", &emp[i].salary);
break;
default:
printf("Invalid choice!\n");
}
}
return 0;
}
OUTPUT:
Enter number of employees: 3
RESULT:
Thus, the C program to store and display employee details using unions
was executed successfully.
PROGRAMS READING/WRITING DATA IN TEXT AND BINARY FILES
EX.NO DATE
6A FILE OPERATION IN C
(TEXT FILE)
AIM
To write a C program that demonstrates basic file operations (creation, writing,
and reading from a text file).
ALGORITHM
1. Start the program.
2. Declare a FILE pointer.
3. Open a text file in write mode (w) using fopen().
4. Write data into the file using fprintf() or fputs().
5. Close the file using fclose().
6. Reopen the same file in read mode (r).
7. Read the contents of the file using fscanf(), fgets(), or fgetc().
8. Display the contents on the screen.
9. Close the file.
10.Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char str[100];
// Step 1: Open file for
writing fp =
fopen("sample.txt", "w"); if
(fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
// Step 2: Write to file
fprintf(fp, "Hello, this is a file operation example in C.\
n"); fprintf(fp, "File handling is important for data
storage.\n"); fclose(fp);
// Step 3: Open file for
reading fp =
fopen("sample.txt", "r"); if (fp
== NULL) {
printf("Error opening file!\n");
exit(1);
}
// Step 4: Read and display contents
printf("Contents of the file:\n");
while (fgets(str, sizeof(str), fp) != NULL)
{ printf("%s", str);
}
fclose(fp);
return 0;
}
OUTPUT:
RESULT:
The C program was successfully executed to demonstrate basic file
operations such as creating a text file, writing data into it, and reading the stored
contents back.
PROGRAMS READING/WRITING DATA IN TEXT AND BINARY FILES
EX.NO DATE
6B FILE OPERATION IN C
(BINARY FILES)
AIM
To write a C program that demonstrates basic binary file operations such
as creating a binary file, writing data to it, and reading the stored data back.
ALGORITHM
1. Start the program.
2. Declare a structure to store sample data (e.g., student information).
3. Declare a FILE pointer.
4. Open a binary file in write mode (wb) using fopen().
5. Write data into the binary file using fwrite().
6. Close the file using fclose().
7. Reopen the same file in read mode (rb).
8. Read the data back using fread().
9. Display the retrieved data on the screen.
10.Close the file.
11.Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct Student
{ int rollNo;
char
name[30];
float marks;
};
int main()
{ FILE
*fp;
struct Student s1, s2;
return 0;
}
OUTPUT:
RESULT:
The C program was successfully executed to demonstrate basic binary
file operations such as creating a binary file, writing structured data into it, and
reading the stored data back.
USE OF STANDARD AND USER-DEFINED LIBRARIES IN SOLVING
PROBLEMS
EX.NO DATE
7A STANDARD LIBRARIES IN C
AIM
To understand and demonstrate the use of standard libraries in C to
simplify programming and solve problems efficiently.
ALGORITHM
1. Start
2. Identify the problem to be solved (e.g., mathematical computation, string
manipulation, I/O operations).
3. Determine which standard library functions are suitable for the task:
o <stdio.h> for input/output operations
o <math.h> for mathematical calculations
o <string.h> for string handling
o <ctype.h> for character processing
o <stdlib.h> for memory management, random numbers, or process
control
4. Include the required header files at the beginning of the program using
#include.
5. Write the program logic using library functions wherever possible
to simplify implementation.
6. Compile and run the program.
7. Observe the output and verify the correctness.
8. End
PROGRAM:
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int main() {
char name[50];
double num, result;
return 0;
}
OUTPUT:
Enter your name: RAJAN
Enter a number: 6
Hello RAJAN, square root of 6.00 is 2.45
RESULT:
Thus, the C program to demonstrate the use of standard libraries was
executed successfully.
USE OF STANDARD AND USER-DEFINED LIBRARIES IN SOLVING
PROBLEMS
EX.NO DATE
7B USER-DEFINED LIBRARIES
AIM
To understand and demonstrate the creation and use of user-defined
libraries in C to organize code and reuse functions efficiently.
OUTPUT:
Sum: 15
Product: 50
RESULT:
Thus, user-defined libraries in C allow programmers to modularize
code, reuse functions, and simplify program development.
EX.NO DATE
PROJECT
8A (Tic-Tac-Toe game)
AIM
To design a Tic-Tac-Toe game in C using 2D arrays and functions that
allows two players to play alternately in the console.
ALGORITHM
1. Start
2. Initialize a 3x3 board with empty spaces.
3. Display the board.
4. Loop until the game ends:
o Player 1 chooses a position and marks ‘X’.
o Display the updated board.
o Check if Player 1 has won.
o Player 2 chooses a position and marks ‘O’.
o Display the updated board.
o Check if Player 2 has won.
o If all positions are filled and no winner → Draw.
5. Display the winner or draw message.
6. End
PROGRAM:
#include <stdio.h>
char board[3][3];
return 0;
}
// Main function
int main() {
int row, col, moves = 0, player = 1;
initializeBoard();
displayBoard();
while(1) {
printf("Player %d, enter row and column (0-2): ", player);
scanf("%d %d", &row, &col);
if(moves == 9)
{ printf("Game Draw!\
n"); break;
}
return 0;
}
OUTPUT:
| |
---|---|---
| |
---|---|---
| |
X| |
---|---|---
| |
---|---|---
| |
X| |
---|---|---
|O|
---|---|---
| |
RESULT:
Thus, the C program to implement the Tic-Tac-Toe game in the console
was executed successfully.
EX.NO DATE
PROJECT
8B (Student Record Management System)
AIM
To develop a Mini Project in C for a Student Record Management
System using nested structures to store and manage student details such as
personal information, academic details, and marks.
ALGORITHM
ALGORITHM
1. Start the program.
2. Define a nested structure:
o Outer structure → Student.
o Inner structures → Address, Marks.
3. Create an array of students to store multiple records.
4. Display a menu with options:
o Add new student record.
o Display all student records.
o Search student by roll number.
o Exit.
5. Use switch-case to perform the selected operation.
6. For each student, input details and store them in the structure.
7. Display student details when requested.
8. Repeat until the user chooses to exit.
9. Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Nested Structures
struct Address {
char city[30];
char state[30];
int pincode;
};
struct Marks
{ float
maths; float
science;
float english;
};
struct Student {
int rollNo;
char
name[30];
struct Address addr;
struct Marks marks;
};
int main() {
struct Student s[50];
int n = 0, choice, i, roll, found;
while (1) {
printf("\n--- Student Record Management System ---\n");
printf("1. Add Student Record\n");
printf("2. Display All Records\n");
printf("3. Search by Roll Number\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{ case 1:
printf("\nEnter Roll No: ");
scanf("%d", &s[n].rollNo);
printf("Enter Name: ");
scanf(" %[^\n]",
s[n].name); printf("Enter
City: ");
scanf(" %[^\n]", s[n].addr.city);
printf("Enter State: ");
scanf(" %[^\n]", s[n].addr.state);
printf("Enter Pincode: ");
scanf("%d",
&s[n].addr.pincode);
printf("Enter Marks (Maths Science English): ");
scanf("%f %f %f", &s[n].marks.maths, &s[n].marks.science,
&s[n].marks.english);
n++;
printf("Record added successfully!\n");
break;
case 2:
if (n == 0) {
printf("\nNo records to display.\n");
} else {
printf("\n--- Student Records ---\n");
for (i = 0; i < n; i++) {
printf("\nRoll No: %d\n",
s[i].rollNo); printf("Name : %s\n",
s[i].name);
printf("Address: %s, %s - %d\n", s[i].addr.city, s[i].addr.state,
s[i].addr.pincode);
printf("Marks : Maths=%.2f, Science=%.2f, English=%.2f\n",
s[i].marks.maths, s[i].marks.science, s[i].marks.english);
}
}
break;
case 3:
printf("\nEnter Roll No to search: ");
scanf("%d", &roll);
found = 0;
for (i = 0; i < n; i++) {
if (s[i].rollNo == roll) {
printf("\n--- Student Found ---\n");
printf("Roll No: %d\n",
s[i].rollNo); printf("Name : %s\n",
s[i].name);
printf("Address: %s, %s - %d\n", s[i].addr.city, s[i].addr.state,
s[i].addr.pincode);
printf("Marks : Maths=%.2f, Science=%.2f, English=%.2f\n",
s[i].marks.maths, s[i].marks.science, s[i].marks.english);
found = 1;
break;
}
}
if (!found) {
printf("Student with Roll No %d not found!\n", roll);
}
break;
case 4:
printf("Exiting program...\n");
exit(0);
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}
OUTPUT:
--- Student Record Management System ---
1. Add Student Record
2. Display All Records
3. Search by Roll Number
4. Exit
Enter your choice: 1
RESULT:
The Mini Project was successfully developed in C to implement a
Student Record Management System using nested structures.