[go: up one dir, main page]

0% found this document useful (0 votes)
3 views44 pages

Programming in C Manual - New.docx

The document is a laboratory manual for the Programming in C Laboratory course at Mangayarkarasi College of Engineering. It outlines the syllabus, course outcomes, and a list of experiments that students will perform, including various programming tasks in C such as I/O statements, decision-making constructs, loops, arrays, strings, functions, recursion, pointers, structures, and file operations. Each experiment includes an aim, algorithm, program code, and expected output.

Uploaded by

henoya7914
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)
3 views44 pages

Programming in C Manual - New.docx

The document is a laboratory manual for the Programming in C Laboratory course at Mangayarkarasi College of Engineering. It outlines the syllabus, course outcomes, and a list of experiments that students will perform, including various programming tasks in C such as I/O statements, decision-making constructs, loops, arrays, strings, functions, recursion, pointers, structures, and file operations. Each experiment includes an aim, algorithm, program code, and expected output.

Uploaded by

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

MANGAYARKARASI COLLEGE OF ENGINEERING

MANGAYARKARASI NAGAR, PARAVAI, MADURAI – 625 402


(Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai)
Website: http://mce-madurai.ac.in E-Mail: :mangai.enggcoll@gmail.com

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


LABORATORY MANUAL

Sub.Code​ : CS3271
Sub.Name​ : Programming in C Laboratory
Regulation​ : R-2021

Prepared By,​ Approved By,


Ms.S.K.Kezial Elizabeth AP/CSE​ ​ HOD-CSE
Syllabus
1.​ I/O statements, operators, expressions
2.​ decision-making constructs: if-else, goto, switch-case, break-continue
3.​ Loops: for, while, do-while
4.​ Arrays: 1D and 2D, Multi-dimensional arrays, traversal
5.​ Strings: operations
6.​ Functions: call, return, passing parameters by (value, reference), passing arrays to
function.
7.​ Recursion
8.​ Pointers: Pointers to functions, Arrays,Strings, Pointers to Pointers, Array of Pointers
9.​ Structures: Nested Structures, Pointers to Structures, Arrays of Structures and
Unions.
10.​ Files: reading and writing, File pointers, file operations, random access, processor
directives.

COURSE OUTCOMES:
CO1: Demonstrate knowledge on C programming
constructs.
CO2: Develop programs in C using basic constructs.
CO3: Develop programs in C using arrays.
CO4: Develop applications in C using strings, pointers, functions.
CO5: Develop applications in C using structures.
CO6: Develop applications in C using file processing.
LIST OF EXPERIMENTS

S.No Experiments Pg.No Marks

1 Practice of C programs using I/O statements, operators,


expressions

2 Practice of C Program using decision-making constructs:


if-else, goto, switch-case, break-continue

3 Practice of C Program using Loops: for, while, do-while

4 Implementation of Arrays: 1D and 2D, Multi-dimensional


arrays, traversal
5 Implementation of Strings: operations

6 Implementation of Functions: call, return, passing


parameters by (value, reference), passing arrays to function.

7 Implementation of Recursion

8 Implementation of Pointers: Pointers to functions,


Arrays,Strings, Pointers to Pointers, Array of Pointers

9 Implementation of Structures: Nested Structures, Pointers


to Structures, Arrays of Structures and Unions
10 Implementation of Files: reading and writing, File pointers,
file operations, random access, processor directives.
EXPERIMENTS TO COURSE OUTCOMES MAPPING

S.No Experiments/ CO1 CO2 CO3 CO4 CO5


CO

1 Experiment 1 X

2 Experiment 2

3 Experiment3

4 Experiment 4

5 Experiment 5

6 Experiment 6

7 Experiment 7

8 Experiment 8

9 Experiment 9

10 Experiment 10
Exp.No:1 Practice of C programs using I/O statements, operators, expressions

Date:

Program 1:

Calculate area and circumference of a circle

Aim:​
To calculate and display the area and circumference of a circle using the radius.

Algorithm:

1.​ Start
2.​ Input radius
3.​ Calculate area = π × r × r
4.​ Calculate circumference = 2 × π × r
5.​ Display area and circumference
6.​ 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:

Enter the radius of the circle: 5


Area = 78.54
Circumference = 31.42

Program 2: Swap values of two variables (with and without third variable)

Aim:​
To swap two numbers using and without using a third variable.

Algorithm (with third variable):


1.​ Input a, b
2.​ temp = a
3.​ a=b
4.​ b = temp

Algorithm (without third variable):

1.​ Input a, b
2.​ a=a+b
3.​ b=a-b
4.​ a=a-b

Program:

#include <stdio.h>
int main() {
int a, b, temp;
// With third variable
printf("Enter two integers (with temp): ");
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
// Without third variable
printf("Enter two integers (without temp): ");
scanf("%d %d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}

Output:

pgsql
CopyEdit
Enter two integers (with temp): 3 7
After swapping: a = 7, b = 3
Enter two integers (without temp): 4 9
After swapping: a = 9, b = 4

Program 3: Calculate and display the volume of a cube

Aim:​
To calculate and display the volume of a cube.

Algorithm:

1.​ Start
2.​ Input side of the cube
3.​ Calculate volume = side³
4.​ Display volume
5.​ Stop

Program:

#include <stdio.h>
int main() {
float side, volume;
printf("Enter the side of the cube: ");
scanf("%f", &side);
volume = side * side * side;
printf("Volume of cube = %.2f\n", volume);
return 0;
}

Output:

Enter the side of the cube: 3


Volume of cube = 27.00

Program 4: Input 3 integer values and print in forward and reversed order

Aim:​
To input 3 integers and display them in forward and reversed order.

Algorithm:

1.​ Input three integers


2.​ Print them in order
3.​ Print them in reverse order

Program:

#include <stdio.h>
int main() {
int a, b, c;
printf("Enter 3 integers: ");
scanf("%d %d %d", &a, &b, &c);
printf("Forward order: %d %d %d\n", a, b, c);
printf("Reversed order: %d %d %d\n", c, b, a);
return 0;
}

Output:

Enter 3 integers: 10 20 30
Forward order: 10 20 30
Reversed order: 30 20 10
Program 5: Check whether the year is a leap year or not

Aim:​
To check whether a given year is a leap year.

Algorithm:

1.​ Input year


2.​ If (year divisible by 4 and not divisible by 100) OR divisible by 400 → Leap year
3.​ Else → Not a leap year

Program:

#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.

Result:
Thus the Practice of C Program using I/O statements,Operators and expressions has been
successfully executed.
Exp.No:2 Practice of C Program using decision-making constructs: if-else, goto,
switch-case, break-continue
Date:

Program 1: C Program to Check Odd or Even Number:


Aim:
To check whether a number is odd or even using the modulus operator.
Algorithm:
1.​ Start the program.
2.​ Prompt the user to enter a number.
3.​ Use the modulus operator (%) to check if the number is divisible by 2.
4.​ If the remainder is 0, the number is even; otherwise, it's odd.
5.​ End the program.
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: 4
4 is even.

Program 2: Sum of First and Last Digit of a Four-Digit Number

Aim:​
To write a C program to find the sum of the first and last digit of a four-digit number.

Algorithm:

1.​ Start.
2.​ Read a four-digit number.
3.​ Extract the last digit using % 10.
4.​ Extract the first digit by dividing the number by 1000.
5.​ Add the first and last digits.
6.​ Display the result.
7.​ Stop.

Program:

#include <stdio.h>
int main() {
int num, first, last, sum;

printf("Enter a four-digit number: ");


scanf("%d", &num);
last = num % 10;
first = num / 1000;
sum = first + last;
printf("Sum of first and last digit: %d\n", sum);
return 0;
}

Output:

Enter a four-digit number: 1234


Sum of first and last digit: 5

Program 3: Check Whether a Number is Armstrong or Not

Aim:​
To write a C program to check whether a number is an Armstrong number.

Algorithm:

1.​ Start.
2.​ Read the number.
3.​ Count digits.
4.​ Extract each digit, raise it to the power of number of digits, and sum.
5.​ If sum equals original number, it's an Armstrong number.
6.​ Stop.

Program:

#include <stdio.h>
#include <math.h>
int main() {
int num, original, remainder, result = 0, n = 0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;

int temp = num;


while (temp != 0) {
temp /= 10;
n++;
}
temp = num;
while (temp != 0) {
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
}
if (result == original)
printf("%d is an Armstrong number.\n", original);
else
printf("%d is not an Armstrong number.\n", original);

return 0;
}

Output:

Enter a number: 9474


9474 is an Armstrong number.

Program 4: C Program to Perform Calculator Operations (Addition, Subtraction,


Multiplication, Division, Square of a Number)
Aim:
To perform basic calculator operations (addition, subtraction, multiplication, division, and
square) using a C program.
Algorithm:
1.​ Start the program.
2.​ Prompt the user to input two numbers and the operation to perform.
3.​ Use if-else or switch-case to perform the chosen operation.
4.​ Display the result.
5.​ End the program.
C Program:
#include <stdio.h>
#include <math.h>
int main() {
int choice, num1, num2;
printf("Choose operation:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Square of a number\n");
printf("Enter your choice (1-5): ");
scanf("%d", &choice);
if (choice == 5) {
printf("Enter a number: ");
scanf("%d", &num1);
} else if (choice >= 1 && choice <= 4) {
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
} else {
printf("Invalid choice.\n");
return 1;
}

switch (choice) {
case 1:
printf("Result: %d\n", num1 + num2);
break;
case 2:
printf("Result: %d\n", num1 - num2);
break;
case 3:
printf("Result: %d\n", num1 * num2);
break;
case 4:
if (num2 != 0)
printf("Result: %.2f\n", (float)num1 / num2);
else
printf("Error: Division by zero.\n");
break;
case 5:
printf("Square of %d is: %.2f\n", num1, pow(num1, 2));
break;
}

return 0;
}
Output
Choose operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square of a number
Enter your choice (1-5): 1
Enter first number: 10
Enter second number: 5
Result: 15

Result:
Thus the Practice of C Program using decision making constructs if else,goto,switch
case,break-continue are successfully executed.
Exp.No:3 Practice of C Program using Loops: for, while, do-while

Date:

Program 1: Display a Star Pattern

Aim:​
To write a C program to display a star pattern using nested loops.

Algorithm:

1.​ Start.
2.​ Read the number of rows.
3.​ Use outer loop for rows.
4.​ Use inner loop to print * in each row.
5.​ Print newline after each row.
6.​ 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;
}

Output:

Enter number of rows: 5


*
**
***
****
*****

Program 2: Reverse an Integer

Aim:​
To write a C program to reverse the digits of an integer.
Algorithm:

1.​ Start.
2.​ Read the number.
3.​ Initialize reverse = 0.
4.​ Loop while number ≠ 0:
o​ Extract digit using % 10
o​ Multiply reverse by 10 and add digit
o​ Divide number by 10
5.​ Print the reversed number.
6.​ Stop.

Program:
#include <stdio.h>
int main() {
int num, reverse = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Reversed number: %d\n", reverse);
return 0;
}
Output:
Enter an integer: 1234
Reversed number: 4321

Program 3: Generate First n Fibonacci Terms

Aim:​
To write a C program to generate the first n terms of the Fibonacci series.

Algorithm:

1.​ Start.
2.​ Read the value of n.
3.​ Initialize a = 0, b = 1.
4.​ Print a and b.
5.​ Loop from 3 to n:
o​ Calculate next = a + b
o​ Print next
o​ Update a = b, b = next
6.​ Stop.

Program:
#include <stdio.h>
int main() {
int n, i;
int a = 0, b = 1, next;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Output:
Enter number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8

Result:
Thus the Practice of C Program using Loops :for ,While ,Do while are successfully executed.
Exp.No:4

Date: Implementation of Arrays: 1D and 2D, Multi-dimensional arrays, traversal

Program 1: Addition of 2×2 Matrices


Aim:

To write a C program to add two 2×2 matrices.

Algorithm:

1.​ Start.
2.​ Declare 2×2 matrices A, B, and Sum.
3.​ Input elements of matrix A.
4.​ Input elements of matrix B.
5.​ Add corresponding elements: Sum[i][j] = A[i][j] + B[i][j].
6.​ Display the result matrix.
7.​ Stop.

Program:
#include <stdio.h>

int main() {
int A[2][2], B[2][2], Sum[2][2];
int i, j;

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


for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
scanf("%d", &A[i][j]);

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


for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
scanf("%d", &B[i][j]);

// Matrix Addition
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
Sum[i][j] = A[i][j] + B[i][j];

// Output Result
printf("Sum of matrices:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
printf("%d ", Sum[i][j]);
printf("\n");
}

return 0;
}
Output:
Enter elements of first 2x2 matrix:
12
34
Enter elements of second 2x2 matrix:
56
78
Sum of matrices:
68
10 12

Program 2: Multiplication of 3×3 Matrices


Aim:

To write a C program to multiply two 3×3 matrices.

Algorithm:

1.​ Start.
2.​ Declare matrices A, B, and Product.
3.​ Input elements of matrices A and B.
4.​ Use three nested loops:
o​ Outer two loops for i and j (position in result matrix),
o​ Inner loop k for calculating the sum of A[i][k] * B[k][j].
5.​ Store the result in Product[i][j].
6.​ Display the result matrix.
7.​ Stop.

Program:
#include <stdio.h>
int main() {
int A[3][3], B[3][3], Product[3][3];
int i, j, k;

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


for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &A[i][j]);

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


for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &B[i][j]);

// Initialize Product matrix to 0


for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
Product[i][j] = 0;
// Matrix Multiplication
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
for (k = 0; k < 3; k++)
Product[i][j] += A[i][k] * B[k][j];

// Output Result
printf("Product of matrices:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", Product[i][j]);
printf("\n");
}

return 0;
}
Output:
Enter elements of first 3x3 matrix:
123
456
789
Enter elements of second 3x3 matrix:
987
654
321
Product of matrices:
30 24 18
84 69 54
138 114 90

Result:
Thus the Implementation of Arrays are successfully executed.
Exp.No:5

Date: Implementation of String Operations

Program 1: Count Number of Vowels in a String


Aim:

To write a C program to count the number of vowels in a given string.

Algorithm:

1.​ Start.
2.​ Read a string from the user.
3.​ Initialize a counter to 0.
4.​ Traverse the string character by character.
5.​ If the character is a vowel (a, e, i, o, u, case-insensitive), increment the counter.
6.​ Display the total count.
7.​ Stop.

Program:
#include <stdio.h>
int main() {
char str[100];
int i, count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
char ch = str[i];
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}

printf("Number of vowels = %d\n", count);


return 0;
}
Output:
Enter a string: Hello World
Number of vowels = 3

Program 2: Check Palindrome without String Functions


Aim:

To write a C program to check if a string is a palindrome (reads the same backward) without
using string functions.
Algorithm:

1.​ Start.
2.​ Read a string.
3.​ Find the length of the string manually.
4.​ Compare characters from start and end moving toward the center.
5.​ If all match, it's a palindrome; else, not.
6.​ Display result.
7.​ Stop.

Program:
#include <stdio.h>

int main() {
char str[100];
int i, len = 0, flag = 1;
printf("Enter a string: ");
gets(str);
while (str[len] != '\0') len++; // find length

for (i = 0; i < len / 2; i++) {


if (str[i] != str[len - i - 1]) {
flag = 0;
break;
}
}

if (flag)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");

return 0;

🧾 Output:
}

Enter a string: madam


The string is a palindrome.

Program 4: Copy String With and Without String Functions


Aim:

To write a C program to copy a string in two ways: using strcpy() and without any string
functions.

Algorithm:

 Start.
 Declare two character arrays str1 and str2.
 Read the original string into str1.
 Initialize a counter i = 0.
 Repeat the following steps until the end of the string (str1[i] != '\0'):
●​ Copy the character from str1[i] to str2[i].
●​ Increment i by 1.
 After the loop ends, add a null terminator str2[i] = '\0'.
 Display the copied string str2.
 Stop

Program:

#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100], str3[100];
int i;

printf("Enter a string: ");


gets(str1);

// Copy without string functions


for (i = 0; str1[i] != '\0'; i++) {
str2[i] = str1[i];
}
str2[i] = '\0';

// Copy with strcpy()


strcpy(str3, str1);

printf("Copied without function: %s\n", str2);


printf("Copied with strcpy(): %s\n", str3);

return 0;

🧾 Output:
}

csharp
CopyEdit
Enter a string: hello
Copied without function: hello
Copied with strcpy(): hello

Result:
Thus the Implementation of String Operations are successfully executed.
Exp.No:6

Date: Implementation of Functions: call, return, passing parameters by (value,


reference), passing arrays to function.

Program 1:C Program to Check if a Number is Prime Using a Function


Aim:
To design and develop a C function isprime(num) that checks if a given integer is prime and
returns 1 if it is prime, and 0 otherwise. The program should generate prime numbers between
a given range.
Algorithm:
1.​ Start.
2.​ Define the function isprime(num):
o​ If num <= 1, return 0 (not prime).
o​ Loop from 2 to the square root of num. If num is divisible by any number in this
range, return 0.
o​ Otherwise, return 1 (prime).
3.​ In the main function, input the range.
4.​ Loop through the given range and for each number, call the isprime(num) function.
5.​ If the function returns 1, print the number as a prime.
6.​ End.
C Program:
#include <stdio.h>
#include <math.h>
int isprime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}

int main() {
int start, end;
printf("Enter the range (start and end): ");
scanf("%d %d", &start, &end);

printf("Prime numbers between %d and %d are:\n", start, end);


for (int i = start; i <= end; i++) {
if (isprime(i)) {
printf("%d ", i);
}
}
printf("\n");

return 0;
}
Output:

Enter the range (start and end): 10 50


Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47

Program 2. Write a Recursive Function to Generate Fibonacci Series


Aim:
To design a recursive function that generates the Fibonacci series up to a given number.
Algorithm:
1.​ Start.
2.​ Define the recursive function fibonacci(n):
o​ If n == 0, return 0.
o​ If n == 1, return 1.
o​ Otherwise, return fibonacci(n-1) + fibonacci(n-2).
3.​ In the main function, input the number of terms n.
4.​ Loop and call fibonacci(i) for each number from 0 to n-1 to generate the series.
5.​ Output the Fibonacci series.
6.​ End.
C Program:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}

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

printf("Fibonacci series up to %d terms:\n", n);


for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");

return 0;
}
Output:
Enter the number of terms: 10
Fibonacci series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Program 3. C Program to Perform Swapping Using Functions


Aim:
To write a C program that swaps two variables using functions.
Algorithm:
1.​ Start.
2.​ Define a function swap(int *x, int *y) that:
o​ Swaps the values of x and y using a temporary variable.
3.​ In the main function, input two integers a and b.
4.​ Call the swap(a, b) function.
5.​ Output the swapped values.
6.​ End.
C Program:
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Enter two integers: 5 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

Result:
Thus the Implementation of String Operations are successfully executed.
Exp.No:7

Date: Implementation of Recursion

Program 1:. Reverse number using recursion


AIM:
To reverse a number using recursion.

ALGORITHM:
1. Start.
2. Read the number.
3. Use recursion to extract last digit and buildreverse.

4. Display the result.

5. End.
Program:
#include <stdio.h>
int reverse(int num, int rev)
{
if (num == 0)
return rev;
else
return reverse(num / 10, rev * 10 +

num % 10); }

void main(){
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Reversed number is %d", reverse(num, 0));
OUTPUT:
Enter a number: 1234
Reversed number is 4321


Program :2 Recursive Fibonacci series
AIM:
To print Fibonacci series using recursion.
ALGORITHM:
1. Define fibo(n) where:
o If n == 0 return 0
o If n == 1 return 1
o Else return fibo(n-1) + fibo(n-2)
2. Loop to print series.
Program:
#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);

}
void main(){
int i, n;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series:\n");
for (i = 0; i < n; i++)
printf("%d ", fibo(i));
}
OUTPUT:
Enter number of terms: 6
Fibonacci Series:
011235

Program:3 Recursive vs Non-Recursive Factorial and GCD


AIM:
To compare recursive and non-recursive implementation of Factorial
and GCD.
ALGORITHM:

1.​ ∙ Recursive factorial uses fact(n) = n * fact(n-1)


2.​ ∙ Non-recursive factorial uses loop
3.​ ∙ Recursive GCD uses Euclidean algorithm gcd(a,b) = gcd(b,a%b)
4.​ ∙ Non-recursive GCD uses loop
Program:
#include <stdio.h>
int rec_fact(int n) {

if (n == 0)

return 1;
return n * rec_fact(n - 1);
}
int nonrec_fact(int n)
{
int f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
return f;

int rec_gcd(int a, int b)


{
if (b == 0)
return a;
return rec_gcd(b, a % b);

int nonrec_gcd(int a, int b)


{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;

return a;

void main(){
int n, a, b;
printf("Enter number for factorial: ");
scanf("%d", &n);
printf("Recursive Factorial: %d\n", rec_fact(n));
printf("Non-Recursive Factorial: %d\n", nonrec_fact(n));
printf("Enter two numbers for GCD: ");
scanf("%d %d", &a, &b);
printf("Recursive GCD: %d\n", rec_gcd(a, b));
printf("Non-Recursive GCD: %d\n", nonrec_gcd(a, b));
}

OUTPUT:
Enter number for factorial: 5
Recursive Factorial: 120
Non-Recursive Factorial: 120
Enter two numbers for GCD: 12 16
Recursive GCD: 4
Non-Recursive GCD: 4

RESULT:

The C programs on implementation of recursive function has executed successfully and


output verified.
Exp.No:8 Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointers, Array of Pointers
Date:

Program 1: Input/Print Array Using Pointer


AIM:
To input and print array elements using a pointer.

ALGORITHM:

1. Declare array and pointer.

2. Use pointer to read and display elements.

3. End.

CODING:

#include <stdio.h>

void main()
{
int arr[5], i;
int *p;

p = arr;

printf("Enter 5 elements:\n");
for (i = 0; i < 5; i++)
scanf("%d", p + i);
printf("Array elements are:\n");
for (i = 0; i < 5; i++)
printf("%d ", *(p + i));
}
OUTPUT:
Enter 5 elements:

12345

Array elements are:

12345

Program 2: Search Element in Array Using Pointers


AIM:
To search for an element in an array

using pointers.

ALGORITHM:

1. Read array and search element.

2. Traverse with pointer and compare.

3. Print result.

PROGRAM:

#include <stdio.h>
void main()
{

int arr[5], i, key, found = 0;

int *p;

printf("Enter 5 elements:\n");
for (i = 0; i < 5; i++)
scanf("%d", &arr[i]);

printf("Enter element to search: ");


scanf("%d", &key);
p = arr;
for (i = 0; i < 5; i++) {
if (*(p + i) == key)
{
found = 1;
break;
}

if (found)

printf("Element found at position %d", i + 1);

else
printf("Element not found");
}

OUTPUT:

Enter 5 elements:

10 20 30 40 50
Enter element to search: 30
Element found at position 3

RESULT:

The C program executed successfully and output verified

PROGRAM 3: Array Processing Using Pointers (Sum & Average)


AIM:
To calculate sum and average of array elements using pointers.

ALGORITHM:

1. Read elements into array.

2. Use pointer to calculate sum.

3. Compute average.

Program:
#include <stdio.h>
void main() {
int arr[5], i, sum = 0;
float avg;
int *p;
printf("Enter 5 elements:\n");
for (i = 0; i < 5; i++)
scanf("%d", &arr[i]);
p = arr;
for (i = 0; i < 5; i++)
sum += *(p + i);
avg = sum / 5.0;
printf("Sum = %d\n", sum);
printf("Average = %.2f", avg);
}

OUTPUT:

Enter 5 elements:

10 20 30 40 50

Sum = 150

Average = 30.00
48
Program 4: String Sorting Using Array of Pointers
AIM:
To sort a list of strings using an array of pointers.

ALGORITHM:

1. Declare array of string pointers.

2. Use bubble sort to sort strings (using

pointer swap).

3. Print sorted list.

Program:

#include <stdio.h>
#include <string.h>
void main() {

char *str[5] = {"banana", "apple", "cherry", "date", "grape"};

char *temp;
int i, j;

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


{

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

if (strcmp(str[i], str[j]) > 0)

temp = str[i];
str[i] = str[j];
str[j] = temp;
}

}
}
printf("Sorted strings:\n");
for (i = 0; i < 5; i++)
printf("%s\n", str[i]);
}

49
OUTPUT:

Sorted strings:

apple
banana
cherry
date
grape

RESULT:

The C program on Pointers are executed successfully and output verified.


Exp.No:9 Structures: Nested Structures, Pointers to Structures, Arrays
of Structures and Unions
Date:

Program 1: 1. Storing and Displaying Info of 5


Students
Aim:

To create a C program that stores and displays the details of 5 students using a structure.

Algorithm:

1.​ Define a structure Student with members such as name, age, roll_number, and
marks.​

2.​ Declare an array of 5 structures to store information for 5 students.​

3.​ Accept input for each student's information (name, age, roll number, marks).​

4.​ Display the stored information for each student.​

Program:

#include <stdio.h>

struct Student {
char name[50];
int age;
int roll_number;
float marks;
};

int main() {
struct Student students[5]; // Array to hold 5 student
records

// Accepting details for 5 students


for (int i = 0; i < 5; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Enter name: ");
scanf("%s", students[i].name);
printf("Enter age: ");
scanf("%d", &students[i].age);
printf("Enter roll number: ");
scanf("%d", &students[i].roll_number);
printf("Enter marks: ");
scanf("%f", &students[i].marks);
printf("\n");
}

// Displaying the details of the students


printf("Student Details:\n");
for (int i = 0; i < 5; i++) {
printf("Student %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Age: %d\n", students[i].age);
printf("Roll Number: %d\n",
students[i].roll_number);
printf("Marks: %.2f\n", students[i].marks);
printf("\n");
}

return 0;
}

Output:

Enter details for student 1:


Enter name: John
Enter age: 20
Enter roll number: 101
Enter marks: 88.5

Enter details for student 2:


Enter name: Alice
Enter age: 22
Enter roll number: 102
Enter marks: 91.2

Enter details for student 3:


Enter name: Bob
Enter age: 21
Enter roll number: 103
Enter marks: 84.3

Enter details for student 4:


Enter name: Charlie
Enter age: 23
Enter roll number: 104
Enter marks: 78.9

Enter details for student 5:


Enter name: Eve
Enter age: 20
Enter roll number: 105
Enter marks: 92.0

Student Details:
Student 1:
Name: John
Age: 20
Roll Number: 101
Marks: 88.50

Student 2:
Name: Alice
Age: 22
Roll Number: 102
Marks: 91.20

Student 3:
Name: Bob
Age: 21
Roll Number: 103
Marks: 84.30

Student 4:
Name: Charlie
Age: 23
Roll Number: 104
Marks: 78.90

Student 5:
Name: Eve
Age: 20
Roll Number: 105
Marks: 92.00

Program 2: Storing and Displaying Employee Details

Aim:

To create a C program that stores and displays employee details using a structure.

Algorithm:

1.​ Define a structure Employee with members such as name, id, salary, and department.​

2.​ Accept input for employee details.​

3.​ Display the stored information of the employee.​

Program:

#include <stdio.h>

struct Employee {
char name[50];
int id;
float salary;
char department[50];
};

int main() {
struct Employee emp; // Structure variable to store
employee details

// Accepting employee details


printf("Enter employee details:\n");
printf("Enter name: ");
scanf("%s", emp.name);
printf("Enter employee ID: ");
scanf("%d", &emp.id);
printf("Enter salary: ");
scanf("%f", &emp.salary);
printf("Enter department: ");
scanf("%s", emp.department);

// Displaying employee details


printf("\nEmployee Details:\n");
printf("Name: %s\n", emp.name);
printf("Employee ID: %d\n", emp.id);
printf("Salary: %.2f\n", emp.salary);
printf("Department: %s\n", emp.department);

return 0;
}

Output:
yaml
CopyEdit
Enter employee details:
Enter name: David
Enter employee ID: 5001
Enter salary: 55000.50
Enter department: HR

Employee Details:
Name: David
Employee ID: 5001
Salary: 55000.50
Department: HR

Program 3: Function That Accepts and Returns a Structure


AIM:
To pass and return a structure in a function.

ALGORITHM:

1. Define structure Point with x, y.

2. Create function that returns a structure.

3. Call function and display returned values.

Program:

#include <stdio.h>

struct Point
{
int x, y;
};
struct Point getPoint()
{
struct Point p; printf("Enter x and y: ");
scanf("%d %d", &p.x, &p.y);
return p;
}
void main()
{
struct Point pt;

pt = getPoint();
printf("Point: (%d, %d)", pt.x, pt.y);
}

OUTPUT:

Enter x and y: 4 5

Point: (4, 5)

RESULT:

The C program on Structures has executed successfully and output verified.


Exp.No:10 Files: reading and writing, File pointers, file operations, random
access, processor directives
Date:

Program 1: Read a File from Disk


AIM:
To open and read a file.

ALGORITHM:

1. Open file in read mode.

2. Read using fgetc().

3. Display contents.

Program:

#include <stdio.h>
void main()
{
FILE *fp;
char ch;

fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("File not found!");

} else

while ((ch = fgetc(fp)) != EOF)


putchar(ch);
fclose(fp);

}
}

OUTPUT:

(Displays content of test.txt)

Program 2: Print Contents of a File


AIM:
To open and read a file.
ALGORITHM:

1. Open file in read mode.

2. Read using fgetc().

3. Display contents.

Program:

#include <stdio.h>
void main()
{
FILE *fp; char ch;

fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("File not found!");

else

while ((ch = fgetc(fp)) != EOF)


putchar(ch);
fclose(fp);

}
}

Output:

56
Program 3:Reverse first n characters in a file ◆

AIM:

To write a C program to reverse the first n characters in a


given file.

Algorithm:

1. Open the input file in read mode.

2. Read the content of the file up to n characters.

3. Reverse the first n characters.

4. Open the file in write mode or use a temporary file.


5. Write the reversed content followed by the rest of the

original content. 6. Close the file.

Program:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>
void reverse(char *str, int n)
{
for (int i = 0; i < n / 2; i++)
{
char temp = str[i]; str[i] = str[n - i - 1];
str[n - i - 1] = temp;

}
int main()
{
FILE *fp;
char filename[100];
int n;

printf("Enter filename: ");


scanf("%s", filename);
printf("Enter number of characters to reverse: ");
57
scanf("%d", &n);

fp = fopen(filename, "r+"); if (!fp) {


perror("Error opening file");
return 1;
}
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
rewind(fp);
char *buffer = (char *)malloc(length + 1);
fread(buffer, 1, length, fp);
buffer[length] = '\0';
if (n > length) n = length;
reverse(buffer, n);
rewind(fp);

fwrite(buffer, 1, length, fp);

fclose(fp);
free(buffer);
printf("First %d characters reversed
successfully.\n", n); return 0;
}

◆ Output:
Enter filename: data.txt

Enter number of characters to reverse: 5


First 5 characters reversed successfully.

Program 4: Copy one file to another ◆

AIM:

To write a C program to copy contents from one file


to another.

Algorithm:

1. Open source file in read mode.

2. Open destination file in write mode.

3. Read from source and write to destination.

4. Close both files.

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

FILE *src, *dest;

charsrcFile[100], destFile[100];
char ch;
printf("Enter source file name: ");
scanf("%s", srcFile);
printf("Enter destination file name: ");
scanf("%s", destFile);
src = fopen(srcFile, "r");
if (!src)
{
perror("Error opening source file");
return 1;
}
dest = fopen(destFile, "w");
if (!dest)
{
perror("Error opening destination file");
fclose(src);
return 1;
}
while ((ch = fgetc(src)) != EOF)
{
fputc(ch, dest);
}
59
printf("File copied successfully.\n");

fclose(src);
fclose(dest);
return 0;
}

◆ Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully.
Result:

The C program on Files are executed successfully and output was verified.

You might also like