0% found this document useful (0 votes)
9 views73 pages

C Programming Lab Experiments List

C programming
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)
9 views73 pages

C Programming Lab Experiments List

C programming
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

LIST OF EXPERIMENTS

[Link] PROGRAM
1 Writing simple programs using printf(), scanf()
2 Sum and average of 3 numbers
3 Conversion of Fahrenheit to Celsius and vice versa.
4 Simple interest calculation
5 Finding the square root of a given number
6 Finding compound interest
7 Area of a triangle using heron’s formulae
8 Distance travelled by an object
9 Evaluate the following expressions.
a. b. A+B*C+(D*E) + F*G
c. d. A/B*C-B+A*D/3
e. f. A+++B---A
g. h. J= (i++) + (++i)
10 Find the maximum of three numbers using conditional operator
11 Take marks of 5 subjects in integers, and find the total, average
in float
12 Write a C program to find the max and min of four numbers
using if-else.
13 Write a C program to generate electricity bill.
14 Find the roots of the quadratic equation.
15 Write a C program to simulate a calculator using switch case.
16 Write a C program to find the given year is a leap year or not.
17 Find the factorial of given number using any loop.
18 Find the given number is a prime or not.
19 Compute sine and cos series
20 Checking a number palindrome
21 Construct a pyramid of numbers
22 Find the min and max of a 1-D integer array
23 Perform linear search on1D array.
24 The reverse of a 1D integer array.
25 Find 2’s complement of the given binary number.
26 Eliminate duplicate elements in an array
27 Addition of two matrices
28 Multiplication two matrices
29 Sort array elements using bubble sort
30 Concatenate two strings without built-in functions
31 Reverse a string using built-in and without built-in string
functions
32 Write a C program to find the sum of a 1D array using malloc()
33 Write a C program to find the total, average of n students using
structures
34 Enter n students data using calloc() and display failed students
list
35 Read student name and marks from the command line and
display the student details along with the total
36 Write a C program to implement realloc()
37 Create and display a singly linked list using self-referential
structure.
38 Demonstrate the differences between structures and unions
using a C program
39 Write a C program to shift/rotate using bitfields
40 Write a C program to copy one structure variable to another
structure of the same type
41 Write a C function to calculate NCR value
42 Write a C function to find the length of a string.
43 Write a C function to transpose of a matrix.
44 Write a C function to demonstrate numerical integration of
differential equations using Euler’s method
45 Write a recursive function to generate Fibonacci series.
46 Write a recursive function to find the lcm of two numbers.
47 Write a recursive function to find the factorial of a number.
48 Write a C Program to implement Ackermann function using
recursion.
49 Write a recursive function to find the sum of series.
50 Write a C program to swap two numbers using call by reference
51 Demonstrate Dangling pointer problem using a C program
52 Write a C program to copy one string into another using pointer.
53 Write a C program to write and read text into a file.
54 Copy the contents of one file to another file.
55 Write a C program to merge two files into the third file using
command-line arguments.
56 Find no. of lines, words and characters in a file
57 Write a C program to print last n characters of a given file.
C LAB PROGRAMS

WEEK 1

Program: Simple Input and Output in C

Aim: To write a simple C program that takes two numbers as input from
the user using scanf() and displays their sum using printf().

Algorithm:

1. Start the program.


2. Declare two integer variables a and b.
3. Use scanf () to read two integer values from the user.
4. Compute the sum sum = a + b.
5. Display the entered numbers and their sum using printf ().
6. Stop the program.

Code:

#include <stdio.h>
int main() {
int a, b, sum;

// Input

printf("Enter two numbers: ");

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

// Processing

sum = a + b;

// Output
printf("You entered: %d and %d\n", a, b);
printf("Sum = %d\n", sum);
return 0;
}
Sample Input/Output:
Enter two numbers: 10 20
You entered: 10 and 20
Sum = 30

WEEK 2

1) Sum and Average of 3 Numbers

Aim:To write a C program to find the sum and average of 3 numbers.

Algorithm:

1. Start the program.


2. Declare three integer variables a, b, c and one float variable
avg.
3. Read three numbers from the user.
4. Compute sum = a + b + c.
5. Compute avg = sum / 3.0.
6. Display sum and average.
7. Stop.

Code:
#include <stdio.h>
int main() {
int a, b, c, sum;
float avg;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
sum = a + b + c;
avg = sum / 3.0;
printf("Sum = %d\n", sum);
printf("Average = %.2f\n", avg);
return 0;
}
Sample Input/Output:
Enter three numbers: 10 20 30
Sum = 60
Average = 20.00

2) Conversion of Fahrenheit to Celsius and Vice Versa


Aim:
To write a C program to convert Fahrenheit to Celsius and Celsius to
Fahrenheit.
Algorithm:
1. Start.
2. Declare float variables celsius, fahrenheit.
3. Read temperature in Fahrenheit and convert to Celsius using
celsius = (fahrenheit - 32) * 5/9.
4. Read temperature in Celsius and convert to Fahrenheit using
fahrenheit = (celsius * 9/5) + 32.
5. Print both results.
6. Stop.
Code:
#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) * 5.0 / 9.0;
printf("Celsius = %.2f\n", celsius);
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9.0 / 5.0) + 32;
printf("Fahrenheit = %.2f\n", fahrenheit);
return 0;
}
Sample Input/Output:
Enter temperature in Fahrenheit: 98.6
Celsius = 37.00
Enter temperature in Celsius: 100
Fahrenheit = 212.00

3) Simple Interest Calculation


Aim:
To write a C program to calculate simple interest.
Algorithm:
1. Start.
2. Declare float variables P, R, T, SI.
3. Read principal amount (P), rate of interest (R), and time (T).
4. Compute simple interest: SI = (P * R * T) / 100.
5. Display SI.
6. Stop.
Code:
#include <stdio.h>
int main() {
float P, R, T, SI;
printf("Enter Principal amount: ");
scanf("%f", &P);
printf("Enter Rate of interest: ");
scanf("%f", &R);
printf("Enter Time (in years): ");
scanf("%f", &T);
SI = (P * R * T) / 100;
printf("Simple Interest = %.2f\n", SI);
return 0;
}
Sample Input/Output:
Enter Principal amount: 10000
Enter Rate of interest: 5
Enter Time (in years): 2
Simple Interest = 1000.00
WEEK 3
1) Finding the Square Root of a Given Number
Aim:
To write a C program to find the square root of a given number.
Algorithm:
1. Start.
2. Declare variable num and sqrtValue.
3. Read number num.
4. Use sqrt(num) function from math.h.
5. Print result.
6. Stop.
Code:
#include <stdio.h>
#include <math.h>
int main() {
double num, sqrtValue;
printf("Enter a number: ");
scanf("%lf", &num);
sqrtValue = sqrt(num);
printf("Square root = %.2lf\n", sqrtValue);
return 0;
}
Sample Input/Output:
Enter a number: 49
Square root = 7.00

2) Finding Compound Interest


Aim:
To write a C program to calculate compound interest.
Algorithm:
1. Start.
2. Declare float variables P, R, T, CI.
3. Read principal amount (P), rate (R), and time (T).
4. Compute: CI = P * (pow((1 + R / 100), T) - 1).
5. Print CI.
6. Stop.
Code:
#include <stdio.h>
#include <math.h>
int main() {
double P, R, T, CI;
printf("Enter Principal: ");
scanf("%lf", &P);
printf("Enter Rate of Interest: ");
scanf("%lf", &R);
printf("Enter Time (in years): ");
scanf("%lf", &T);
CI = P * (pow((1 + R / 100), T) - 1);
printf("Compound Interest = %.2lf\n", CI);
return 0;
}
Sample Input/Output:
Enter Principal: 10000
Enter Rate of Interest: 5
Enter Time (in years): 2
Compound Interest = 1025.00

3) Area of a Triangle using Heron’s Formula


Aim:
To write a C program to find the area of a triangle using Heron’s
formula.
Algorithm:
1. Start.
2. Read three sides a, b, c.
3. Compute semi-perimeter s = (a+b+c)/2.
4. Compute area sqrt(s*(s-a)*(s-b)*(s-c)).
5. Print area.
6. Stop.
Code:
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, s, area;
printf("Enter sides of the triangle: ");
scanf("%lf %lf %lf", &a, &b, &c);
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("Area of the triangle = %.2lf\n", area);
return 0;
}
Sample Input/Output:
Enter sides of the triangle: 3 4 5
Area of the triangle = 6.00

4) Distance Travelled by an Object


Aim:
To write a C program to calculate distance travelled using the formula s
= ut + (1/2)at^2.
Algorithm:
1. Start.
2. Declare float variables u, a, t, s.
3. Read values of u, a, and t.
4. Compute s = u*t + 0.5*a*t*t.
5. Print s.
6. Stop.
Code:
#include <stdio.h>
int main() {
float u, a, t, s;
printf("Enter initial velocity (u): ");
scanf("%f", &u);
printf("Enter acceleration (a): ");
scanf("%f", &a);
printf("Enter time (t): ");
scanf("%f", &t);
s = u*t + 0.5*a*t*t;
printf("Distance travelled = %.2f\n", s);
return 0;
}
Sample Input/Output:
Enter initial velocity (u): 10
Enter acceleration (a): 2
Enter time (t): 5
Distance travelled = 75.00
WEEK 4
1) Evaluate Expressions
Aim:
To write a C program to evaluate given arithmetic expressions.
Algorithm:
1. Start.
2. Declare required variables.
3. Assign values.
4. Evaluate expressions.
5. Print results.
6. Stop.
Code:
#include <stdio.h>
int main() {
int A=5, B=10, C=2, D=3, E=4, F=6, G=2;
int result;
result = A + B * C + (D * E) + F * G;
printf("Expression 1 = %d\n", result);
result = A / B * C - B + A * D / 3;
printf("Expression 2 = %d\n", result);
result = A++ + B-- - A;
printf("Expression 3 = %d\n", result);
int i=5, J;
J = (i++) + (++i);
printf("Expression 4 = %d\n", J);
return 0;
}
Sample Output:
Expression 1 = 55
Expression 2 = -9
Expression 3 = 10
Expression 4 = 12

2) Find Maximum of Three Numbers using Conditional Operator


Aim:
To write a C program to find the maximum of three numbers using the
conditional operator.
Algorithm:
1. Start.
2. Read three numbers a, b, c.
3. Use conditional operator:
max = (a > b ? (a > c ? a : c) : (b > c ? b : c));
4. Print maximum.
5. Stop.
Code:
#include <stdio.h>
int main() {
int a, b, c, max;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
max = (a > b ? (a > c ? a : c) : (b > c ? b : c));
printf("Maximum = %d\n", max);
return 0;
}
Sample Input/Output:
Enter three numbers: 12 45 32
Maximum = 45

3) Marks of 5 Subjects (Total & Average in Float)


Aim:
To write a C program to read marks of 5 subjects and find total and
average.
Algorithm:
1. Start.
2. Declare array marks[5], int total=0, float avg.
3. Read 5 marks.
4. Compute total = sum of marks.
5. avg = total / 5.0.
6. Print total and avg.
7. Stop.
Code:
#include <stdio.h>
int main() {
int marks[5], total = 0;
float avg;
int i;
printf("Enter marks of 5 subjects: ");
for(i=0; i<5; i++) {
scanf("%d", &marks[i]);
total += marks[i];
}
avg = total / 5.0;
printf("Total = %d\n", total);
printf("Average = %.2f\n", avg);
return 0;
}
Sample Input/Output:
Enter marks of 5 subjects: 80 75 90 85 70
Total = 400
Average = 80.00
WEEK 5 LAB RECORD
Program 1: Find Maximum and Minimum of Four Numbers
AIM:
Write a C program to find the maximum and minimum of four numbers
using if-else.
Algorithm:
1. Start
2. Read four numbers a, b, c, d
3. Assume max = a and min = a
4. Compare b, c, d with max and update if any is larger
5. Compare b, c, d with min and update if any is smaller
6. Print max and min
7. Stop
CODE:
#include <stdio.h>
int main() {
int a, b, c, d;
int max, min;
printf("Enter four numbers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
max = a;
if(b > max){
max = b;
}
if(c > max) {
max = c;
}
if(d > max){
max = d;
}
min = a;
if(b < min){
min = b;
}
if(c < min){
min = c;
}
if(d < min){
min = d;
}
printf("Maximum = %d\n", max);
printf("Minimum = %d\n", min);
return 0;
}
OUTPUT:
Enter four numbers: 10 25 5 40
Maximum = 40
Minimum = 5

Program 2: Generate Electricity Bill


AIM:
Write a C program to generate an electricity bill using if-else.
Algorithm:
1. Start
2. Read the number of electricity units consumed (units)
3. If units <= 100, bill = units * 1.50
4. Else if units <= 200, bill = 100 * 1.50 + (units - 100) * 2.00
5. Else if units <= 300, bill = 100 * 1.50 + 100 * 2.00 + (units - 200)
* 2.50
6. Else, bill = 100 * 1.50 + 100 * 2.00 + 100 * 2.50 + (units - 300) *
3.00
7. Print the total bill
8. Stop
CODE:
#include <stdio.h>
int main() {
int units;
float bill;
printf("Enter electricity units consumed: ");
scanf("%d", &units);
if(units <= 100) {
bill = units * 1.50;
}
else if(units <= 200){
bill = 100 * 1.50 + (units - 100) * 2.00;
}
else if(units <= 300){
bill = 100 * 1.50 + 100 * 2.00 + (units - 200) * 2.50;
}
else{
bill = 100 * 1.50 + 100 * 2.00 + 100 * 2.50 + (units - 300) *
3.00;
}
printf("Electricity Bill = Rs. %.2f\n", bill);
return 0;
}
OUTPUT:
Enter electricity units consumed: 250
Electricity Bill = Rs. 475.00

Program 3: Roots of Quadratic Equation


AIM:
Write a C program to find the roots of a quadratic equation.
Algorithm:
1. Start
2. Read coefficients a, b, c
3. Compute discriminant d = b*b - 4*a*c
4. If d > 0, roots are real and distinct
 root1 = (-b + sqrt(d)) / (2*a)
 root2 = (-b - sqrt(d)) / (2*a)
5. Else if d == 0, roots are real and equal
 root = -b / (2*a)
6. Else, roots are imaginary
7. Print the roots
8. Stop
CODE:
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, d, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
d = b*b - 4*a*c;
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 = -b / (2*a);
printf("Roots are real and equal: %.2f\n", root1);
}
else {
printf("Roots are imaginary\n");
}
return 0;
}
OUTPUT:
Enter coefficients a, b and c: 1 -5 6
Roots are real and distinct: 3.00 and 2.00

Program 4: Calculator using Switch Case


AIM:
Write a C program to simulate a calculator using switch case.
Algorithm:
1. Start
2. Read two numbers a and b
3. Read the operator op (+, -, *, /)
4. Switch(op):
 If +: result = a + b
 If -: result = a - b
 If *: result = a * b
 If /:
 If b != 0 → result = a / b
 Else → print "Division not allowed"
 Default → print "Invalid operator"
5. Print result
6. Stop
CODE:
#include <stdio.h>
int main() {
int a, b;
char op;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &op);
switch(op) {
case '+':
printf("Result = %d\n", a + b);
break;
case '-':
printf("Result = %d\n", a - b);
break;
case '*':
printf("Result = %d\n", a * b);
break;
case '/':
if(b != 0)
printf("Result = %d\n", a / b);
else
printf("Division by zero not allowed\n");
break;
default: printf("Invalid operator\n");
}
return 0;
}
OUTPUT:
Enter first number: 10
Enter second number: 5
Enter operator (+, -, *, /): *
Result = 50

Program 5: Leap Year Check


AIM:
Write a C program to check whether a given year is a leap year or not.
Algorithm:
1. Start
2. Read a year year
3. If (year % 4 == 0 AND year % 100 != 0) OR (year % 400 == 0)
→ print "Leap Year"
4. Else
→ print "Not a Leap Year"
5. Stop
CODE:
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);

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


printf("%d is a Leap Year\n", year);
else
printf("%d is not a Leap Year\n", year);

return 0;
}
OUTPUT:
Enter a year: 2024
2024 is a Leap Year
WEEK 6 LAB RECORD
Program 1: Factorial of a Number
AIM:
Write a C program to find the factorial of a given number using any
loop.
Algorithm:
1. Start
2. Read number n
3. Initialize fact = 1
4. Repeat loop i = 1 to n:
 Multiply fact = fact * i
5. Print factorial
6. Stop
CODE:
#include <stdio.h>

int main() {
int n, i;
long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial of %d = %lld\n", n, fact);
return 0;
}
OUTPUT:
Enter a number: 5
Factorial of 5 = 120
Program 2: Prime Number Check
AIM:
Write a C program to check whether a given number is prime or not.
Algorithm:
1. Start
2. Read number n
3. If n <= 1, set flag = 1 (not prime)
4. Else repeat from i = 2 to n/2:
 If n % i == 0, set flag = 1 and break
5. If flag == 0 → print "Prime"
Else → print "Not Prime"
6. Stop
CODE:
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if(n <= 1) flag = 1;
for(i = 2; i <= n/2; i++) {
if(n % i == 0) {
flag = 1;
break;
}
}
if(flag == 0)
printf("%d is a Prime number\n", n);
else
printf("%d is not a Prime number\n", n);
return 0;

}
OUTPUT:
Enter a number: 7
7 is a Prime number
Program 3: Sine and Cosine Series
AIM:
Write a C program to compute sine and cosine series.
Algorithm:
1. Start
2. Read value x (in radians) and number of terms n
3. Initialize sumS = 0, sumC = 0
4. For sine series (odd terms):
 For i = 0 to n-1:
 term = (−1)i∗(x2i+1)/(2i+1)!(-1)^i * (x^{2i+1}) /
(2i+1)!(−1)i∗(x2i+1)/(2i+1)!
 Add to sumS
5. For cosine series (even terms):
 For i = 0 to n-1:
 term = (−1)i∗(x2i)/(2i)!(-1)^i * (x^{2i}) /
(2i)!(−1)i∗(x2i)/(2i)!
 Add to sumC
6. Print sumS and sumC
7. Stop
CODE:
#include <stdio.h>
#include <math.h>
int main() {
int i, n;
float x, sumS=0, sumC=0, term;
printf("Enter value of x (in radians): ");
scanf("%f", &x);
printf("Enter number of terms: ");
scanf("%d", &n);
for(i=0; i<n; i++) {
term = pow(-1, i) * pow(x, 2*i+1) / tgamma(2*i+2);
sumS += term;
}
for(i=0; i<n; i++) {
term = pow(-1, i) * pow(x, 2*i) / tgamma(2*i+1);
sumC += term;
}
printf("Sin(%f) = %f\n", x, sumS);
printf("Cos(%f) = %f\n", x, sumC);
return 0;
}
OUTPUT:
Enter value of x (in radians): 1.0
Enter number of terms: 5
Sin(1.000000) = 0.841471
Cos(1.000000) = 0.540302
Program 4: Palindrome Number Check
AIM:
Write a C program to check whether a given number is palindrome or
not.
Algorithm:
1. Start
2. Read number n and store it in original
3. Initialize reversed = 0
4. Repeat until n != 0:
 Extract last digit → remainder = n % 10
 Update reversed = reversed * 10 + remainder
 Remove last digit → n = n / 10
5. If reversed == original → print "Palindrome"
Else → print "Not Palindrome"
6. Stop
CODE:
#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while(n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if(original == reversed)
printf("%d is a palindrome.\n", original);
else
printf("%d is not a palindrome.\n", original);
return 0;
}
OUTPUT:
Enter an integer: 121
121 is a palindrome.
Program 5: Pyramid of Numbers
AIM:
Write a C program to construct a pyramid of numbers.
Algorithm:
1. Start
2. Read number of rows rows
3. Repeat for i = 1 to rows:
 Print spaces (rows - i)
 Print numbers from 1 to i
 Move to next line
4. Stop
CODE:
#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<=rows-i; j++) {
printf(" ");
}
for(j=1; j<=i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows: 5
1
12
123
1234
12345
WEEK 7 LAB RECORD
Program 1: Find Min and Max of 1D Array
AIM:
Write a C program to find the minimum and maximum of a 1-D integer
array.
Algorithm:
1. Start
2. Read array size n
3. Read n elements into arr
4. Initialize min = arr[0], max = arr[0]
5. Repeat for i = 1 to n-1:
 If arr[i] < min, update min
 If arr[i] > max, update max
6. Print min and max
7. Stop
CODE:
#include <stdio.h>
int main() {
int n, i;
printf("Enter size of array: ");
scanf("%d", &n);
int arr[n];
printf("Enter array elements: ");
for(i=0;i<n;i++) {
scanf("%d",&arr[i]);
}
int min = arr[0], max = arr[0];
for(i=1;i<n;i++) {
if(arr[i] < min)
min = arr[i];

if(arr[i] > max)


max = arr[i];
}
printf("Min = %d, Max = %d\n", min, max);
return 0;
}
OUTPUT:
Enter size of array: 5
Enter array elements: 3 8 1 6 9
Min = 1, Max = 9
Program 2: Linear Search in Array
AIM:
Write a C program to perform linear search on a 1-D array.
Algorithm:
1. Start
2. Read array size n
3. Read n elements into arr
4. Read search element key
5. Repeat for i = 0 to n-1:
 If arr[i] == key, print "Found at position i+1" and stop
6. If not found, print "Not found"
7. Stop
CODE:
#include <stdio.h>
int main() {
int n, key, i, found=0;
printf("Enter size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter array elements: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter element to search: ");
scanf("%d",&key);
for(i=0;i<n;i++) {
if(arr[i]==key) {
printf("Element found at position %d\n", i+1);
found=1;
break;
}
}
if(!found)
printf("Element not found\n");
return 0;
}
OUTPUT:
Enter size of array: 5
Enter array elements: 2 4 6 8 10
Enter element to search: 8
Element found at position 4
Program 3: Reverse of 1D Array
AIM:
Write a C program to reverse a 1-D integer array.
Algorithm:
1. Start
2. Read array size n
3. Read n elements into arr
4. Print elements from arr[n-1] to arr[0]
5. Stop
CODE:
#include <stdio.h>
int main() {
int n,i;
printf("Enter size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter array elements: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Reversed array: ");
for(i=n-1;i>=0;i--)
printf("%d ",arr[i]);
return 0;
}
OUTPUT:
Enter size of array: 4
Enter array elements: 1 2 3 4
Reversed array: 4 3 2 1
Program 4: 2's Complement of Binary Number
AIM:
Write a C program to find the 2's complement of a given binary number.
Algorithm:
1. Start
2. Read binary number as string bin
3. Convert all bits (0→1, 1→0) (1’s complement)
4. From right to left:
 Add 1 to the first 0 found, change it to 1, and stop
 If bit is 1, change to 0 and continue
5. Print updated binary (2’s complement)
6. Stop
CODE:
#include <stdio.h>
#include <string.h>
int main() {
char bin[20];
int i, len;
printf("Enter a binary number: ");
scanf("%s", bin);
len = strlen(bin);
for(i=0;i<len;i++)
bin[i] = (bin[i]=='0') ? '1':'0';
for(i=len-1;i>=0;i--) {
if(bin[i]=='0') {
bin[i]='1'; break;
}
else
bin[i]='0';
}
printf("2's Complement: %s\n", bin);
return 0;
}
OUTPUT:
Enter a binary number: 1010
2's Complement: 0110
Program 5: Eliminate Duplicates from Array
AIM:
Write a C program to eliminate duplicate elements in an array.
Algorithm:
1. Start
2. Read array size n
3. Read n elements into arr
4. Repeat for i = 0 to n-1:
 Repeat for j = i+1 to n-1:
 If arr[i] == arr[j], shift elements left and decrease n
5. Print new array without duplicates
6. Stop
CODE:
#include <stdio.h>
int main() {
int n,i,j,k;
printf("Enter size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter array elements: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++) {
for(j=i+1;j<n;j++) {
if(arr[i]==arr[j]) {
for(k=j;k<n-1;k++)
arr[k]=arr[k+1];
n--;
j--;
}
}
}
printf("Array after removing duplicates: ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
return 0;
}
OUTPUT:
Enter size of array: 6
Enter array elements: 1 2 2 3 4 4
Array after removing duplicates: 1 2 3 4
WEEK 8 LAB RECORD
Program 1: Addition of Two Matrices
AIM:
Write a C program to perform addition of two matrices.
Algorithm:
1. Start
2. Read rows m and columns n
3. Read matrix a[m][n]
4. Read matrix b[m][n]
5. Compute sum[i][j] = a[i][j] + b[i][j]
6. Print sum matrix
7. Stop
CODE:
#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int i,j,m,n;
printf("Enter rows and columns: ");
scanf("%d %d",&m,&n);
printf("Enter first matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum[i][j]=a[i][j]+b[i][j];
}
}
printf("Resultant Matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",sum[i][j]);
printf("\n");
}
}
return 0;
}
OUTPUT:
Enter rows and columns: 2 2
Enter first matrix: 1 2 3 4
Enter second matrix: 5 6 7 8
Resultant Matrix:
68
10 12
Program 2: Multiplication of Two Matrices
AIM:
Write a C program to perform multiplication of two matrices.
Algorithm:
1. Start
2. Read order of matrices: a[m][n] and b[p][q]
3. If n != p, multiplication not possible → Stop
4. Read both matrices
5. Initialize mul[i][j] = 0
6. Repeat for each row i of a and column j of b:
 Multiply row elements × column elements and add to
mul[i][j]
7. Print product matrix
8. Stop
CODE:
#include <stdio.h>
int main() {
int a[10][10], b[10][10], mul[10][10];
int i,j,k,m,n,p,q;
printf("Enter rows and cols of first matrix: ");
scanf("%d %d",&m,&n);
printf("Enter rows and cols of second matrix: ");
scanf("%d %d",&p,&q);
if(n!=p)
{
printf("Multiplication not possible\n");
return 0;
}
printf("Enter first matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
mul[i][j]=0;
for(k=0;k<n;k++){
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("Resultant Matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d ",mul[i][j]); printf("\n");
}
}
return 0;
}
OUTPUT:
Enter rows and cols of first matrix: 2 2
Enter rows and cols of second matrix: 2 2
Enter first matrix: 1 2 3 4
Enter second matrix: 5 6 7 8
Resultant Matrix:
19 22
43 50
Program 3: Sort Array using Bubble Sort
AIM:
Write a C program to sort array elements using bubble sort.
Algorithm:
1. Start
2. Read array size n
3. Read n elements into arr
4. Repeat i = 0 to n-2:
 Repeat j = 0 to n-i-2:
 If arr[j] > arr[j+1], swap them
5. Print sorted array
6. Stop
CODE:
#include <stdio.h>

int main() {

int n,i,j,temp;

printf("Enter size of array: ");


scanf("%d",&n);

int arr[n];

printf("Enter array elements: ");

for(i=0;i<n;i++) scanf("%d",&arr[i]);

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

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

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

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

printf("Sorted Array: ");

for(i=0;i<n;i++) printf("%d ",arr[i]);

return 0;

}
OUTPUT:
Enter size of array: 5
Enter array elements: 5 3 4 1 2
Sorted Array: 1 2 3 4 5
Program 4: Concatenate Two Strings
AIM:
Write a C program to concatenate two strings without using built-in
functions.
Algorithm:
1. Start
2. Read two strings str1 and str2
3. Find length of str1
4. Append characters of str2 to str1
5. Add null character \0 at the end
6. Print concatenated string
7. Stop
CODE:
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i,j;
printf("Enter first string: \n");
scanf("%s",str1);
printf("Enter second string: \n");
scanf("%s",str2);
for(i=0;str1[i]!='\0';i++);
for(j=0;str2[j]!='\0';j++,i++)
{
str1[i]=str2[j];
}
str1[i]='\0';
printf("Concatenated String: %s\n",str1);
return 0;
}
OUTPUT:
Enter first string: Hello
Enter second string: World
Concatenated String: HelloWorld
Program 5: Reverse a String
AIM:
Write a C program to reverse a string with and without using built-in
string functions.
Algorithm:
1. Start
2. Read string str
3. Find length of str
4. For i = 0 to len-1, store characters in reverse order into rev
5. Print rev (manual method)
6. Use built-in function strrev() to reverse directly
7. Print reversed string (built-in method)
8. Stop
CODE:
#include <stdio.h>

#include <string.h>

int main() {

char str[100], rev[100];

int i,len;

printf("Enter a string: ");

scanf("%s",str);

len=strlen(str);

for(i=0;i<len;i++) {
rev[i]=str[len-i-1];
}

rev[len]='\0';
printf("Reversed String (manual): %s\n",rev);

strrev(str);

printf("Reversed String (built-in): %s\n",str);

return 0;

}
OUTPUT:
Enter a string: OpenAI
Reversed String (manual): IAnepO
Reversed String (built-in): IAnepO

AIM:(ii) To write a program in Reverse a string with out using built-in


string functions
Program:

#include <stdio.h>
#include <string.h>
void main()
{
char string[20],temp;
int i,length;
printf("Enter String : ");
scanf("%s",string);
length=strlen(string)-1;
for(i=0;i<strlen(string)/2;i++)
{
temp=string[i];
string[i]=string[length];
string[length--]=temp;
}
printf("Reverse string :%s",string);
}
Out put : Enter String : hai
Reverse string :iah

WEEK 9 LAB RECORD


Program 1: Sum of a 1D Array using malloc()
AIM:
Write a C program to find the sum of a 1D array using malloc().
Algorithm:
Start
Read size n
Allocate memory dynamically for n integers using malloc()
Read n elements into array
Compute sum of all elements
Print sum
Free allocated memory
Stop
CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n, i, sum = 0;
printf("Enter size of array: ");
scanf("%d", &n);
arr = (int*)malloc(n * sizeof(int));
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum = %d\n", sum);
free(arr);
return 0;
}
OUTPUT:
Enter size of array: 5
Enter 5 elements: 1 2 3 4 5
Sum = 15
Program 2: Total and Average of n Students using Structures
AIM:
Write a C program to calculate the total and average marks of n students
using structures.
Algorithm:
Start
Define structure Student with name and marks
Read number of students n
Read details (name, marks) of each student
Calculate total marks and average
Print total and average
Stop
CODE:
#include <stdio.h>
struct Student {
char name[50];
float marks;
};
int main() {
int n, i;
float total = 0, avg;
struct Student s[100];
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter name and marks of student %d: ", i+1);
scanf("%s %f", s[i].name, &s[i].marks);
total += s[i].marks;
}
avg = total / n;
printf("Total = %.2f, Average = %.2f\n", total, avg);
return 0;
}
OUTPUT:
Enter number of students: 3
Enter name and marks of student 1: Ram 80
Enter name and marks of student 2: Sita 90
Enter name and marks of student 3: Ravi 70
Total = 240.00, Average = 80.00
Program 3: Enter n Students using calloc() and Display Failed
Students List
AIM:
Write a C program to enter n students data using calloc() and display
failed students (marks < 40).
Algorithm:
Start
Define structure Student with name and marks
Read number of students n
Allocate memory using calloc() for n students
Read name and marks of each student
Check if marks < 40 → student failed
Display failed students list
Free allocated memory
Stop
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
float marks;
};
int main() {
int n, i;
struct Student *s;
printf("Enter number of students: ");
scanf("%d", &n);
s = (struct Student*)calloc(n, sizeof(struct Student));
for (i = 0; i < n; i++) {
printf("Enter name and marks of student %d: ", i+1);
scanf("%s %f", s[i].name, &s[i].marks);
}
printf("Failed Students (marks < 40):\n");
for (i = 0; i < n; i++) {
if (s[i].marks < 40)
printf("%s - %.2f\n", s[i].name, s[i].marks);
}
free(s);
return 0;
}
OUTPUT:
Enter number of students: 3
Enter name and marks of student 1: Ram 80
Enter name and marks of student 2: Sita 35
Enter name and marks of student 3: Ravi 50
Failed Students (marks < 40):
Sita - 35.00
Program 4: Read Student Name and Marks from Command Line
AIM:
Write a C program to read student name and marks from the command
line.
Algorithm:
Start
Check if command line arguments are sufficient
If not, display usage message and stop
Otherwise read student name and marks from command line arguments
Print student details
Stop
CODE:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <name> <marks>\n", argv[0]);
return 1;
}
printf("Student Name: %s\n", argv[1]);
printf("Marks: %s\n", argv[2]);
return 0;
}
OUTPUT:
$ ./[Link] Ram 85
Student Name: Ram
Marks: 85
Program 5: Demonstrate realloc()
AIM:
Write a C program to demonstrate the use of realloc().
Algorithm:
Start
Read initial number of elements n
Allocate memory using malloc()
Read n elements into array
Read new size
Reallocate memory using realloc()
Read elements into resized array
Print all elements
Free memory
Stop
CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int*)malloc(n * sizeof(int));
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Enter new size: ");
scanf("%d", &n);
arr = (int*)realloc(arr, n * sizeof(int));
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Final elements: ");
for (i = 0; i < n; i++) printf("%d ", arr[i]);
free(arr);
return 0;
}
OUTPUT:
Enter number of elements: 3
Enter 3 elements: 10 20 30
Enter new size: 5
Enter 5 elements: 10 20 30 40 50
Final elements: 10 20 30 40 50

WEEK 10 LAB RECORD


Program 1: Store and Display Student Information using Structure
AIM:
Write a C program to store and display student information using
structure.
Algorithm:
Start
Define structure Student with roll, name, marks
Read number of students n
Read details of each student
Display details of all students
Stop
CODE:
#include <stdio.h>
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
int n, i;
struct Student s[100];
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter roll, name, marks of student %d: ", i+1);
scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks);
}
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Roll: %d, Name: %s, Marks: %.2f\n", s[i].roll, s[i].name,
s[i].marks);
}
return 0;
}
OUTPUT:
Enter number of students: 2
Enter roll, name, marks of student 1: 1 Ram 80
Enter roll, name, marks of student 2: 2 Sita 90
Student Information:
Roll: 1, Name: Ram, Marks: 80.00
Roll: 2, Name: Sita, Marks: 90.00
Program 2: Demonstrate Union
AIM:
Write a C program to demonstrate the use of union.
Algorithm:
Start
Define union Data with int, float, char
Assign values to union members
Display values
Observe memory sharing
Stop
CODE:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("d.i = %d\n", d.i);
d.f = 20.5;
printf("d.f = %.2f\n", d.f);
sprintf([Link], "Hello");
printf("[Link] = %s\n", [Link]);
return 0;
}
OUTPUT:
d.i = 10
d.f = 20.50
[Link] = Hello
Program 3: Demonstrate Bitfields
AIM:
Write a C program to demonstrate the use of bitfields in structures.
Algorithm:
Start
Define structure with bitfields (a:1, b:3, c:4)
Assign values to members
Display values
Stop
CODE:
#include <stdio.h>
struct BitField {
unsigned int a:1;
unsigned int b:3;
unsigned int c:4;
};
int main() {
struct BitField bf;
bf.a = 1;
bf.b = 7;
bf.c = 15;
printf("a = %u, b = %u, c = %u\n", bf.a, bf.b, bf.c);
return 0;
}
OUTPUT:
a = 1, b = 7, c = 15

Program 4: Write a C program to shift/rotate using bitfields


Aim:Write a C program to shift/rotate using bitfields
Program:
#include <stdio.h>
#define INT_BITS 32
int leftRotate(int n, unsigned int d)
{
return (n << d) | (n >> (INT_BITS - d));
}
int rightRotate(int n, unsigned int d)
{
return (n >> d) | (n << (INT_BITS - d));
}
void main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
}
Output : Left Rotation of 16 by 2 is 64 Right Rotation of 16 by 2 is 4.

Program 5. Write a C program to copy one structure variable to


another structure of the same type
Aim:
Write a C program to copy one structure variable to another structure of
the same type
Program:
#include <stdio.h>
struct myStructure
{
int myNum;
char myLetter;
char myString[30];
};
int main()
{
struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2={14,'c',"hello"};
struct myStructure s3;
s3 = s2;
printf("%d %c %s", [Link], [Link], [Link]);
return 0;
}
Output:14 c hello
Program 6: Singly Linked List Operations
AIM:
Write a C program to implement basic singly linked list operations
(insertion and display).
Algorithm:
Start
Define structure Node with data and next pointer
Initialize head = NULL
Insert nodes at end
Display list
Stop
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertEnd(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) temp = temp->next;
temp->next = newNode;
}
}
void display(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
int n, val, i;
printf("Enter number of nodes: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter value for node %d: ", i+1);
scanf("%d", &val);
insertEnd(&head, val);
}
printf("Linked List: ");
display(head);
return 0;
}
OUTPUT:
Enter number of nodes: 3
Enter value for node 1: 10
Enter value for node 2: 20
Enter value for node 3: 30
Linked List: 10 -> 20 -> 30 -> NULL

WEEK 11 LAB RECORD


Program 1: Demonstrate Call by Value
AIM:
Write a C program to demonstrate call by value using functions.
Algorithm:
Start
Define function swap(a, b)
Inside swap, exchange local values
In main, read two numbers and call swap
Display values before and after function call
Stop
CODE:
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
printf("Inside function: a=%d, b=%d\n", a, b);
}
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("Before function call: x=%d, y=%d\n", x, y);
swap(x, y);
printf("After function call: x=%d, y=%d\n", x, y);
return 0;
}
OUTPUT:
Enter two numbers: 5 10
Before function call: x=5, y=10
Inside function: a=10, b=5
After function call: x=5, y=10

Program 2: Demonstrate String Functions

AIM:
Write a C program to demonstrate string functions strlen, strcpy, strcat,
strcmp.
Algorithm:
Start
Read two strings s1 and s2
Find length using strlen
Copy s1 into another string
Concatenate s1 and s2
Compare s1 and s2
Stop
CODE:
#include <stdio.h>
#include <string.h>
int main() {
char s1[50], s2[50], s3[50];
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
printf("Length of s1 = %lu\n", strlen(s1));
strcpy(s3, s1);
printf("Copy of s1 = %s\n", s3);
strcat(s1, s2);
printf("Concatenation = %s\n", s1);
if (strcmp(s3, s2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
return 0;
}
OUTPUT:
Enter first string: Hello
Enter second string: World
Length of s1 = 5
Copy of s1 = Hello
Concatenation = HelloWorld
Strings are not equal
Program 3: Write a C function to transpose of a matrix.
AIM: to write a C function to transpose of a matrix.
Program:
#include<stdio.h>
int main()
{
int a[20][20],i,j,m,n;
printf("Enter how many rows & columns:");
scanf("%d%d",&m,&n);
printf("Enter %d elements:",m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

}
printf("\nMatrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
printf("\nTranspose Matrix is:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<m;j++)
printf("%d\t",a[j][i]);
}
}
Output:
Enter how many rows & columns:3 3
Enter 9 elements:1 2 3 4 5 6 7 8 9
Matrix is:

1 2 3
4 5 6
7 8 9
Transpose Matrix is:

1 4 7
2 5 8
3 6 9

Program 4: Write a C function to calculate NCR value


AIM: To Write a C function to calculate NCR value
Program:
#include <stdio.h>
int fact(int z);
void main()
{
int n, r, ncr;
printf("\n Enter the value for N and R \n");
scanf("%d%d", &n, &r);
ncr = fact(n) / (fact(r) * fact(n - r));
printf("\n The value of ncr is: %d", ncr);
}
int fact(int z)
{
int f = 1, i;
if (z == 0)
{
return(f);
}
else
{
for (i = 1; i <= z; i++)
{
f = f * i;
}
}
return(f);
}
Output:
Enter the value for N and R
52
The value of ncr is: 10

Program 5: Euler’s Method


AIM:
Write a C program to solve differential equation using Euler’s method.
Algorithm:
Start
Define function f(x,y) = dy/dx
Read x0, y0, h, n
Repeat n times:
y = y + h * f(x,y)
x=x+h
Display result
Stop
CODE:
#include <stdio.h>
float f(float x, float y) {
return x + y;
}
int main() {
float x0, y0, h;
int n, i;
printf("Enter initial x0, y0: ");
scanf("%f %f", &x0, &y0);
printf("Enter step size h: ");
scanf("%f", &h);
printf("Enter number of steps: ");
scanf("%d", &n);
for (i=0; i<n; i++) {
y0 = y0 + h * f(x0, y0);
x0 = x0 + h;
printf("Step %d: x=%.2f, y=%.4f\n", i+1, x0, y0);
}
return 0;
}
OUTPUT:
Enter initial x0, y0: 0 1
Enter step size h: 0.1
Enter number of steps: 5
Step 1: x=0.10, y=1.1000
Step 2: x=0.20, y=1.2200
Step 3: x=0.30, y=1.3620
Step 4: x=0.40, y=1.5282
Step 5: x=0.50, y=1.7210

WEEK 12 – Lab Record

Program 1: Fibonacci Series using Recursion

Aim:
Write a C program to generate Fibonacci series using recursion.

Algorithm:
1. Start
2. Define function fibo(n)
if n == 0 return 0
if n == 1 return 1
else return fibo(n-1) + fibo(n-2)
3. Read n (number of terms)
4. Call fibo(i) in a loop from 0 to n-1
5. Print results
6. Stop

Example:

#include <stdio.h>

int fibo(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fibo(n - 1) + fibo(n - 2);
}

int main() {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);

printf("Fibonacci Series: ");


for (i = 0; i < n; i++) {
printf("%d ", fibo(i));
}
return 0;
}

Input/Output:
Enter number of terms: 6
Fibonacci Series: 0 1 1 2 3 5
Program 2: Factorial using Recursion

Aim:
Write a recursive program to find factorial of a number.

Algorithm:
1. Start
2. Define fact(n)
if n == 0, return 1
else return n * fact(n-1)
3. Read n from user
4. Call function and print result
5. Stop

Code:
#include <stdio.h>
int fact(int n) {
if (n == 0) return 1;
else return n * fact(n - 1);
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Factorial of %d = %d\n", n, fact(n));
return 0;
}

Input/Output:
Enter a number: 5
Factorial of 5 = 120
Program 3: GCD (Greatest Common Divisor) using Recursion

Aim:
Write a recursive function to find GCD of two numbers.
Algorithm:
1. Start
2. Define gcd(a, b)
o If b == 0, return a
o Else return gcd(b, a % b)
3. Read two numbers
4. Call gcd(a, b) and print result
5. Stop

Code:
#include <stdio.h>

int gcd(int a, int b) {


if (b == 0) return a;
else return gcd(b, a % b);
}

int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("GCD of %d and %d = %d\n", x, y, gcd(x, y));
return 0;
}

Input/Output:

Enter two numbers: 20 28


GCD of 20 and 28 = 4

Program 4: Sum of Natural Numbers using Recursion


Aim:
Write a recursive program to find the sum of first N natural numbers.

Algorithm:

1. Start
2. Define sum(n)
if n == 0, return 0
else return n + sum(n-1)
3. Read n
4. Call sum(n) and print result
5. Stop

Code:
#include <stdio.h>
int sum(int n) {
if (n == 0) return 0;
else return n + sum(n - 1);
}

int main() {
int n;
printf("Enter N: ");
scanf("%d", &n);
printf("Sum of first %d natural numbers = %d\n", n, sum(n));
return 0;
}

Input/Output:

Enter N: 10
Sum of first 10 natural numbers = 55

Program 5: Ackermann Function using Recursion

Aim:
Write a recursive program to compute Ackermann’s function.

Algorithm:
1. Start
2. Define Ackermann(m, n)
if m == 0 return n + 1
if n == 0 return Ackermann(m-1, 1)
else return Ackermann(m-1, Ackermann(m, n-1))
3. Read m, n
4. Call function and print result
5. Stop

Code:
#include <stdio.h>

int ackermann(int m, int n) {


if (m == 0) return n + 1;
else if (n == 0) return ackermann(m - 1, 1);
else return ackermann(m - 1, ackermann(m, n - 1));
}

int main() {
int m, n;
printf("Enter m and n: ");
scanf("%d %d", &m, &n);
printf("Ackermann(%d, %d) = %d\n", m, n, ackermann(m, n));
return 0;
}
Input/Output:
Enter m and n: 2 3
Ackermann(2, 3) = 9

WEEK 13 – Call by Reference & Pointers

Program 1: Swap Two Numbers using Call by Reference

Aim:
Write a C program to swap two numbers using call by reference.

Algorithm:
1. Start
2. Define function swap(&a, &b) using pointers
o Use a temporary variable to exchange values
3. Call function with addresses of two numbers
4. Print swapped values
5. Stop

Code:
#include <stdio.h>

void swap(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);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}

Input/Output:
Enter two numbers: 10 20
After swapping: a = 20, b = 10

Program 2: Demonstrate Dangling Pointer Problem

Aim:
Write a C program to demonstrate dangling pointer problem.

Algorithm:
1. Start
2. Declare a pointer p and assign memory dynamically
3. Free the memory using free(p)
4. Print pointer after freeing → dangling pointer
5. Stop

Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int *)malloc(sizeof(int));
*p = 100;
printf("Before free: *p = %d\n", *p);
free(p); // memory deallocated
p = NULL; // avoid dangling pointer
if (p == NULL)
printf("Pointer is now NULL (avoiding dangling pointer)\n");
return 0;
}
Input/Output:
Before free: *p = 100
Pointer is now NULL (avoiding dangling pointer)

Program 3: Copy One String into Another using Pointers

Aim:
Write a C program to copy one string into another using pointers.

Algorithm:
1. Start
2. Read a string into str1
3. Use pointer variables to copy characters from str1 to str2 until
'\0'
4. Print str2
5. Stop

Code:
#include <stdio.h>
int main() {
char str1[100], str2[100];
char *p1 = str1, *p2 = str2;
printf("Enter a string: ");
gets(str1);
while (*p1 != '\0') {
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
printf("Copied string: %s\n", str2);
return 0;
}
Input/Output:
Enter a string: Hello
Copied string: Hello

Program 4: Count Number of Characters in a String using Pointers

Aim:
Write a C program to count the number of characters in a string using
pointers.

Algorithm:
1. Start
2. Read a string str
3. Use pointer p to traverse each character until '\0'
4. Increment counter for each character
5. Print the count
6. Stop

Code:
#include <stdio.h>
int main() {
char str[100];
char *p;
int count = 0;
printf("Enter a string: ");
gets(str);
p = str;
while (*p != '\0') {
count++;
p++;
}

printf("Number of characters: %d\n", count);


return 0;
}

Input/Output:
Enter a string: OpenAI
Number of characters: 6

WEEK 14 – File Handling

Program 1: Copy the Contents of One File to Another

Aim:
Write a C program to copy the contents of one file to another.

Algorithm:
1. Start
2. Open [Link] in read mode and [Link] in write mode
3. Read each character from [Link] until EOF
4. Write each character into [Link]
5. Close both files
6. Stop

Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f1, *f2;
char ch;
f1 = fopen("[Link]", "r");
f2 = fopen("[Link]", "w");
if (f1 == NULL || f2 == NULL) {
printf("Error opening file.\n");
exit(1);
}
while ((ch = fgetc(f1)) != EOF) {
fputc(ch, f2);
}
printf("File copied successfully.\n");
fclose(f1);
fclose(f2);
return 0;
}

Input/Output:
If [Link] contains:
Hello World

[Link] will contain:


Hello World

Program Output:
File copied successfully.

Program 2: Merge Two Files into a Third File (Command-Line


Arguments)

Aim:
Write a C program to merge two files into a third file using command-
line arguments.

Algorithm:
1. Start
2. Open files argv[1], argv[2] in read mode
3. Open argv[3] in write mode
4. Copy contents of first file, then second file into third file
5. Close all files
6. Stop

Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *f1, *f2, *f3;
char ch;
if (argc != 4) {
printf("Usage: %s file1 file2 file3\n", argv[0]);
return 1;
}
f1 = fopen(argv[1], "r");
f2 = fopen(argv[2], "r");
f3 = fopen(argv[3], "w");

if (f1 == NULL || f2 == NULL || f3 == NULL) {


printf("Error opening files.\n");
return 1;
}
while ((ch = fgetc(f1)) != EOF) fputc(ch, f3);
while ((ch = fgetc(f2)) != EOF) fputc(ch, f3);
printf("Files merged successfully into %s\n", argv[3]);
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}

Input/Output (command line):


./[Link] [Link] [Link] [Link]

If [Link] has Hello and [Link] has World, then [Link] will
contain:
HelloWorld

Program 3: Write a C program to write and read text into a file.


code:
#include< stdio.h >
int main()
{

FILE *fp; /* file pointer*/


char fName[20];

printf("\nEnter file name to create :");


scanf("%s",fName);

/*creating (open) a file*/


fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);

printf("\nData written successfully.");


fclose(fp);

/*again open file to read data*/


fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n");
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));

fclose(fp);
return 0;
}
Output
Enter file name to create : [Link]
File created successfully.
Data written successfully.
Contents of file is :
ABC

Program 4: Count Number of Lines, Words, and Characters in a


File

Aim:
Write a C program to count the number of lines, words, and characters
in a file.

Algorithm:
1. Start
2. Open file in read mode
3. Initialize counters → lines = words = chars = 0
4. Read file character by character
if ch == '\n', increment lines
if ch == ' ' || ch == '\n' || ch == '\t', increment words
Always increment chars
5. Display results
6. Stop
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *f;
char ch;
int lines = 0, words = 0, chars = 0, inWord = 0;
f = fopen("[Link]", "r");
if (f == NULL) {
printf("Error opening file.\n");
exit(1);
}

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


chars++;
if (ch == '\n') lines++;

if (isspace(ch))
inWord = 0;
else if (inWord == 0) {
inWord = 1;
words++;
}
}

fclose(f);
printf("Lines: %d\nWords: %d\nCharacters: %d\n", lines, words,
chars);
return 0;
}
Input:
If [Link] contains:
Hello World
C Programming

Output:
Lines: 2
Words: 3
Characters: 25

Program 5: Print N Characters of a File

Aim:
Write a C program to print the first N characters of a given file.

Algorithm:
1. Start
2. Open file in read mode
3. Read characters until N is reached or EOF
4. Print each character
5. Stop

Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f;
char ch;
int n, count = 0;
f = fopen("[Link]", "r");
if (f == NULL) {
printf("Error opening file.\n");
exit(1);
}
printf("Enter number of characters to print: ");
scanf("%d", &n);
while ((ch = fgetc(f)) != EOF && count < n) {
printf("%c", ch);
count++;
}

fclose(f);
return 0;
}

Input:
If [Link] contains:
Hello World

User enters 5

Output:
Hello

You might also like