0% found this document useful (0 votes)
87 views64 pages

C Programs for Basic Calculations and Patterns

Uploaded by

RaghaviSelva
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)
87 views64 pages

C Programs for Basic Calculations and Patterns

Uploaded by

RaghaviSelva
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

Experiment 1A: Calculate Area and Circumference of Circle

Aim: To write a C program to calculate the area and circumference of a circle given its radius.
Algorithm:

1. Start.
2. Declare variables radius, area, circumference.
3. Define constant PI as 3.14159.
4. Read the value of radius from the user.
5. Calculate area = PI * radius * radius.
6. Calculate circumference = 2 * PI * radius.
7. Print the calculated area and circumference.
8. Stop.
Program:
#include <stdio.h>

#define PI 3.14159

int main() {

float radius, area, circumference;

printf("Enter the radius of the circle: ");

scanf("%f", &radius);

area = PI * radius * radius;

circumference = 2 * PI * radius;

printf("Area: %.2f\n", area);

printf("Circumference: %.2f\n", circumference);

return 0;

}
Output:

Result: The program to calculate the area and circumference of a circle was written and
executed successfully.
1
Experiment 1B: Simple Interest Calculation
Aim: To write a C program to calculate simple interest.
Algorithm:

1. Start.
2. Declare variables principal, rate, time, simple_interest.
3. Read principal, rate, and time from the user.
4. Calculate simple_interest = (principal * rate * time) / 100.
5. Print the calculated simple_interest.
6. Stop.
Program:
#include <stdio.h>

int main() {

float principal, rate, time, simple_interest;

printf("Enter principal amount: ");

scanf("%f", &principal);

printf("Enter rate of interest: ");

scanf("%f", &rate);

printf("Enter time (in years): ");

scanf("%f", &time);

simple_interest = (principal * rate * time) / 100;

printf("Simple Interest: %.2f\n", simple_interest);

return 0;

}
Output:

Result: The program to calculate simple interest was written and executed successfully.

2
Experiment 2A: Largest of Three Numbers
Aim: To write a C program to find the largest of three numbers.
Algorithm:

1. Start.
2. Declare variables a, b, c.
3. Read three numbers a, b, and c.
4. Check if a is greater than both b and c. If yes, a is largest.
5. Else, check if b is greater than c. If yes, b is largest.
6. Else, c is largest.
7. Print the largest number.
8. Stop.
Program:
#include <stdio.h>

int main() {

int a, b, c;

printf("Enter three numbers: ");

scanf("%d %d %d", &a, &b, &c);

if (a >= b && a >= c) {

printf("%d is the largest number.\n", a);

} else if (b >= a && b >= c) {

printf("%d is the largest number.\n", b);

} else {

printf("%d is the largest number.\n", c);

return 0;

}
Output:

Result: The program to find the largest of three numbers was written and executed successfully.
3
Experiment 2B: Leap Year or Not
Aim: To write a C program to check if a given year is a leap year.
Algorithm:

1. Start.
2. Declare variable year.
3. Read the year from the user.
4. If year is divisible by 400, it is a leap year.
5. Else, if it is divisible by 100, it is not a leap year.
6. Else, if it is divisible by 4, it is a leap year.
7. Else, it is not a leap year.
8. Print the result.
9. Stop.
Program:
#include <stdio.h>

int main() {

int year;

printf("Enter a year: ");

scanf("%d", &year);

if ((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) {

printf("%d is a leap year.\n", year);

} else {

printf("%d is not a leap year.\n", year);

return 0;

}
Output:

Result: The program to check for a leap year was written and executed successfully.

4
Experiment 2C: Armstrong Number or Not
Aim: To write a C program to check if a given number is an Armstrong number.
Algorithm:

1. Start.
2. Declare variables num, originalNum, remainder, result = 0, n = 0.
3. Read an integer num from the user.
4. Store num in originalNum.
5. Count the number of digits n.
6. For originalNum != 0:
7. remainder = originalNum % 10
8. Add remainder raised to the power n to result.
9. originalNum /= 10
10. If result == num, it is an Armstrong number.
11. Else, it is not.
12. Print the result.
13. Stop.
Program:
#include <stdio.h>

#include <math.h>

int main() {

int num, originalNum, remainder, n = 0;

float result = 0.0;

printf("Enter an integer: ");

scanf("%d", &num);

originalNum = num;

while (originalNum != 0) {

originalNum /= 10;

++n;

originalNum = num;

while (originalNum != 0) {
remainder = originalNum % 10;

result += pow(remainder, n);


5
originalNum /= 10;

if ((int)result == num)

printf("%d is an Armstrong number.\n", num);

else

printf("%d is not an Armstrong number.\n", num);

return 0;

}
Output:

Result: The program to check for an Armstrong number was written and executed successfully.

6
Experiment 3A: Generating Number Pattern
Aim: To write a C program to generate a number pattern.
Algorithm:

1. Start.
2. Declare variables i, j, rows.
3. Read number of rows from the user.
4. For i from 1 to rows:
5. For j from 1 to i:
6. Print j.
7. Print a newline.
8. Stop.
Program:
#include <stdio.h>

int main() {

int i, j, rows;

printf("Enter number of rows: ");

scanf("%d", &rows);

for (i = 1; i <= rows; i++) {

for (j = 1; j <= i; j++) {

printf("%d ", j);

printf("\n");

return 0;

7
Output:

Result: The program to generate a number pattern was written and executed successfully.

8
Experiment 3B: Generating Symbol Pattern
Aim: To write a C program to generate a symbol pattern (e.g., using '*').
Algorithm:

1. Start.
2. Declare variables i, j, rows.
3. Read number of rows from the user.
4. For i from 1 to rows:
5. For j from 1 to i:
6. Print *.
7. Print a newline.
8. Stop.
Program:
#include <stdio.h>

int main() {

int i, j, rows;

printf("Enter number of rows: ");

scanf("%d", &rows);

for (i = 1; i <= rows; i++) {

for (j = 1; j <= i; j++) {

printf("* ");

printf("\n");

return 0;

9
Output:

Result: The program to generate a star pattern was written and executed successfully.

10
Experiment 3C: Generating Letters Pattern
Aim: To write a C program to generate a pattern with letters.
Algorithm:

1. Start.
2. Declare variables i, j.
3. Declare a character input, current.
4. Read an uppercase letter input from the user.
5. For i from 'A' to input:
6. For j from 'A' to i:
7. Print j.
8. Print a newline.
9. Stop.
Program:
#include <stdio.h>

int main() {

char input, i, j;

printf("Enter an uppercase letter: ");

scanf(" %c", &input);

for (i = 'A'; i <= input; i++) {

for (j = 'A'; j <= i; j++) {

printf("%c ", j);

printf("\n");

return 0;

11
Output:

Result: The program to generate a letter pattern was written and executed successfully.

12
Experiment 4A: Finding the Sum of Array Elements
Aim: To write a C program to find the sum of elements in an array.
Algorithm:

1. Start.
2. Declare variables i, n, sum = 0.
3. Declare an array arr of size 100.
4. Read the size of the array n.
5. Read n elements into the array.
6. For each element in the array, add it to sum.
7. Print sum.
8. Stop.
Program:
#include <stdio.h>

int main() {

int i, n, arr[100], sum = 0;

printf("Enter the number of elements (1-100): ");

scanf("%d", &n);

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

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

sum += arr[i];

printf("Sum of array elements = %d\n", sum);

return 0;

}
Output:

Result: The program to find the sum of array elements was written and executed successfully.
13
Experiment 4B: Insert an Element in an Array
Aim: To write a C program to insert an element at a specific position in an array.
Algorithm:

1. Start.
2. Declare variables i, n, pos, value.
3. Declare an array arr of size 100.
4. Read the size of the array n.
5. Read n elements into the array.
6. Read the position where you want to insert and the value to insert.
7. Shift all elements from the position to the end one place to the right.
8. Insert the value at the position.
9. Increment n by 1.
10. Print the new array.
11. Stop.
Program:
#include <stdio.h>

int main() {

int arr[100], i, n, pos, value;

printf("Enter number of elements in array: ");

scanf("%d", &n);

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

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

printf("Enter the location to insert: ");

scanf("%d", &pos);

printf("Enter the value to insert: ");

scanf("%d", &value);

for (i = n - 1; i >= pos - 1; i--) {

arr[i+1] = arr[i];

arr[pos-1] = value;
14
n++;

printf("Array after insertion:\n");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

}
Output:

Result: The program to insert an element into an array was written and executed successfully.

15
Experiment 4B: Insert an Element in an Array
Aim: To write a C program to insert an element at a specific position in an array.
Algorithm:

1. Start.
2. Declare variables i, n, pos, value.
3. Declare an array arr of size 100.
4. Read the size of the array n.
5. Read n elements into the array.
6. Read the position where you want to insert and the value to insert.
7. Shift all elements from the position to the end one place to the right.
8. Insert the value at the position.
9. Increment n by 1.
10. Print the new array.
11. Stop.
Program:
#include <stdio.h>

int main() {

int arr[100], i, n, pos, value;

printf("Enter number of elements in array: ");

scanf("%d", &n);

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

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

printf("Enter the location to insert: ");

scanf("%d", &pos);

printf("Enter the value to insert: ");

scanf("%d", &value);

for (i = n - 1; i >= pos - 1; i--) {

arr[i+1] = arr[i];

arr[pos-1] = value;
16
n++;

printf("Array after insertion:\n");

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

}
Output:

Result: The program to insert an element into an array was written and executed successfully.

17
Experiment 5A: Add Two Matrices
Aim: To write a C program to add two matrices.
Algorithm:

1. Start.
2. Declare variables i, j, rows, cols.
3. Declare three 2D arrays mat1, mat2, sum of the same size.
4. Read the number of rows and columns for the matrices.
5. Read elements for mat1 and mat2.
6. For each element [i][j], compute sum[i][j] = mat1[i][j] + mat2[i][j].
7. Print the sum matrix.
8. Stop.
Program:
#include <stdio.h>

int main() {

int i, j, rows, cols;

int mat1[10][10], mat2[10][10], sum[10][10];

printf("Enter number of rows (max 10): ");

scanf("%d", &rows);

printf("Enter number of columns (max 10): ");

scanf("%d", &cols);

printf("Enter elements of first matrix:\n");

for(i=0; i<rows; i++)

for(j=0; j<cols; j++)

scanf("%d", &mat1[i][j]);

printf("Enter elements of second matrix:\n");

for(i=0; i<rows; i++)

for(j=0; j<cols; j++)

scanf("%d", &mat2[i][j]);

for(i=0; i<rows; i++)

for(j=0; j<cols; j++)


sum[i][j] = mat1[i][j] + mat2[i][j];

18
printf("Sum of the matrices:\n");

for(i=0; i<rows; i++) {

for(j=0; j<cols; j++)

printf("%d\t", sum[i][j]);

printf("\n");

return 0;

}
Output:

Result: The program to add two matrices was written and executed successfully.

19
Experiment 5B: Multiply Two Matrices
Aim: To write a C program to multiply two matrices.
Algorithm:

1.
Start.
2.
Declare variables i, j, k, r1, c1, r2, c2.
3.
Declare 2D arrays a, b, product.
4.
Read dimensions of first matrix (r1, c1). Ensure c1 equals r2.
5.
Read elements for matrices a and b.
6.
Initialize product matrix to zero.
7.
For each i from 0 to r1-1, and each j from 0 to c2-1:
o For k from 0 to c1-1:
 product[i][j] += a[i][k] * b[k][j]
8. Print the product matrix.
9. Stop.
Program:
#include <stdio.h>

int main() {

int a[10][10], b[10][10], product[10][10];

int r1, c1, r2, c2, i, j, k;

printf("Enter rows and columns for first matrix: ");

scanf("%d %d", &r1, &c1);

printf("Enter rows and columns for second matrix: ");

scanf("%d %d", &r2, &c2);

if (c1 != r2) {

printf("Error! Column of first matrix not equal to row of second.\n");

return 0;

printf("Enter elements of matrix 1:\n");

for(i=0; i<r1; i++)

for(j=0; j<c1; j++)

scanf("%d", &a[i][j]);

printf("Enter elements of matrix 2:\n");

20
for(i=0; i<r2; i++)

for(j=0; j<c2; j++)

scanf("%d", &b[i][j]);

for(i=0; i<r1; i++)

for(j=0; j<c2; j++)

product[i][j] = 0;

for(i=0; i<r1; i++)

for(j=0; j<c2; j++)

for(k=0; k<c1; k++)

product[i][j] += a[i][k] * b[k][j];

printf("Product of the matrices:\n");

for(i=0; i<r1; i++) {

for(j=0; j<c2; j++)

printf("%d\t", product[i][j]);

printf("\n");

return 0;

}
Output:

Result: The program to multiply two matrices was written and executed successfully.
21
Experiment 6A(i): Length of a String without String Function
Aim: To write a C program to find the length of a string without using the built-
in strlen() function.
Algorithm:

1. Start.
2. Declare a character array str[] and initialize a counter length = 0.
3. Read a string into str.
4. Use a loop to traverse the string until the null terminator '\0' is found.
5. Increment length for each character encountered.
6. Print length.
7. Stop.
Program:
#include <stdio.h>

int main() {

char str[100];

int length = 0;

printf("Enter a string: ");

scanf("%s", str);

while (str[length] != '\0') {

length++;

printf("Length of the string: %d\n", length);

return 0;

}
Output:

Result: The program to find the string length without built-in functions was executed
successfully.

22
Experiment 6A(ii): Length of a String with String Function
Aim: To write a C program to find the length of a string using the strlen() function.
Algorithm:

1. Start.
2. Declare a character array str[] and an integer length.
3. Read a string into str.
4. Use length = strlen(str) to get the length.
5. Print length.
6. Stop.
Program:
#include <stdio.h>

#include <string.h> // For strlen()

int main() {

char str[100];

int length;

printf("Enter a string: ");

scanf("%s", str);

length = strlen(str);

printf("Length of the string: %d\n", length);

return 0;

}
Output:

Result: The program to find the string length using strlen() was executed successfully.

23
Experiment 6B(i): Copy a String without String Function
Aim: To write a C program to copy one string to another without using the strcpy() function.
Algorithm:

1.
Start.
2.
Declare two character arrays source[] and destination[].
3.
Read a string into source.
4.
Use a loop to copy each character from source to destination until the null
terminator '\0' is found.
5. Manually add the null terminator to the end of destination.
6. Print both strings.
7. Stop.
Program:
#include <stdio.h>

int main() {

char source[100], destination[100];

int i = 0;

printf("Enter a string to copy: ");

scanf("%s", source);

while (source[i] != '\0') {

destination[i] = source[i];

i++;

destination[i] = '\0'; // Add null terminator

printf("Original string: %s\n", source);

printf("Copied string: %s\n", destination);

return 0;

24
Output:

Result: The program to copy a string without built-in functions was executed successfully.

25
Experiment 6B(ii): Copy a String with String Function
Aim: To write a C program to copy one string to another using the strcpy() function.
Algorithm:

1. Start.
2. Declare two character arrays source[] and destination[].
3. Read a string into source.
4. Use strcpy(destination, source) to copy the string.
5. Print both strings.
6. Stop.
Program:
#include <stdio.h>

#include <string.h> // For strcpy()

int main() {

char source[100], destination[100];

printf("Enter a string to copy: ");

scanf("%s", source);

strcpy(destination, source);

printf("Original string: %s\n", source);

printf("Copied string: %s\n", destination);

return 0;

}
Output:

Result: The program to copy a string using strcpy() was executed successfully.

26
Experiment 6C(i): Compare Two Strings without String Function
Aim: To write a C program to compare two strings without using the strcmp() function.
Algorithm:

1. Start.
2. Declare two character arrays str1[], str2[], and an integer i = 0.
3. Read both strings.
4. Use a loop to compare each corresponding character.
5. If any character differs, or if one string ends before the other, set a flag and break.
6. After the loop, check the flag and the null terminators to determine the result.
7. Print whether the strings are equal or not.
8. Stop.
Program:
#include <stdio.h>

int main() {

char str1[100], str2[100];

int i = 0, areEqual = 1; // Assume they are equal initially

printf("Enter first string: ");

scanf("%s", str1);

printf("Enter second string: ");

scanf("%s", str2);

while (str1[i] != '\0' || str2[i] != '\0') {

if (str1[i] != str2[i]) {

areEqual = 0;

break;

i++;

if (areEqual == 1 && str1[i] == '\0' && str2[i] == '\0')

printf("Strings are equal.\n");

else
printf("Strings are not equal.\n");

27
return 0;

}
Output:

Result: The program to compare strings without built-in functions was executed successfully.

28
Experiment 6C(ii): Compare Two Strings with String Function
Aim: To write a C program to compare two strings using the strcmp() function.
Algorithm:

1. Start.
2. Declare two character arrays str1[], str2[].
3. Read both strings.
4. Use result = strcmp(str1, str2).
5. If result == 0, the strings are equal.
6. Print the result accordingly.
7. Stop.
Program:
#include <stdio.h>

#include <string.h> // For strcmp()

int main() {

char str1[100], str2[100];

int result;

printf("Enter first string: ");

scanf("%s", str1);

printf("Enter second string: ");

scanf("%s", str2);

result = strcmp(str1, str2);

if (result == 0)

printf("Strings are equal.\n");

else

printf("Strings are not equal.\n");

return 0;

29
Output:

Result: The program to compare strings using strcmp() was executed successfully.

30
Experiment 7A: Swap Two Numbers using Call by Value
Aim: To write a C program to swap two numbers using call by value.
Algorithm:

1.
Start.
2.
Declare variables a and b in main().
3.
Read values for a and b.
4.
Call a function swapByValue(a, b), passing the values.
5.
Inside the function, swap the values of the parameters. This swap will not
affect a and b in main().
6. Print the values inside the function (swapped) and then in main() (original).
7. Stop.
Program:
#include <stdio.h>

void swapByValue(int x, int y) {

int temp;

temp = x;

x = y;

y = temp;

printf("Inside swap function (Call by Value): a = %d, b = %d\n", x, y);

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

printf("Before swap: a = %d, b = %d\n", a, b);

swapByValue(a, b);

printf("After swap (in main): a = %d, b = %d\n", a, b); // Values unchanged

return 0;

31
Output:

Result: The program demonstrated that call by value does not change the original arguments.

32
Experiment 7B: Swap Two Numbers using Call by Reference
Aim: To write a C program to swap two numbers using call by reference.
Algorithm:

1. Start.
2. Declare variables a and b in main().
3. Read values for a and b.
4. Call a function swapByReference(&a, &b), passing the addresses.
5. Inside the function, swap the values stored at the addresses.
6. This swap will directly change the values of a and b in main().
7. Print the values in main() to see the change.
8. Stop.
Program:
#include <stdio.h>

void swapByReference(int *x, int *y) {

int temp;

temp = *x;

*x = *y;

*y = temp;

printf("Inside swap function (Call by Reference): a = %d, b = %d\n", *x, *y);

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

printf("Before swap: a = %d, b = %d\n", a, b);

swapByReference(&a, &b);

printf("After swap (in main): a = %d, b = %d\n", a, b); // Values changed

return 0;

33
Output:

Result: The program demonstrated that call by reference changes the original arguments.

34
Experiment 7C: Sort an Array of Elements using Functions
Aim: To write a C program to sort an array of integers using a function.
Algorithm:

1.
Start.
2.
Declare an array arr[] and an integer n in main().
3.
Read n and the elements of the array.
4.
Call a function sortArray(arr, n), passing the array (which is passed by reference).
5.
Inside the function, implement the Bubble Sort algorithm:
o Use two nested loops.
o The outer loop runs from i = 0 to n-1.
o The inner loop runs from j = 0 to n-i-1.
o Compare adjacent elements arr[j] and arr[j+1].
o If arr[j] > arr[j+1], swap them.
6. The original array in main() will be sorted.
7. Print the sorted array from main().
8. Stop.
Program:
#include <stdio.h>

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

int i, j, temp;

for (i = 0; i < n-1; i++) {

for (j = 0; j < n-i-1; j++) {

if (arr[j] > arr[j+1]) {

// Swap elements

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

int main() {

int arr[100], n, i;
35
printf("Enter number of elements: ");

scanf("%d", &n);

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

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

sortArray(arr, n);

printf("Sorted array in ascending order:\n");

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

return 0;

}
Output:

Result: The program to sort an array using a function was executed successfully.

36
Experiment 8A: Factorial of a Number using Recursive Functions
Aim: To write a C program to find the factorial of a number using recursion.
Algorithm:

1. Start.
2. Declare a recursive function long int factorial(int n).
o Base case: if n == 0 or n == 1, return 1.
o Recursive case: return n * factorial(n-1).
3. In main(), read an integer num.
4. Call factorial(num) and print the result.
5. Stop.
Program:
#include <stdio.h>

long int factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a positive integer: ");

scanf("%d", &num);

printf("Factorial of %d = %ld\n", num, factorial(num));

return 0;

}
Output:

Result: The recursive program to calculate factorial was executed successfully.

37
Experiment 8B: Fibonacci Series using Recursive Functions
Aim: To write a C program to print the Fibonacci series up to n terms using recursion.
Algorithm:

1. Start.
2. Declare a recursive function int fibonacci(int n).
o Base case 1: if n == 0, return 0.
o Base case 2: if n == 1, return 1.
o Recursive case: return fibonacci(n-1) + fibonacci(n-2).
3. In main(), read the number of terms terms.
4. Use a loop to call fibonacci(i) for i from 0 to terms-1 and print the result.
5. Stop.
Program:
#include <stdio.h>

int fibonacci(int n) {

if (n == 0)

return 0;

else if (n == 1)

return 1;

else

return (fibonacci(n-1) + fibonacci(n-2));

int main() {

int terms, i;

printf("Enter the number of terms: ");

scanf("%d", &terms);

printf("Fibonacci Series: ");

for (i = 0; i < terms; i++) {

printf("%d ", fibonacci(i));

}
printf("\n");

38
return 0;

}
Output:

Result: The recursive program to generate the Fibonacci series was executed successfully.

39
Experiment 8C: Tower of Hanoi using Recursive Functions
Aim: To write a C program to solve the Tower of Hanoi problem using recursion.
Algorithm:

1. Start.
2. Declare a recursive function void towerOfHanoi(int n, char from_rod, char to_rod, char
aux_rod).
o Base case: if n == 1, print "Move disk 1 from rod from_rod to rod to_rod".
o Recursive case:
 Move n-1 disks from from_rod to aux_rod using to_rod.
 Move the nth disk from from_rod to to_rod.
 Move the n-1 disks from aux_rod to to_rod using from_rod.
3. In main(), read the number of disks n.
4. Call towerOfHanoi(n, 'A', 'C', 'B'). (A is source, C is destination, B is auxiliary)
5. Stop.
Program:
#include <stdio.h>

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {

if (n == 1) {

printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);

return;

towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);

towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

int main() {

int n;

printf("Enter number of disks: ");

scanf("%d", &n);

printf("The sequence of moves involved in the Tower of Hanoi are:\n");

towerOfHanoi(n, 'A', 'C', 'B');

return 0;

40
}
Output:

Result: The recursive program to solve the Tower of Hanoi problem was executed successfully.

41
Experiment 9A: Print Text using Dynamic Memory
Aim: To write a C program to read and print a string using dynamic memory allocation.
Algorithm:

1. Start.
2. Declare a character pointer str.
3. Allocate memory dynamically for the string using malloc() or calloc().
4. Read a string from the user into the allocated memory.
5. Print the string.
6. Free the allocated memory using free().
7. Stop.
Program:
#include <stdio.h>

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

int main() {

char *str;

int n;

printf("Enter maximum length of string: ");

scanf("%d", &n);

getchar(); // To consume the newline left by scanf

str = (char *)malloc((n+1) * sizeof(char)); // +1 for null terminator

if (str == NULL) {

printf("Memory allocation failed!\n");

return 1;

printf("Enter a string: ");

fgets(str, n+1, stdin); // Read string with spaces, safely

printf("You entered: %s\n", str);

free(str); // Free the allocated memory

return 0;

42
Output:

Result: The program to handle strings using dynamic memory allocation was executed
successfully.

43
Experiment 9B: One Dimensional Array Dynamic Memory
Aim: To write a C program to manage a one-dimensional array using dynamic memory
allocation.
Algorithm:

1. Start.
2. Declare an integer pointer arr and variables n, i.
3. Read the size of the array n.
4. Allocate memory for n integers using malloc().
5. Read n integers into the dynamically allocated array.
6. Print the array elements.
7. Free the allocated memory using free().
8. Stop.
Program:
#include <stdio.h>

#include <stdlib.h>

int main() {

int *arr;

int n, i;

printf("Enter number of elements: ");

scanf("%d", &n);

arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1;

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

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

printf("The elements are: ");

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");
44
free(arr);

return 0;

}
Output:

Result: The program to manage a 1D array using dynamic memory was executed successfully.

45
Experiment 10A: Creating Employee Payslip Using Structure
Aim: To write a C program to create an employee payslip using structures.
Algorithm:

1. Start.
2. Define a structure Employee with members
like id, name, basic_salary, hra, da, pf, net_salary.
3. Declare a variable emp of type struct Employee.
4. Read employee details.
5. Calculate deductions and net salary: e.g., net_salary = basic_salary + hra + da - pf.
6. Print the payslip with all details.
7. Stop.
Program:
#include <stdio.h>

struct Employee {

int id;

char name[50];

float basic_salary;

float hra;

float da;

float pf;

float net_salary;

};

int main() {

struct Employee emp;

printf("Enter Employee ID: ");

scanf("%d", &[Link]);

getchar(); // To consume newline

printf("Enter Employee Name: ");

fgets([Link], 50, stdin);

printf("Enter Basic Salary: ");


scanf("%f", &emp.basic_salary);

46
// Calculate components (example calculations)

[Link] = 0.1 * emp.basic_salary;

[Link] = 0.05 * emp.basic_salary;

[Link] = 0.12 * emp.basic_salary;

emp.net_salary = emp.basic_salary + [Link] + [Link] - [Link];

printf("\n--- Employee Payslip ---\n");

printf("ID: %d\n", [Link]);

printf("Name: %s", [Link]);

printf("Basic Salary: %.2f\n", emp.basic_salary);

printf("HRA: %.2f\n", [Link]);

printf("DA: %.2f\n", [Link]);

printf("PF: %.2f\n", [Link]);

printf("Net Salary: %.2f\n", emp.net_salary);

return 0;

}
Output:

Result: The program to create an employee payslip using structures was executed successfully.

47
Experiment 10B: Creating Student Details using Structure and Union
Aim: To write a C program to manage student details using a structure and demonstrate the use
of a union within it.
Algorithm:

1. Start.
2. Create a union to store either a grade (char) or a percentage (float).
3. Define a structure Student containing rollno, name, a tag field, and the union.
4. Read student details. Ask the user if they want to enter a grade or percentage.
5. Based on the choice, store the data in the union and set the tag accordingly.
6. Print the student details, using the tag to correctly interpret the union.
7. Stop.
Program:
#include <stdio.h>

#include <string.h>

// Union to hold either grade or percentage

union Result {

char grade;

float percentage;

};

// Structure with a tag to interpret the union

struct Student {

int rollno;

char name[50];

int result_type; // 1 for grade, 2 for percentage

union Result result;

};

int main() {

struct Student stu;

char choice;

printf("Enter Student Roll No: ");


scanf("%d", &[Link]);

48
getchar();

printf("Enter Student Name: ");

fgets([Link], 50, stdin);

[Link][strcspn([Link], "\n")] = 0; // Remove trailing newline

printf("Enter result type (G for Grade, P for Percentage): ");

scanf(" %c", &choice);

if (choice == 'G' || choice == 'g') {

stu.result_type = 1;

printf("Enter Grade (A/B/C/D/F): ");

scanf(" %c", &[Link]);

} else if (choice == 'P' || choice == 'p') {

stu.result_type = 2;

printf("Enter Percentage: ");

scanf("%f", &[Link]);

} else {

printf("Invalid choice!\n");

return 1; }

printf("\n--- Student Details ---\n");

printf("Roll No: %d\n", [Link]);

printf("Name: %s\n", [Link]);

if (stu.result_type == 1)

printf("Grade: %c\n", [Link]);

else if (stu.result_type == 2)

printf("Percentage: %.2f%%\n", [Link]);

return 0;

49
Output:

Result: The program to manage student details using a structure and a union was executed
successfully.

50
Experiment 11A: Calculating Sum and Average of n Numbers Present in a File
Aim: To write a C program to read numbers from a file and calculate their sum and average.
Algorithm:

1. Start.
2. Declare variables num, count = 0, sum = 0.
3. Open a file (e.g., [Link]) in read mode.
4. Use a loop to read numbers from the file until EOF is reached.
5. For each number read, add it to sum and increment count.
6. Calculate average = sum / count.
7. Print sum and average.
8. Close the file.
9. Stop.
Program:
#include <stdio.h>

int main() {

FILE *filePtr;

int num, count = 0;

float sum = 0, average;

filePtr = fopen("[Link]", "r");

if (filePtr == NULL) {

printf("Could not open file [Link]\n");

return 1; }

while (fscanf(filePtr, "%d", &num) != EOF) {

sum += num;

count++;

fclose(filePtr);

if (count > 0) {

average = sum / count;

printf("Sum = %.2f\n", sum);

printf("Average = %.2f\n", average);

} else {
51
printf("No numbers found in the file.\n");

return 0;

}
Output:

Result: The program to calculate the sum and average of numbers from a file was executed
successfully.

52
Experiment 11B: Transaction Processing using Random Access File
Aim: To write a C program to demonstrate simple transaction processing (deposit/withdrawal)
using a random access file.
Algorithm:

1. Start.
2. Define a structure Account with accountNumber, name, balance.
3. Use fseek(), fwrite(), and fread() to update a specific account record.
4. Open a file in "r+b" mode for reading and writing.
5. Read the account number to process.
6. Move the file pointer to the start of that record using fseek().
7. Read the current record.
8. Update the balance based on the transaction type.
9. Move the pointer back and write the updated record.
10. Close the file.
11. Stop.
Program:
#include <stdio.h>

struct Account {

int accountNumber;

char name[50];

float balance;

};

int main() {

FILE *filePtr;

struct Account acc;

int accNumber;

char transaction;

float amount;

filePtr = fopen("[Link]", "r+b");

if (filePtr == NULL) {

printf("Error opening file!\n");


return 1;

}
53
printf("Enter account number: ");

scanf("%d", &accNumber);

printf("Enter transaction type (D for Deposit, W for Withdrawal): ");

scanf(" %c", &transaction);

printf("Enter amount: ");

scanf("%f", &amount);

// Search for the account

while (fread(&acc, sizeof(struct Account), 1, filePtr) == 1) {

if ([Link] == accNumber) {

// Found the account

if (transaction == 'D' || transaction == 'd') {

[Link] += amount;

printf("Deposit successful.\n");

} else if (transaction == 'W' || transaction == 'w') {

if ([Link] >= amount) {

[Link] -= amount;

printf("Withdrawal successful.\n");

} else {

printf("Insufficient balance.\n");

fclose(filePtr);

return 1;

} else {

printf("Invalid transaction type.\n");

fclose(filePtr);

return 1;

}
// Move back and write the updated record

54
fseek(filePtr, -sizeof(struct Account), SEEK_CUR);

fwrite(&acc, sizeof(struct Account), 1, filePtr);

printf("New Balance for %s: %.2f\n", [Link], [Link]);

fclose(filePtr);

return 0;

printf("Account not found.\n");

fclose(filePtr);

return 1;

}
Create a sample file:
#include <stdio.h>

// ... (use the same struct Account as above)

int main() {

FILE *fp = fopen("[Link]", "wb");

struct Account a1 = {1001, "Alice", 5000.0};

struct Account a2 = {1002, "Bob", 3000.0};

fwrite(&a1, sizeof(struct Account), 1, fp);

fwrite(&a2, sizeof(struct Account), 1, fp);

fclose(fp);

return 0;

55
Output:

Result: The program to process transactions using random access files was executed
successfully.

56
Experiment 12A: Comparing Two Strings using Command Line Argument
Aim: To write a C program that accepts two strings as command line arguments and compares
them.
Algorithm:

1. Start.
2. Define the main function with parameters argc and argv[].
3. Check if argc is 3 (program name + 2 strings).
4. If not, print a usage message.
5. Use strcmp() to compare argv[1] and argv[2].
6. Print the result of the comparison.
7. Stop.
Program:
#include <stdio.h>

#include <string.h>

int main(int argc, char *argv[]) {

if (argc != 3) {

printf("Usage: %s <string1> <string2>\n", argv[0]);

return 1;

int result = strcmp(argv[1], argv[2]);

if (result == 0)

printf("The strings are equal.\n");

else if (result < 0)

printf("'%s' is less than '%s'.\n", argv[1], argv[2]);

else

printf("'%s' is greater than '%s'.\n", argv[1], argv[2]);

return 0;

57
Output:

Result: The program to compare strings using command line arguments was executed
successfully.

58
Experiment 12B: Copying Content of One File to Another using Command Line Argument
Aim: To write a C program that accepts source and destination filenames as command line
arguments and copies the content.
Algorithm:

1. Start.
2. Define the main function with parameters argc and argv[].
3. Check if argc is 3 (program name + source + destination).
4. Open the source file in read mode.
5. Open the destination file in write mode.
6. Read characters from the source file and write them to the destination file until EOF.
7. Close both files.
8. Print a success message.
9. Stop.
Program:
#include <stdio.h>

int main(int argc, char *argv[]) {

FILE *sourceFile, *destFile;

char ch;

if (argc != 3) {

printf("Usage: %s <sourcefile> <destinationfile>\n", argv[0]);

return 1;

sourceFile = fopen(argv[1], "r");

if (sourceFile == NULL) {

printf("Could not open source file %s\n", argv[1]);

return 1;

destFile = fopen(argv[2], "w");

if (destFile == NULL) {

printf("Could not open destination file %s\n", argv[2]);

fclose(sourceFile);

return 1;
59
}

while ((ch = fgetc(sourceFile)) != EOF) {

fputc(ch, destFile);

printf("File copied successfully from %s to %s.\n", argv[1], argv[2]);

fclose(sourceFile);

fclose(destFile);

return 0;

}
Create a sample file first:

Output:

Result: The program to copy a file using command line arguments was executed successfully.

60
Experiment 13: Creating Student Records using File Handling and Structures
Aim: To write a C program to maintain student records using structures and file handling.
Algorithm:

1.
Start.
2.
Define a structure Student with rollno, name, marks.
3.
Present a menu: Add record, View all records, Exit.
4.
For 'Add record':
o Open the file in "ab" (append binary) mode.
o Read student details from the user.
o Write the structure to the file.
o Close the file.
5. For 'View all records':
o Open the file in "rb" (read binary) mode.
o Read structures from the file until EOF.
o Print each student's details.
o Close the file.
6. Stop.
Program:
#include <stdio.h>

struct Student {

int rollno;

char name[50];

float marks;

};

void addStudent() {

FILE *filePtr;

struct Student stu;

filePtr = fopen("[Link]", "ab");

if (filePtr == NULL) {

printf("Error opening file for writing!\n");

return;

printf("Enter Roll No: ");

61
scanf("%d", &[Link]);

getchar();

printf("Enter Name: ");

fgets([Link], 50, stdin);

printf("Enter Marks: ");

scanf("%f", &[Link]);

fwrite(&stu, sizeof(struct Student), 1, filePtr);

fclose(filePtr);

printf("Record added successfully.\n");

void viewAllStudents() {

FILE *filePtr;

struct Student stu;

filePtr = fopen("[Link]", "rb");

if (filePtr == NULL) {

printf("No records found or error opening file.\n");

return;

printf("\n--- All Student Records ---\n");

printf("Roll No\tName\tMarks\n");

while (fread(&stu, sizeof(struct Student), 1, filePtr) == 1) {

printf("%d\t%s\t%.2f\n", [Link], [Link], [Link]);

fclose(filePtr);

int main() {

int choice;
do {

62
printf("\nStudent Record Menu\n");

printf("1. Add Student\n");

printf("2. View All Students\n");

printf("3. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1: addStudent(); break;

case 2: viewAllStudents(); break;

case 3: printf("Exiting...\n"); break;

default: printf("Invalid choice!\n");

} while (choice != 3);

return 0;

}
Output:

63
Result: The program to maintain student records using structures and file handling was
executed successfully.

64

You might also like