Educational

C programming Experiments

UNIT I – BASIC CONCEPTS & INPUT/OUTPUT (EXPERIMENTS 1–10)

Experiment 1

Title: Hello World Program

Objective: Understand the basic structure of a C program and print output to the console.

Outcome: Able to write and execute a simple C program using printf().

Theory: Every C program starts with the main() function. The #include <stdio.h> header allows the use of input/output functions like printf() and scanf().

Algorithm / Flowchart:

  1. Start program
  2. Write #include <stdio.h>
  3. Define main() function
  4. Use printf() to display “Hello World”
  5. End program

Program Code:

#include <stdio.h>

int main() {

printf(“Hello World\n”);

return 0;

}

Sample I/O:

Output: Hello World

Result: Successfully displayed “Hello World” on the console.

Viva Questions:

  1. What is the purpose of #include <stdio.h>?
  2. What does return 0; signify?
  3. Can a C program have multiple main() functions?
  4. What is the difference between printf and scanf?
  5. What are header files in C?

Experiment 2

Title: Basic Input from User

Objective: Read and display user input.

Outcome: Able to use scanf() for input.

Theory: scanf() reads formatted input from the user. The format specifier (like %d, %f) determines the data type.

Algorithm / Flowchart:

  1. Start program
  2. Include stdio.h
  3. Define main()
  4. Declare variables
  5. Prompt user for input
  6. Read input using scanf()
  7. Display input using printf()
  8. End program

Program Code:

#include <stdio.h>

int main() {

int num;

printf(“Enter an integer: “);

scanf(“%d”, &num);

printf(“You entered: %d\n”, num);

return 0;

}

Sample I/O:

Enter an integer: 25

You entered: 25

Result: Program successfully reads and displays user input.

  

Viva Questions:

  1. How does scanf work internally?
  2. What is the significance of & before the variable?
  3. Can we read multiple variables in one scanf statement?
  4. What happens if the input type does not match the format specifier?
  5. What are common input errors?

 

Experiment 3

Title: Addition of Two Numbers

Objective: Learn to perform arithmetic operations.

Outcome: Able to perform addition of two numbers entered by the user.

Theory: Arithmetic operators in C include +, -, *, /, %.

Algorithm / Flowchart:

  1. Start
  2. Include stdio.h
  3. Declare two integer variables
  4. Input values from user
  5. Add numbers
  6. Display sum
  7. End

Program Code:

#include <stdio.h>

int main() {

int a, b, sum;

printf(“Enter two integers: “);

scanf(“%d %d”, &a, &b);

sum = a + b;

printf(“Sum = %d\n”, sum);

return 0;

}

Sample I/O:

Enter two integers: 5 7

Sum = 12

Result: Successfully performed addition of two numbers.

Viva Questions:

  1. List all arithmetic operators in C.
  2. What is operator precedence?
  3. How is % operator different from /?
  4. Can arithmetic operations be done on float types?
  5. What is integer overflow?

Experiment 4

Title: Subtraction, Multiplication, Division

Objective: Perform all basic arithmetic operations.

Outcome: Able to compute subtraction, multiplication, and division.

Theory: C arithmetic operators follow standard precedence. Parentheses can alter the order of evaluation.

Algorithm / Flowchart:

  1. Start
  2. Include stdio.h
  3. Declare variables
  4. Input two numbers
  5. Perform subtraction, multiplication, division
  6. Display results
  7. End

Program Code:

#include <stdio.h>

int main() {

int a, b;

printf(“Enter two integers: “);

scanf(“%d %d”, &a, &b);

printf(“Subtraction: %d\n”, a – b);

printf(“Multiplication: %d\n”, a * b);

printf(“Division: %d\n”, a / b);

return 0;

}

Sample I/O:

Enter two integers: 10 2

Subtraction: 8

Multiplication: 20

Division: 5

Result: Program successfully executed all arithmetic operations.

 Viva Questions:

  1. What is integer division?
  2. How does operator precedence work?
  3. Can you divide by zero in C?
  4. Difference between integer division and float division?
  5. What happens if parentheses are used in expressions?

 

Experiment 5

Title: Swap Two Numbers

Objective: Learn how to swap values using a temporary variable.

Outcome: Able to exchange values of two variables.

Theory: Swapping is done using a temporary variable or arithmetic operations.

Algorithm / Flowchart:

  1. Start
  2. Input two numbers a and b
  3. Use temporary variable temp = a; a = b; b = temp;
  4. Display swapped values
  5. End

Program Code:

#include <stdio.h>

int main() {

int a, b, temp;

printf(“Enter two integers: “);

scanf(“%d %d”, &a, &b);

temp = a;

a = b;

b = temp;

printf(“After swapping: a = %d, b = %d\n”, a, b);

return 0;

}

Sample I/O:

Enter two integers: 3 7

After swapping: a = 7, b = 3

Result: Values successfully swapped.

 

Viva Questions:

  1. Can swapping be done without a temporary variable?
  2. Explain XOR swap technique.
  3. Difference between swapping integers and swapping floats?
  4. Can we swap two numbers using pointers?
  5. Why is swapping useful?

 

 

Experiment 6

Title: Find the Largest of Two Numbers

Objective: Learn to use conditional statements to compare numbers.

Outcome: Able to determine the larger of two numbers using if-else.

Theory: Conditional statements (if, else if, else) allow decision making based on logical conditions.

Algorithm / Flowchart:

  1. Start
  2. Input two numbers a and b
  3. If a > b, print a is larger
  4. Else, print b is larger
  5. End

Program Code:

#include <stdio.h>

int main() {

int a, b;

printf(“Enter two integers: “);

scanf(“%d %d”, &a, &b);

if(a > b)

printf(“%d is larger\n”, a);

else

printf(“%d is larger\n”, b);

return 0;

}

Sample I/O:

Enter two integers: 8 15

15 is larger

Result: Successfully determined the larger number.

Viva Questions:

  1. Difference between if and if-else statements.
  2. Can multiple conditions be checked using nested if?
  3. What happens if the condition is false?
  4. Explain logical operators in conditional statements.
  5. How to compare floating-point numbers?

Experiment 7

Title: Find the Largest of Three Numbers

Objective: Use nested if statements to compare three numbers.

Outcome: Able to determine the largest number among three inputs.

Theory: Nested if statements allow multiple conditions to be checked sequentially.

Algorithm / Flowchart:

  1. Start
  2. Input three numbers a, b, c
  3. Compare a with b and c
  4. Print the largest number
  5. End

Program Code:

#include <stdio.h>

int main() {

int a, b, c;

printf(“Enter three integers: “);

scanf(“%d %d %d”, &a, &b, &c);

if(a > b && a > c)

printf(“%d is largest\n”, a);

else if(b > c)

printf(“%d is largest\n”, b);

else

printf(“%d is largest\n”, c);

return 0;

}

Sample I/O:

Enter three integers: 12 25 18

25 is largest

Result: Successfully determined the largest of three numbers.

Viva Questions:

  1. How do logical AND (&&) and OR (||) operators work?
  2. Can we implement this without nested if?
  3. Difference between else if and multiple if statements.
  4. How to find the smallest number instead?
  5. What happens if all numbers are equal?

 

Experiment 8

Title: Check Even or Odd Number

Objective: Use modulus operator % and conditional statements to check parity.

Outcome: Able to determine whether a number is even or odd.

Theory: A number divisible by 2 (num % 2 == 0) is even; otherwise it’s odd.

Algorithm / Flowchart:

  1. Start
  2. Input number num
  3. If num % 2 == 0, print “Even”
  4. Else, print “Odd”
  5. End

Program Code:

#include <stdio.h>

int main() {

int num;

printf(“Enter an integer: “);

scanf(“%d”, &num);

if(num % 2 == 0)

printf(“%d is Even\n”, num);

else

printf(“%d is Odd\n”, num);

return 0;

}

Sample I/O:

Enter an integer: 13

13 is Odd

Result: Successfully checked parity of a number.

 

Viva Questions:

  1. What does % operator do?
  2. Can this program work for negative numbers?
  3. Difference between == and =?
  4. Can we check even/odd using bitwise operators?
  5. What is the output if input is zero?

 

Experiment 9

Title: Check Leap Year

Objective: Determine if a year is a leap year using conditional statements.

Outcome: Able to implement the logic for leap year calculation.

Theory:
A year is a leap year if:

  • It is divisible by 4 and not divisible by 100, or
  • It is divisible by 400

Algorithm / Flowchart:

  1. Start
  2. Input year y
  3. If (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) then leap year
  4. Else, not leap year
  5. End

Program 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;

}

Sample I/O:

Enter a year: 2000

2000 is a Leap Year

Result: Successfully checked leap year condition.

 

Viva Questions:

  1. Explain the rules for leap year.
  2. Why is year divisible by 100 not a leap year?
  3. Can a leap year be negative?
  4. How to modify program for multiple years?
  5. Can bitwise operations be used here?

 

Experiment 10

Title: Simple Calculator (Using Switch Statement)

Objective: Implement arithmetic operations using switch-case.

Outcome: Able to perform addition, subtraction, multiplication, and division using switch statements.

Theory: The switch statement executes a block of code based on the value of an expression. break prevents fall-through.

Algorithm / Flowchart:

  1. Start
  2. Input two numbers a and b
  3. Input choice (1-add, 2-subtract, 3-multiply, 4-divide)
  4. Use switch-case to perform operation
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int main() {

int a, b, choice;

printf(“Enter two numbers: “);

scanf(“%d %d”, &a, &b);

printf(“Choose operation: 1-Add 2-Subtract 3-Multiply 4-Divide: “);

scanf(“%d”, &choice);

switch(choice) {

case 1: printf(“Sum = %d\n”, a+b); break;

case 2: printf(“Difference = %d\n”, a-b); break;

case 3: printf(“Product = %d\n”, a*b); break;

case 4:

if(b!=0) printf(“Quotient = %d\n”, a/b);

else printf(“Division by zero error\n”);

break;

default: printf(“Invalid choice\n”);

}

return 0;

}

Sample I/O:

Enter two numbers: 10 5

Choose operation: 1-Add 2-Subtract 3-Multiply 4-Divide: 3

Product = 50

Result: Simple calculator successfully performs all operations.

Viva Questions:

  1. What is the purpose of break in switch-case?
  2. Can we use if-else instead of switch?
  3. What happens if break is omitted?
  4. How to extend calculator for modulo and power?
  5. Can switch-case work with strings?

 

 

UNIT II – CONTROL STRUCTURES (EXPERIMENTS 11–20)

Experiment 11

Title: Check Positive, Negative, or Zero

Objective: Learn conditional statements (if-else) for multi-way decisions.

Outcome: Determine whether a number is positive, negative, or zero.

Theory: Multi-way decisions allow programs to choose between three or more alternatives.

Algorithm / Flowchart:

  1. Start
  2. Input number num
  3. If num > 0, print “Positive”
  4. Else if num < 0, print “Negative”
  5. Else print “Zero”
  6. End

Program Code:

#include <stdio.h>

int main() {

int num;

printf(“Enter an integer: “);

scanf(“%d”, &num);

if(num > 0)

printf(“Positive\n”);

else if(num < 0)

printf(“Negative\n”);

else

printf(“Zero\n”);

return 0;

}

Sample I/O:

Enter an integer: -7

Negative

Result: Program successfully classifies number as positive, negative, or zero.

Viva Questions:

  1. What is multi-way selection?
  2. Difference between if-else and nested if?
  3. Can switch-case be used here?
  4. How does C evaluate conditional expressions?
  5. Explain Boolean logic in C.

 

Experiment 12

Title: Find Largest of Three Numbers Using Nested if

Objective: Practice nested if statements.

Outcome: Determine largest of three numbers.

Theory: Nested if statements allow multiple conditional checks sequentially.

Algorithm / Flowchart:

  1. Start
  2. Input three numbers a, b, c
  3. Compare a with b and c
  4. Print the largest number
  5. End

Program Code:

#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 largest\n”, a);

else if(b >= c)

printf(“%d is largest\n”, b);

else

printf(“%d is largest\n”, c);

return 0;

}

Sample I/O:

Enter three numbers: 12 25 18

25 is largest

Result: Correctly identifies the largest number.

 

Viva Questions:

  1. Explain nested if vs multiple if-else.
  2. How does operator precedence affect logical expressions?
  3. Can ternary operator be used here?
  4. What is the difference between >= and >?
  5. Can this program handle equal numbers?

 

Experiment 13

Title: Grade Calculation Using if-else

Objective: Learn decision making with multiple conditions.

Outcome: Assign grades based on marks.

Theory: Grades are assigned using conditional thresholds.

Algorithm / Flowchart:

  1. Start
  2. Input marks
  3. If marks ≥ 90, Grade = A
  4. Else if marks ≥ 80, Grade = B
  5. Else if marks ≥ 70, Grade = C
  6. Else Grade = F
  7. End

Program Code:

#include <stdio.h>

int main() {

int marks;

printf(“Enter marks: “);

scanf(“%d”, &marks);

if(marks >= 90)

printf(“Grade A\n”);

else if(marks >= 80)

printf(“Grade B\n”);

else if(marks >= 70)

printf(“Grade C\n”);

else

printf(“Grade F\n”);

return 0;

}

Sample I/O:

Enter marks: 85

Grade B

Result: Successfully assigned grades.

Viva Questions:

  1. What are decision-making statements?
  2. Difference between multiple if and if-else-if.
  3. Can switch-case be used here?
  4. How to handle invalid marks (<0 or >100)?
  5. What is the importance of condition order?

 

Experiment 14

Title: Simple Interest Calculation Using Switch

Objective: Learn switch-case structure for multiple options.

Outcome: Compute simple interest for different principal, rate, time inputs.

Theory: Switch-case executes a block based on the value of a variable.

Algorithm / Flowchart:

  1. Start
  2. Input principal P, rate R, time T
  3. Choose option: 1-Calculate SI, 2-Display details
  4. Use switch-case
  5. End

Program Code:

#include <stdio.h>

int main() {

float P, R, T, SI;

int choice;

printf(“Enter Principal, Rate, Time: “);

scanf(“%f %f %f”, &P, &R, &T);

printf(“1-Calculate SI\n2-Exit\nEnter choice: “);

scanf(“%d”, &choice);

switch(choice) {

case 1:

SI = (P * R * T) / 100;

printf(“Simple Interest = %.2f\n”, SI);

break;

case 2:

printf(“Exiting\n”);

break;

default:

printf(“Invalid choice\n”);

}

return 0;

}

Sample I/O:

Enter Principal, Rate, Time: 1000 5 2

1-Calculate SI

2-Exit

Enter choice: 1

Simple Interest = 100.00

Result: Successfully computed simple interest.

Viva Questions:

  1. Difference between if-else and switch-case.
  2. Can switch handle float values?
  3. What happens if break is omitted?
  4. Can default case be omitted?
  5. When to prefer switch over if-else?

 

Experiment 15

Title: Display Numbers from 1 to N Using for Loop

Objective: Understand for loop iteration.

Outcome: Display sequence of numbers up to user input.

Theory: The for loop repeats a block of code a known number of times.

Algorithm / Flowchart:

  1. Start
  2. Input N
  3. For i = 1 to N, print i
  4. End

Program Code:

#include <stdio.h>

int main() {

int N, i;

printf(“Enter N: “);

scanf(“%d”, &N);

for(i = 1; i <= N; i++)

printf(“%d “, i);

return 0;

}

Sample I/O:

Enter N: 5

1 2 3 4 5

Result: Numbers displayed correctly using for loop.

Viva Questions:

  1. Difference between for, while, and do-while.
  2. What happens if increment is missing?
  3. Can we write a for loop without initialization?
  4. Can i be float?
  5. How to print numbers in reverse?

 

Experiment 16

Title: Sum of First N Natural Numbers

Objective: Learn how to use loops to accumulate a total.

Outcome: Calculate the sum of the first N natural numbers using for loop.

Theory:
A loop can be used to repeatedly add numbers until a condition is met.
Formula: image

Algorithm / Flowchart:

  1. Start
  2. Input integer n
  3. Initialize sum = 0
  4. For i = 1 to n, add i to sum
  5. Display sum
  6. End

Program Code:

#include <stdio.h>

int main() {

int n, i, sum = 0;

printf(“Enter n: “);

scanf(“%d”, &n);

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

sum += i;

}

printf(“Sum = %d\n”, sum);

return 0;

}

Sample I/O:

Enter n: 5

Sum = 15

Result: Program successfully calculates the sum of first N natural numbers.

 

Viva Questions:

  1. What is the difference between sum += i and sum = sum + i?
  2. Can we use while loop instead of for loop?
  3. What happens if n = 0 or negative?
  4. What is the time complexity of this loop?
  5. Write the mathematical formula for the sum of N natural numbers.

 

Experiment 17

Title: Factorial of a Number Using Loop

Objective: Learn to use loops for product accumulation.

Outcome: Compute factorial of a given number.

Theory:
Factorial of n = n × (n-1) × (n-2) × … × 1

Algorithm / Flowchart:

  1. Start
  2. Input number n
  3. Initialize fact = 1
  4. For i = 1 to n, multiply fact *= i
  5. Display fact
  6. End

Program 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;

}

Sample I/O:

Enter a number: 5

Factorial of 5 = 120

Result: Factorial computed correctly.

 

Viva Questions:

  1. What is factorial used for?
  2. What data type is best for large factorials?
  3. Can factorial be computed recursively?
  4. What is overflow in factorial computation?
  5. How to find factorial of 0?

 

Experiment 18

Title: Reverse a Number

Objective: Practice digit extraction and reverse logic.

Outcome: Reverse an integer using loops.

Theory:
A number can be reversed by repeatedly extracting its last digit using % and dividing by 10.

Algorithm / Flowchart:

  1. Start
  2. Input number n
  3. Initialize rev = 0
  4. While n > 0
    • Extract rem = n % 10
    • rev = rev * 10 + rem
    • n = n / 10
  5. Display rev
  6. End

Program Code:

#include <stdio.h>

int main() {

int n, rev = 0, rem;

printf(“Enter a number: “);

scanf(“%d”, &n);

while(n != 0) {

rem = n % 10;

rev = rev * 10 + rem;

n /= 10;

}

printf(“Reversed number = %d\n”, rev);

return 0;

}

Sample I/O:

Enter a number: 1234

Reversed number = 4321

Result: Successfully reversed the number.

Viva Questions:

  1. What happens if number ends with zero?
  2. Can this logic be applied to negative numbers?
  3. Difference between integer division and floating division?
  4. How can we check if a number is palindrome using this?
  5. What is modulo operator used for?

 

Experiment 19

Title: Check Palindrome Number

Objective: Learn to check if a number reads same backward and forward.

Outcome: Verify if a number is palindrome.

Theory:
A number is palindrome if it equals its reverse.

Algorithm / Flowchart:

  1. Start
  2. Input number n
  3. Store temp = n
  4. Reverse number as in previous experiment
  5. If temp == rev, print palindrome
  6. Else not palindrome
  7. End

Program Code:

#include <stdio.h>

int main() {

int n, rev = 0, rem, temp;

printf(“Enter a number: “);

scanf(“%d”, &n);

temp = n;

while(n != 0) {

rem = n % 10;

rev = rev * 10 + rem;

n /= 10;

}

if(temp == rev)

printf(“%d is a palindrome\n”, temp);

else

printf(“%d is not a palindrome\n”, temp);

return 0;

}

 

Sample I/O:

Enter a number: 121

121 is a palindrome

Result: Correctly identified palindrome number.

Viva Questions:

  1. What is a palindrome?
  2. Can strings also be palindromes?
  3. How can this be modified for strings?
  4. What is the use of temporary variable here?
  5. What happens if number is 0?

 

Experiment 20

Title: Fibonacci Series Using Loops

Objective: Generate Fibonacci sequence using iterative control structures.

Outcome: Display first N Fibonacci numbers.

Theory:
Fibonacci series: 0, 1, 1, 2, 3, 5, 8, …
Each term = sum of previous two terms.

Algorithm / Flowchart:

  1. Start
  2. Input N
  3. Initialize a=0, b=1
  4. Print first two numbers
  5. For i = 3 to N, compute c = a + b, print c, then update a=b, b=c
  6. End

Program Code:

#include <stdio.h>

int main() {

int n, i;

long a = 0, b = 1, c;

printf(“Enter number of terms: “);

scanf(“%d”, &n);

printf(“Fibonacci Series: %ld %ld “, a, b);

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

c = a + b;

printf(“%ld “, c);

a = b;

b = c;

}

return 0;

}

Sample I/O:

Enter number of terms: 7

Fibonacci Series: 0 1 1 2 3 5 8

Result: Successfully generated Fibonacci series.

Viva Questions:

  1. What is Fibonacci sequence?
  2. Difference between iterative and recursive approach?
  3. How to generate only even Fibonacci numbers?
  4. What happens if N = 1?
  5. What is the time complexity?

 

UNIT III – FUNCTIONS & RECURSION (EXPERIMENTS 21–30)

Experiment 21

Title: Function to Add Two Numbers

Objective: Learn to create and call user-defined functions.

Outcome: Able to implement a function for addition of two numbers.

Theory:
Functions modularize code, allowing reuse and better readability.

Algorithm / Flowchart:

  1. Start
  2. Define function add(a, b) returning sum
  3. Input two numbers
  4. Call function add(a,b)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int add(int x, int y) {

return x + y;

}

int main() {

int a, b, sum;

printf(“Enter two numbers: “);

scanf(“%d %d”, &a, &b);

sum = add(a, b);

printf(“Sum = %d\n”, sum);

return 0;

}

Sample I/O:

Enter two numbers: 10 15

Sum = 25

Result: Successfully added two numbers using a function.

 Viva Questions:

  1. What are the advantages of functions?
  2. Difference between user-defined and library functions?
  3. Can a function return multiple values?
  4. What is the difference between call by value and call by reference?
  5. Can main() be called recursively?

 

 Experiment 22

Title: Function to Find Factorial

Objective: Implement factorial using user-defined function.

Outcome: Compute factorial using a separate function.

Theory: Functions can be recursive or non-recursive.

Algorithm / Flowchart:

  1. Start
  2. Define function factorial(n)
  3. Input number n
  4. Call factorial(n)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int factorial(int n) {

int fact = 1, i;

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

fact *= i;

return fact;

}

int main() {

int num;

printf(“Enter a number: “);

scanf(“%d”, &num);

printf(“Factorial of %d = %d\n”, num, factorial(num));

return 0;

}

Sample I/O:

Enter a number: 5

Factorial of 5 = 120

Result: Successfully computed factorial using a function.

 Viva Questions:

  1. Difference between iterative and recursive factorial.
  2. Can we use global variables inside functions?
  3. What is function prototype?
  4. Can a function call itself?
  5. Explain stack usage in recursion.

 

 Experiment 23

Title: Function to Find Largest Number

Objective: Use a function to determine the largest of three numbers.

Outcome: Modular approach for largest number logic.

Theory: Functions improve readability and reduce code duplication.

Algorithm / Flowchart:

  1. Start
  2. Define function largest(a,b,c)
  3. Input three numbers
  4. Call largest(a,b,c)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int largest(int a, int b, int c) {

if(a >= b && a >= c) return a;

else if(b >= c) return b;

else return c;

}

int main() {

int x, y, z;

printf(“Enter three numbers: “);

scanf(“%d %d %d”, &x, &y, &z);

printf(“Largest = %d\n”, largest(x,y,z));

return 0;

}

Sample I/O:

Enter three numbers: 10 25 15

Largest = 25

Result: Function correctly returned largest number.

 Viva Questions:

  1. Can we return multiple values from a function?
  2. Difference between call by value and call by reference.
  3. Can a function call another function?
  4. What is the scope of variables inside a function?
  5. Difference between local and global variables?

 

Experiment 24

Title: Recursive Factorial

Objective: Implement factorial using recursion.

Outcome: Understand recursive function calls.

Theory:
Recursion is when a function calls itself. Base case prevents infinite recursion.

Algorithm / Flowchart:

  1. Start
  2. Define factorial(n) recursively
  3. Input n
  4. Call factorial(n)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int factorial(int n) {

if(n == 0) return 1;

else return n * factorial(n-1);

}

int main() {

int num;

printf(“Enter a number: “);

scanf(“%d”, &num);

printf(“Factorial of %d = %d\n”, num, factorial(num));

return 0;

}

Sample I/O:

Enter a number: 5

Factorial of 5 = 120

Result: Successfully computed factorial recursively.

 Viva Questions:

  1. Difference between recursion and iteration.
  2. What is base case and why is it necessary?
  3. Can recursion be memory-intensive?
  4. Explain stack overflow in recursion.
  5. Other examples of recursive problems.

 

Experiment 25

Title: Fibonacci Series Using Recursion

Objective: Generate Fibonacci numbers recursively.

Outcome: Understand recursive sequence generation.

Theory:
F(n) = F(n-1) + F(n-2), with F(0)=0, F(1)=1

Algorithm / Flowchart:

  1. Start
  2. Define fib(n) recursively
  3. Input number of terms n
  4. Call fib(i) in loop for i = 0 to n-1
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int fib(int n) {

if(n == 0) return 0;

else if(n == 1) return 1;

else return fib(n-1) + fib(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 “, fib(i));

return 0;

}

Sample I/O:

Enter number of terms: 7

Fibonacci series: 0 1 1 2 3 5 8

Result: Successfully generated Fibonacci sequence recursively.

Viva Questions:

  1. Compare recursive and iterative Fibonacci.
  2. Explain time complexity of recursive Fibonacci.
  3. What is memoization?
  4. Can recursion be avoided?
  5. What happens if n is negative?

 

Experiment 26

Title: Prime Number Check Using Function

Objective: Check if a number is prime using a separate function.

Outcome: Modular prime number checking.

Theory:
A prime number has exactly two factors: 1 and itself.

Algorithm / Flowchart:

  1. Start
  2. Define function isPrime(n)
  3. Input n
  4. Call isPrime(n)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int isPrime(int n) {

int i;

if(n <= 1) return 0;

for(i=2;i<=n/2;i++)

if(n%i==0) return 0;

return 1;

}

int main() {

int num;

printf(“Enter a number: “);

scanf(“%d”, &num);

if(isPrime(num)) printf(“%d is Prime\n”, num);

else printf(“%d is Not Prime\n”, num);

return 0;

}

Sample I/O:

Enter a number: 17

17 is Prime

Result: Successfully determined prime number using function.

Viva Questions:

  1. What is a prime number?
  2. How to optimize prime check?
  3. Can recursion be used here?
  4. Difference between prime and composite numbers?
  5. What happens for 0 or 1?

 

Experiment 27

Title: Sum of Array Elements Using Function

Objective: Compute sum of array using a user-defined function.

Outcome: Modular approach to array operations.

Theory:
Functions can accept arrays as arguments.

Algorithm / Flowchart:

  1. Start
  2. Input array of size n
  3. Define function sumArray(arr, n)
  4. Loop through array to sum elements
  5. Display sum
  6. End

Program Code:

#include <stdio.h>

int sumArray(int arr[], int n) {

int sum=0, i;

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

sum += arr[i];

return sum;

}

int main() {

int n, i;

printf(“Enter number of elements: “);

scanf(“%d”, &n);

int arr[n];

printf(“Enter elements: “);

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

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

printf(“Sum of elements = %d\n”, sumArray(arr,n));

return 0;

}

 Sample I/O:

Enter number of elements: 5

Enter elements: 1 2 3 4 5

Sum of elements = 15

Result: Successfully computed array sum using a function.

Viva Questions:

  1. How are arrays passed to functions?
  2. Difference between arr[] and *arr in function argument.
  3. Can function modify array elements?
  4. What is array indexing?
  5. How to pass multidimensional arrays?

 

Experiment 28

Title: Find Maximum in Array Using Function

Objective: Determine largest element using a function.

Outcome: Modular approach to array max.

Theory:
Iterate through array and compare elements to find maximum.

Algorithm / Flowchart:

  1. Start
  2. Input array of size n
  3. Define function maxArray(arr, n)
  4. Loop to find maximum
  5. Display maximum
  6. End

Program Code:

#include <stdio.h>

int maxArray(int arr[], int n) {

int i, max = arr[0];

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

if(arr[i]>max) max=arr[i];

return max;

}

int main() {

int n, i;

printf(“Enter number of elements: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

printf(“Maximum element = %d\n”, maxArray(arr,n));

return 0;

}

 Sample I/O:

Enter number of elements: 5

Enter elements: 12 7 22 9 15

Maximum element = 22

Result: Successfully found maximum element using a function.

Viva Questions:

  1. Difference between local and global max.
  2. Can we return index of maximum?
  3. How to modify function for 2D arrays?
  4. How to handle empty arrays?
  5. What is complexity of this function?

 

 Experiment 29

Title: Recursive Sum of N Numbers

Objective: Compute sum of first N numbers recursively.

Outcome: Practice recursion for accumulation.

Theory:
Sum(n) = n + Sum(n-1), Sum(0)=0

Algorithm / Flowchart:

  1. Start
  2. Define sum(n) recursively
  3. Input n
  4. Call sum(n)
  5. Display result
  6. End

Program Code:

#include <stdio.h>

int sum(int n) {

if(n==0) return 0;

return n + sum(n-1);

}

int main() {

int n;

printf(“Enter n: “);

scanf(“%d”,&n);

printf(“Sum = %d\n”, sum(n));

return 0;

}

Sample I/O:

Enter n: 5

Sum = 15

Result: Recursively computed sum of N numbers.

 Viva Questions:

  1. Difference between iterative and recursive sum.
  2. Explain base case importance.
  3. Can negative numbers be handled?
  4. What is recursion depth?
  5. How is recursion executed internally?

 

Experiment 30

Title: Reverse an Array Using Function

Objective: Reverse elements of an array using a user-defined function.

Outcome: Understand array manipulation via functions.

Theory:
An array can be reversed by swapping elements from both ends.

Algorithm / Flowchart:

  1. Start
  2. Input array of size n
  3. Define function reverseArray(arr, n)
  4. Swap elements: arr[i] ↔ arr[n-i-1] for i = 0 to n/2
  5. Display reversed array
  6. End

Program Code:

#include <stdio.h>

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

int i, temp;

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

temp = arr[i];

arr[i] = arr[n-i-1];

arr[n-i-1] = temp;

}

}

int main() {

int n, i;

printf(“Enter number of elements: “);

scanf(“%d”, &n);

int arr[n];

printf(“Enter elements: “);

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

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

reverseArray(arr,n);

printf(“Reversed Array: “);

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

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

return 0;

}

Sample I/O:

Enter number of elements: 5

Enter elements: 1 2 3 4 5

Reversed Array: 5 4 3 2 1

Result: Array reversed successfully using a function.

Viva Questions:

  1. How are arrays passed to functions in C?
  2. Difference between pass by value and pass by reference for arrays?
  3. Can this function be used for strings?
  4. What is the time complexity?
  5. Can we reverse array recursively?

 

UNIT IV – ARRAYS & STRINGS (EXPERIMENTS 31–40)

Experiment 31

Title: One-Dimensional Array Operations

Objective: Learn array declaration, initialization, and traversal.

Outcome: Able to input, display, and manipulate arrays.

Theory:
Arrays are a collection of homogeneous elements stored in contiguous memory locations.

Algorithm / Flowchart:

  1. Start
  2. Input size of array n
  3. Input array elements
  4. Display array elements
  5. End

Program Code:

#include <stdio.h>

int main() {

int n, i;

printf(“Enter size of array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

printf(“Array elements: “);

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

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

return 0;

}

Sample I/O:

Enter size of array: 5

Enter elements: 10 20 30 40 50

Array elements: 10 20 30 40 50

Result: Array elements successfully stored and displayed.

Viva Questions:

  1. Difference between 1D and 2D arrays.
  2. Can arrays have variable size?
  3. How is memory allocated for arrays?
  4. Can array elements be float?
  5. Explain array indexing in C.

 

Experiment 32

Title: Sum and Average of Array Elements

Objective: Perform computations on array elements.

Outcome: Compute sum and average of array.

Theory:
Sum is calculated by iterating through array; average = sum / n

Algorithm / Flowchart:

  1. Start
  2. Input array elements
  3. Initialize sum = 0
  4. Loop through array, add elements to sum
  5. Calculate average = sum / n
  6. Display sum and average
  7. End

Program Code:

#include <stdio.h>

int main() {

int n, i, sum=0;

float avg;

printf(“Enter size of array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

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

sum += arr[i];

avg = (float)sum/n;

printf(“Sum = %d, Average = %.2f\n”, sum, avg);

return 0;

}

 

Sample I/O:

Enter size of array: 5

Enter elements: 10 20 30 40 50

Sum = 150, Average = 30.00

Result: Successfully computed sum and average of array.

Viva Questions:

  1. What is the data type of average?
  2. Can average be integer type?
  3. Difference between sum of int and float arrays.
  4. What happens if array size is zero?
  5. How to find maximum and minimum in the same loop?

 

 Experiment 33

Title: Reverse an Array

Objective: Reverse elements of a 1D array.

Outcome: Reverse and display array elements.

Theory:
Swap elements at start and end indices iteratively.

Algorithm / Flowchart:

  1. Start
  2. Input array size n and elements
  3. Initialize i=0, j=n-1
  4. Swap arr[i] and arr[j], increment i, decrement j
  5. Repeat until i<j
  6. Display reversed array
  7. End

Program Code:

#include <stdio.h>

int main() {

int n, i, temp;

printf(“Enter size of array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

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

temp = arr[i];

arr[i] = arr[n-i-1];

arr[n-i-1] = temp;

}

printf(“Reversed Array: “);

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

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

return 0;

}

Sample I/O:

Enter size of array: 5

Enter elements: 1 2 3 4 5

Reversed Array: 5 4 3 2 1

Result: Array successfully reversed.

Viva Questions:

  1. How to reverse array recursively?
  2. Difference between original and reversed array.
  3. Can this work for character arrays?
  4. Time complexity of array reversal.
  5. Explain swapping logic.

 

Experiment 34

Title: Linear Search in Array

Objective: Search an element using linear search algorithm.

Outcome: Find position of element in array.

Theory:
Linear search checks each element sequentially until a match is found.

Algorithm / Flowchart:

  1. Start
  2. Input array size n and elements
  3. Input key element
  4. Loop through array: if arr[i]==key, return i
  5. If not found, print “Not found”
  6. End

Program Code:

#include <stdio.h>

int main() {

int n, i, key, found = 0;

printf(“Enter size of array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter 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) {

found=1;

printf(“Element found at position %d\n”, i+1);

break;

}

}

if(!found)

printf(“Element not found\n”);

return 0;

}

Sample I/O:

Enter size of array: 5

Enter elements: 10 20 30 40 50

Enter element to search: 30

Element found at position 3

Result: Linear search executed successfully.

Viva Questions:

  1. Difference between linear and binary search.
  2. What is best, worst, and average case?
  3. Can linear search work for unsorted arrays?
  4. Time complexity of linear search.
  5. How to return multiple occurrences?

 

Experiment 35

Title: Binary Search in Array

Objective: Search an element using binary search.

Outcome: Efficient search in a sorted array.

Theory:
Binary search repeatedly divides the array in half to locate element.

Algorithm / Flowchart:

  1. Start
  2. Input sorted array
  3. Input key
  4. Initialize low=0, high=n-1
  5. While low ≤ high
    • mid = (low+high)/2
    • If arr[mid]==key, found
    • Else if arr[mid]<key, low=mid+1
    • Else, high=mid-1
  6. If not found, print “Not found”
  7. End

Program Code:

#include <stdio.h>

int main() {

int n, i, key, low, high, mid, found=0;

printf(“Enter size of sorted array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

printf(“Enter element to search: “);

scanf(“%d”,&key);

low = 0; high = n-1;

while(low <= high) {

mid = (low + high)/2;

if(arr[mid]==key) { found=1; break; }

else if(arr[mid]<key) low = mid+1;

else high = mid-1;

}

if(found) printf(“Element found at position %d\n”, mid+1);

else printf(“Element not found\n”);

return 0;

}

Sample I/O:

Enter size of sorted array: 5

Enter elements: 10 20 30 40 50

Enter element to search: 40

Element found at position 4

Result: Binary search executed successfully.

Viva Questions:

  1. Difference between linear and binary search.
  2. Why array must be sorted?
  3. Time complexity comparison.
  4. Can binary search be implemented recursively?
  5. Explain mid calculation.

 

Experiment 36

Title: Bubble Sort

Objective: Sort array elements using bubble sort.

Outcome: Understand simple sorting algorithm.

Theory:
Bubble sort repeatedly compares adjacent elements and swaps them if they are in wrong order.

Algorithm / Flowchart:

  1. Start
  2. Input array size n and elements
  3. For i = 0 to n-2
    • For j = 0 to n-i-2
      • If arr[j] > arr[j+1], swap
  4. Display sorted array
  5. End

Program Code:

#include <stdio.h>

int main() {

int n, i, j, temp;

printf(“Enter size of array: “);

scanf(“%d”, &n);

int arr[n];

printf(“Enter 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;

}

Sample I/O:

Enter size of array: 5

Enter elements: 50 20 40 10 30

Sorted array: 10 20 30 40 50

Result: Array sorted successfully using bubble sort.

Viva Questions:

  1. What is the time complexity of bubble sort?
  2. How to optimize bubble sort?
  3. Difference between bubble sort and selection sort.
  4. Can it sort in descending order?
  5. What is best and worst-case scenario?

 

Experiment 37

Title: Selection Sort

Objective: Sort array elements using selection sort.

Outcome: Learn selection sort algorithm.

Theory:
Selection sort selects the minimum element from unsorted portion and places it at the beginning.

Algorithm / Flowchart:

  1. Start
  2. Input array size n and elements
  3. For i = 0 to n-2
    • min = i
    • For j = i+1 to n-1, if arr[j]<arr[min], min=j
    • Swap arr[i] and arr[min]
  4. Display sorted array
  5. End

Program Code:

#include <stdio.h>

int main() {

int n, i, j, min, temp;

printf(“Enter size of array: “);

scanf(“%d”,&n);

int arr[n];

printf(“Enter elements: “);

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

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

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

min=i;

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

if(arr[j]<arr[min]) min=j;

temp=arr[i]; arr[i]=arr[min]; arr[min]=temp;

}

printf(“Sorted array: “);

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

return 0;

}

Sample I/O:

Enter size of array: 5

Enter elements: 25 10 50 40 30

Sorted array: 10 25 30 40 50

Result: Array sorted successfully using selection sort.

Viva Questions:

  1. Difference between bubble and selection sort.
  2. Time complexity of selection sort.
  3. Can it sort in descending order?
  4. Number of swaps in worst case?
  5. Applications of selection sort.

 

Experiment 38

Title: Two-Dimensional Array Operations

Objective: Learn 2D array declaration, initialization, and traversal.

Outcome: Input, display, and manipulate 2D arrays.

Theory:
2D arrays store data in row-column format.

Algorithm / Flowchart:

  1. Start
  2. Input rows m and columns n
  3. Input array elements
  4. Display array elements
  5. End

Program Code:

#include <stdio.h>

int main() {

int m, n, i, j;

printf(“Enter rows and columns: “);

scanf(“%d %d”,&m,&n);

int arr[m][n];

printf(“Enter elements:\n”);

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

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

scanf(“%d”,&arr[i][j]);

printf(“2D Array:\n”);

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

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

printf(“%d “, arr[i][j]);

printf(“\n”);

}

return 0;

}

 

Sample I/O:

Enter rows and columns: 2 3

Enter elements:

1 2 3

4 5 6

2D Array:

1 2 3

4 5 6

Result: Successfully stored and displayed 2D array.

Viva Questions:

  1. Difference between 1D and 2D arrays.
  2. How is memory allocated for 2D arrays?
  3. Can 2D arrays be passed to functions?
  4. Difference between row-major and column-major storage.
  5. Applications of 2D arrays.

 

Experiment 39

Title: Sum of Rows and Columns in 2D Array

Objective: Compute sum of each row and column in a 2D array.

Outcome: Practice 2D array traversal and accumulation.

Theory:
Row sum = sum of elements in each row; Column sum = sum of elements in each column.

Algorithm / Flowchart:

  1. Start
  2. Input 2D array
  3. Loop through rows to compute row sum
  4. Loop through columns to compute column sum
  5. Display results
  6. End

Program Code:

#include <stdio.h>

int main() {

int m, n, i, j;

printf(“Enter rows and columns: “);

scanf(“%d %d”,&m,&n);

int arr[m][n];

printf(“Enter elements:\n”);

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

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

scanf(“%d”,&arr[i][j]);

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

int sum=0;

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

sum += arr[i][j];

printf(“Sum of row %d = %d\n”, i+1, sum);

}

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

int sum=0;

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

sum += arr[i][j];

printf(“Sum of column %d = %d\n”, j+1, sum);

}

return 0;

}

Sample I/O:

Enter rows and columns: 2 3

Enter elements:

1 2 3

4 5 6

Sum of row 1 = 6

Sum of row 2 = 15

Sum of column 1 = 5

Sum of column 2 = 7

Sum of column 3 = 9

Result: Row and column sums computed successfully.

Viva Questions:

  1. Difference between row sum and column sum.
  2. Can this be generalized for any m×n matrix?
  3. How to find diagonal sum?
  4. Applications of matrix sums.
  5. Can this be done using functions?

 

Experiment 40

Title: String Operations (Length, Copy, Concatenation)

Objective: Perform basic string operations in C.

Outcome: Learn to manipulate strings using standard functions.

Theory:
Strings are arrays of characters ending with \0. Standard functions:

  • strlen() – length
  • strcpy() – copy
  • strcat() – concatenate

Algorithm / Flowchart:

  1. Start
  2. Input two strings
  3. Compute length of first string
  4. Copy second string to another variable
  5. Concatenate two strings
  6. Display results
  7. End

Program Code:

#include <stdio.h>

#include <string.h>

int main() {

char str1[50], str2[50], str3[50];

printf(“Enter first string: “);

gets(str1);

printf(“Enter second string: “);

gets(str2);

printf(“Length of first string: %lu\n”, strlen(str1));

strcpy(str3,str2);

printf(“Copied string: %s\n”, str3);

strcat(str1,str2);

printf(“Concatenated string: %s\n”, str1);

return 0;

}

Sample I/O:

Enter first string: Hello

Enter second string: World

Length of first string: 5

Copied string: World

Concatenated string: HelloWorld

Result: Successfully performed string operations.

Viva Questions:

  1. Difference between gets() and scanf().
  2. Explain strlen, strcpy, strcat.
  3. How to compare strings?
  4. What is null character \0?
  5. Can strings be passed to functions?

 

UNIT V – POINTERS (EXPERIMENTS 41–50)

Experiment 41

Title: Introduction to Pointers

Objective: Understand pointer declaration, initialization, and dereferencing.

Outcome: Learn to store and access addresses using pointers.

Theory:
A pointer is a variable that stores the memory address of another variable.

  • * is used to declare pointer
  • & is used to get the address
  • *ptr is used to access value at the address

Algorithm / Flowchart:

  1. Start
  2. Declare integer variable a
  3. Declare pointer int *ptr
  4. Assign ptr = &a
  5. Display address using ptr
  6. Display value using *ptr
  7. End

Program Code:

#include <stdio.h>

int main() {

int a = 10;

int *ptr;

ptr = &a;

printf(“Address of a: %p\n”, ptr);

printf(“Value of a using pointer: %d\n”, *ptr);

return 0;

}

Sample I/O:

Address of a: 0x7ffee3b7b98c

Value of a using pointer: 10

Result: Successfully accessed variable value via pointer.

Viva Questions:

  1. What is a pointer?
  2. Difference between pointer and normal variable.
  3. What is NULL pointer?
  4. What happens if you dereference an uninitialized pointer?
  5. How to declare pointer for float and char?

 

Experiment 42

Title: Pointer Arithmetic

Objective: Learn arithmetic operations on pointers.

Outcome: Increment, decrement, addition, and subtraction of pointers.

Theory:
Pointer arithmetic depends on the size of data type it points to.

  • ptr++ moves to next element of type
  • ptr– moves to previous element

Algorithm / Flowchart:

  1. Start
  2. Declare array of integers
  3. Assign pointer to array
  4. Perform pointer arithmetic to access array elements
  5. Display values
  6. End

Program Code:

#include <stdio.h>

int main() {

int arr[5] = {10, 20, 30, 40, 50};

int *ptr = arr;

int i;

printf(“Array elements using pointer:\n”);

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

printf(“%d “, *(ptr+i));

return 0;

}

Sample I/O:

Array elements using pointer:

10 20 30 40 50

Result: Accessed array elements using pointer arithmetic.

Viva Questions:

  1. What is difference between ptr and &ptr?
  2. Can we subtract two pointers?
  3. How does pointer arithmetic depend on data type?
  4. Can pointer arithmetic be done with void pointers?
  5. Explain *(ptr+i) notation.

 

Experiment 43

Title: Pointer to Pointer

Objective: Understand double pointers.

Outcome: Learn how to store address of a pointer in another pointer.

Theory:

  • Pointer to pointer stores address of another pointer.
  • Declaration: int **pptr;

Algorithm / Flowchart:

  1. Start
  2. Declare variable a
  3. Declare pointer ptr = &a
  4. Declare double pointer pptr = &ptr
  5. Access value using *pptr
  6. End

Program Code:

#include <stdio.h>

int main() {

int a = 100;

int *ptr = &a;

int **pptr = &ptr;

printf(“Value of a using pointer to pointer: %d\n”, **pptr);

return 0;

}

Sample I/O:

Value of a using pointer to pointer: 100

Result: Successfully accessed value via pointer to pointer.

 

Viva Questions:

  1. How many levels of pointers can we have?
  2. Difference between single and double pointers.
  3. Applications of pointer to pointer.
  4. How is memory accessed via double pointer?
  5. Can pointer to pointer point to array?

 

Experiment 44

Title: Passing Pointers to Functions

Objective: Modify variable values using pointers passed to functions.

Outcome: Understand call by reference using pointers.

Theory:
Passing pointer to a function allows direct modification of variable in memory.

Algorithm / Flowchart:

  1. Start
  2. Define function void modify(int *p)
  3. In main, declare a and pass &a to function
  4. Modify value using pointer
  5. Display modified value in main
  6. End

Program Code:

#include <stdio.h>

void modify(int *p) {

*p = *p + 50;

}

int main() {

int a = 100;

modify(&a);

printf(“Modified value of a: %d\n”, a);

return 0;

}

Sample I/O:

Modified value of a: 150

Result: Successfully modified variable using pointer in function.

Viva Questions:

  1. Difference between call by value and call by reference.
  2. Can arrays be modified using pointers in function?
  3. What happens if pointer is NULL?
  4. Explain pointer dereferencing in function.
  5. Can multiple pointers be passed to a function?

 

Experiment 45

Title: Dynamic Memory Allocation (malloc)**

Objective: Allocate memory dynamically using malloc.

Outcome: Learn runtime memory allocation for arrays.

Theory:

  • malloc(size) allocates size bytes and returns pointer.
  • Must include <stdlib.h>

Algorithm / Flowchart:

  1. Start
  2. Input size n
  3. Allocate memory for n integers using malloc
  4. Input elements into allocated memory
  5. Display elements
  6. Free memory
  7. End

Program Code:

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i;

printf(“Enter number of elements: “);

scanf(“%d”,&n);

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

if(ptr==NULL) {

printf(“Memory not allocated.\n”);

return 0;

}

printf(“Enter elements: “);

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

scanf(“%d”,&ptr[i]);

printf(“Elements: “);

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

printf(“%d “, ptr[i]);

free(ptr);

return 0;

}

Sample I/O:

Enter number of elements: 5

Enter elements: 10 20 30 40 50

Elements: 10 20 30 40 50

Result: Memory allocated and freed successfully.

Viva Questions:

  1. Difference between malloc and calloc.
  2. Why free() is necessary?
  3. What happens if malloc fails?
  4. How to check for memory leaks?
  5. Can we realloc memory?

 

Experiment 46

Title: Dynamic Memory Allocation (calloc)**

Objective: Allocate memory dynamically and initialize to zero.

Outcome: Learn calloc for zero-initialized arrays.

Theory:

  • calloc(n, size) allocates memory for n elements, initializes to 0

Program Code:

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i;

printf(“Enter number of elements: “);

scanf(“%d”,&n);

int *ptr = (int*)calloc(n, sizeof(int));

if(ptr==NULL) {

printf(“Memory not allocated.\n”);

return 0;

}

printf(“Enter elements: “);

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

scanf(“%d”,&ptr[i]);

printf(“Elements: “);

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

printf(“%d “, ptr[i]);

free(ptr);

return 0;

}

 

Viva Questions:

  1. Difference between malloc and calloc.
  2. What happens if calloc memory not freed?
  3. Applications of dynamic memory.
  4. Can we use calloc for strings?
  5. How is memory initialized in calloc?

 

Experiment 47

Title: Reallocating Memory (realloc)

Objective: Expand or shrink dynamically allocated memory.

Outcome: Learn how to resize memory at runtime.

Program Code:

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr, n, i;

printf(“Enter initial size: “);

scanf(“%d”,&n);

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

printf(“Enter elements: “);

for(i=0;i<n;i++) scanf(“%d”,&ptr[i]);

printf(“Enter new size: “);

scanf(“%d”,&n);

ptr = (int*)realloc(ptr, n*sizeof(int));

printf(“Enter new elements if any: “);

for(i=0;i<n;i++) scanf(“%d”,&ptr[i]);

printf(“Elements after realloc: “);

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

free(ptr);

return 0;

}

Viva Questions:

  1. Difference between realloc and malloc.
  2. Can realloc shrink memory?
  3. What happens if realloc fails?
  4. Applications of realloc.
  5. How to avoid memory leaks with realloc?

 

Experiment 48

Title: Pointer to Array

Objective: Access array using pointers.

Program Code:

#include <stdio.h>

int main() {

int arr[5] = {10,20,30,40,50};

int *ptr = arr;

for(int i=0;i<5;i++)

printf(“%d “, *(ptr+i));

return 0;

}

Viva Questions:

  1. Difference between arr and &arr
  2. How pointer arithmetic works for arrays
  3. Can we pass array pointer to function
  4. Difference between arr[i] and *(arr+i)
  5. Advantages of using pointers for arrays

 

Experiment 49

Title: Array of Pointers

Objective: Store addresses of multiple variables in an array of pointers.

Program Code:

#include <stdio.h>

int main() {

int a=10,b=20,c=30;

int *ptr[3];

ptr[0]=&a; ptr[1]=&b; ptr[2]=&c;

for(int i=0;i<3;i++)

printf(“%d “, *ptr[i]);

return 0;

}

Viva Questions:

  1. Difference between array of integers and array of pointers
  2. Applications of array of pointers
  3. Can we have pointer to array of pointers?
  4. How memory is stored?
  5. Difference between ptr[i] and *ptr[i]

 

Experiment 50

Title: Pointer and Strings

Objective: Access string using pointers.

Program Code:

#include <stdio.h>

int main() {

char str[] = “Hello”;

char *ptr = str;

while(*ptr != ‘\0’) {

printf(“%c “, *ptr);

ptr++;

}

return 0;

}

Viva Questions:

  1. Difference between char array and char pointer
  2. How to pass string to function using pointer
  3. Explain *ptr++ in context of strings
  4. Can we modify string using pointer
  5. Difference between string literal and char array

 

UNIT VI – STRUCTURES & UNIONS (EXPERIMENTS 51–60)

Experiment 51

Title: Introduction to Structures

Objective: Learn structure declaration, initialization, and access.

Outcome: Understand how to group different data types into a single unit.

Theory:

  • Structure is a user-defined data type to store different data types together.
  • Syntax:

struct structure_name {

data_type member1;

data_type member2;

};

Program Code:

#include <stdio.h>

struct Student {

int id;

char name[20];

float marks;

};

int main() {

struct Student s1 = {1, “Alice”, 95.5};

printf(“ID: %d\nName: %s\nMarks: %.2f\n”, s1.id, s1.name, s1.marks);

return 0;

}

 Viva Questions:

  1. Difference between structure and array.
  2. Can structure members be of different data types?
  3. How to access structure members?
  4. Can structure be passed to function?
  5. Size of a structure?

 

Experiment 52

Title: Array of Structures

Objective: Store and access multiple records using structure array.

Outcome: Manage multiple data sets using structures.

Program Code:

#include <stdio.h>

struct Student {

int id;

char name[20];

float marks;

};

int main() {

struct Student s[3];

for(int i=0;i<3;i++) {

printf(“Enter ID, Name, Marks: “);

scanf(“%d %s %f”,&s[i].id,s[i].name,&s[i].marks);

}

printf(“\nStudent Details:\n”);

for(int i=0;i<3;i++)

printf(“ID: %d, Name: %s, Marks: %.2f\n”, s[i].id, s[i].name, s[i].marks);

return 0;

}

Viva Questions:

  1. Difference between structure and array of structures.
  2. How to input multiple structure records.
  3. How memory is allocated for array of structures.
  4. Can array of structures be passed to a function?
  5. How to sort array of structures?

 

Experiment 53

Title: Nested Structures

Objective: Use one structure inside another.

Outcome: Handle complex data using nested structures.

Program Code:

#include <stdio.h>

struct Date {

int day;

int month;

int year;

};

struct Student {

int id;

char name[20];

struct Date dob;

};

int main() {

struct Student s1 = {1, “Bob”, {12, 5, 2000}};

printf(“ID: %d\nName: %s\nDOB: %d/%d/%d\n”, s1.id, s1.name, s1.dob.day, s1.dob.month, s1.dob.year);

return 0;

}

Viva Questions:

  1. What is nested structure?
  2. How to access members of nested structure?
  3. Can a structure have pointer to another structure?
  4. Difference between nested structure and array of structures.
  5. Applications of nested structures.

 

Experiment 54

Title: Structures and Functions

Objective: Pass structures to functions.

Outcome: Manipulate structured data through functions.

Program Code:

#include <stdio.h>

struct Student {

int id;

char name[20];

float marks;

};

void display(struct Student s) {

printf(“ID: %d, Name: %s, Marks: %.2f\n”, s.id, s.name, s.marks);

}

int main() {

struct Student s1 = {2, “Alice”, 88.5};

display(s1);

return 0;

}

Viva Questions:

  1. Can we pass structure by reference?
  2. Difference between passing by value and pointer.
  3. Can a function return a structure?
  4. How is memory managed for structure in function?
  5. Applications of passing structures to function.

 

Experiment 55

Title: Pointer to Structure

Objective: Access structure members using pointers.

Program Code:

#include <stdio.h>

struct Student {

int id;

char name[20];

float marks;

};

int main() {

struct Student s1 = {1, “Charlie”, 90.0};

struct Student *ptr = &s1;

printf(“ID: %d, Name: %s, Marks: %.2f\n”, ptr->id, ptr->name, ptr->marks);

return 0;

}

Viva Questions:

  1. Difference between . and -> operators.
  2. Can we have pointer to array of structures?
  3. How to dynamically allocate memory for structure?
  4. Difference between pointer to structure and array of structures.
  5. Applications of pointer to structure.

 

Experiment 56

Title: Union Basics

Objective: Learn union declaration and usage.

Outcome: Save memory by sharing storage among members.

Theory:

  • Union allows storing different data types in the same memory location.
  • Only one member can hold a value at a time.

Program Code:

#include <stdio.h>

union Data {

int i;

float f;

char str[20];

};

int main() {

union Data d;

d.i = 10;

printf(“i = %d\n”, d.i);

d.f = 220.5;

printf(“f = %.2f\n”, d.f);

strcpy(d.str,”Hello”);

printf(“str = %s\n”, d.str);

return 0;

}

Viva Questions:

  1. Difference between structure and union.
  2. Memory allocation in union.
  3. Can multiple members store value simultaneously?
  4. Applications of unions.
  5. Why unions are used in embedded systems?

 

Experiment 57

Title: Size of Structure vs Union

Objective: Compare memory usage of structure and union.

Program Code:

#include <stdio.h>

struct S {

int i;

float f;

char c;

};

union U {

int i;

float f;

char c;

};

int main() {

printf(“Size of structure: %lu\n”, sizeof(struct S));

printf(“Size of union: %lu\n”, sizeof(union U));

return 0;

}

Viva Questions:

  1. Why union occupies less memory?
  2. Explain memory alignment in structures.
  3. Can structure size be optimized?
  4. Applications where memory optimization is critical.
  5. Can union contain arrays or structures?

 

Experiment 58

Title: Bit Fields in Structure

Objective: Use bit fields to save memory.

Program Code:

#include <stdio.h>

struct Flags {

unsigned int isOn:1;

unsigned int error:1;

unsigned int mode:2;

};

int main() {

struct Flags f = {1,0,3};

printf(“isOn=%u, error=%u, mode=%u\n”, f.isOn, f.error, f.mode);

return 0;

}

Viva Questions:

  1. What is bit field?
  2. How many bits are used for each member?
  3. Difference between normal member and bit field member.
  4. Applications of bit fields.
  5. Can we use signed and unsigned bit fields?

 

Experiment 59

Title: Nested Unions

Objective: Use union inside a structure.

Program Code:

#include <stdio.h>

struct Data {

int type;

union {

int i;

float f;

char str[20];

} value;

};

int main() {

struct Data d;

d.type=1; d.value.i=100;

printf(“Integer value: %d\n”, d.value.i);

d.type=2; d.value.f=3.14;

printf(“Float value: %.2f\n”, d.value.f);

return 0;

}

Viva Questions:

  1. Difference between nested union and nested structure.
  2. How memory is allocated for nested union?
  3. Can we access all members simultaneously?
  4. Applications of nested unions.
  5. Difference between union and enum.

 

Experiment 60

Title: Typedef with Structure and Union

Objective: Use typedef to simplify structure/union declaration.

Program Code:

#include <stdio.h>

typedef struct {

int id;

char name[20];

} Student;

typedef union {

int i;

float f;

} Data;

int main() {

Student s1 = {1, “Alice”};

Data d; d.f = 3.14;

printf(“Student: %d %s\n”, s1.id, s1.name);

printf(“Data: %.2f\n”, d.f);

return 0;

}

Viva Questions:

  1. Advantages of typedef.
  2. Difference between typedef structure and normal structure.
  3. Can we use typedef for union arrays?
  4. Applications of typedef in large programs.
  5. Difference between typedef and macro.

 

UNIT VII – FILE HANDLING (EXPERIMENTS 61–70)

Experiment 61

Title: File Handling Basics – Create and Write File

Objective: Learn to create a file and write data to it.

Outcome: Understand file pointers and basic file operations.

Theory:

  • Files are used for permanent storage of data.
  • fopen() is used to open/create a file.
  • fprintf() or fputs() is used to write data.
  • fclose() closes the file.

Program Code:

#include <stdio.h>

int main() {

FILE *fp;

fp = fopen(“data.txt”,”w”);

if(fp==NULL) {

printf(“File cannot be opened.\n”);

return 0;

}

fprintf(fp,”Hello, File Handling!\n”);

fclose(fp);

printf(“Data written successfully.\n”);

return 0;

}

Viva Questions:

  1. Difference between text and binary files.
  2. Explain fopen modes (r, w, a, rb, wb).
  3. Why fclose() is necessary?
  4. What is file pointer?
  5. How to check if file exists?

Experiment 62

Title: File Read Operation**

Objective: Read data from a text file.

Program Code:

#include <stdio.h>

int main() {

FILE *fp;

char ch;

fp = fopen(“data.txt”,”r”);

if(fp==NULL) {

printf(“File not found.\n”);

return 0;

}

printf(“File contents:\n”);

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

printf(“%c”, ch);

fclose(fp);

return 0;

}

Viva Questions:

  1. Difference between fgetc() and fscanf().
  2. What is EOF?
  3. How to read line by line?
  4. Difference between binary and text read.
  5. How to check end of file?

 

Experiment 63

Title: File Append Operation**

Objective: Append data to an existing file.

Program Code:

#include <stdio.h>

int main() {

FILE *fp;

fp = fopen(“data.txt”,”a”);

if(fp==NULL) {

printf(“File cannot be opened.\n”);

return 0;

}

fprintf(fp,”Appending new line.\n”);

fclose(fp);

printf(“Data appended successfully.\n”);

return 0;

}

Viva Questions:

  1. Difference between write and append mode.
  2. Can we append binary data?
  3. What happens if file does not exist in append mode?
  4. How to combine reading and appending?
  5. Applications of append mode.

 

Experiment 64

Title: Copy Contents of One File to Another

Objective: Copy data from source file to destination file.

Program Code:

#include <stdio.h>

int main() {

FILE *src, *dest;

char ch;

src = fopen(“data.txt”,”r”);

dest = fopen(“copy.txt”,”w”);

if(src==NULL || dest==NULL) {

printf(“File cannot be opened.\n”);

return 0;

}

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

fputc(ch,dest);

fclose(src); fclose(dest);

printf(“File copied successfully.\n”);

return 0;

}

Viva Questions:

  1. How to copy binary file?
  2. Difference between fgetc/fputc and fread/fwrite.
  3. Can we overwrite destination file?
  4. How to check file size?
  5. Applications of file copy.

 

Experiment 65

Title: Count Characters, Words, and Lines in a File

Objective: Perform file analysis.

Program Code:

#include <stdio.h>

#include <ctype.h>

int main() {

FILE *fp;

char ch;

int characters=0, words=0, lines=0;

fp = fopen(“data.txt”,”r”);

if(fp==NULL) { printf(“File not found.\n”); return 0; }

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

characters++;

if(ch==’ ‘ || ch==’\t’) words++;

if(ch==’\n’) lines++;

}

fclose(fp);

printf(“Characters: %d\nWords: %d\nLines: %d\n”, characters, words+1, lines+1);

return 0;

}

Viva Questions:

  1. How to count punctuation marks?
  2. Difference between text file and binary file.
  3. Can word count be done using fscanf?
  4. Why add 1 to words and lines?
  5. Applications of file statistics.

 

Experiment 66

Title: File Copy Using Command Line Arguments

Objective: Copy files using argv[] parameters.

Program Code:

#include <stdio.h>

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

if(argc != 3) { printf(“Usage: <source> <destination>\n”); return 0; }

FILE *src = fopen(argv[1],”r”);

FILE *dest = fopen(argv[2],”w”);

char ch;

if(src==NULL || dest==NULL) { printf(“File error.\n”); return 0; }

while((ch=fgetc(src))!=EOF) fputc(ch,dest);

fclose(src); fclose(dest);

printf(“File copied successfully.\n”);

return 0;

}

Viva Questions:

  1. Explain argc and argv.
  2. How to handle errors in command line files?
  3. Difference between argv[0] and argv[1].
  4. Can this work for binary files?
  5. Applications of command line arguments.

 

Experiment 67

Title: Random Access in File

Objective: Read/write file at specific position using fseek() and ftell().

Program Code:

#include <stdio.h>

int main() {

FILE *fp = fopen(“data.txt”,”r”);

char ch;

fseek(fp, 5, SEEK_SET); // move 5 bytes from beginning

ch = fgetc(fp);

printf(“Character at 6th position: %c\n”, ch);

fclose(fp);

return 0;

}

Viva Questions:

  1. Difference between SEEK_SET, SEEK_CUR, SEEK_END
  2. How to find current file position?
  3. Can we modify file using fseek?
  4. Applications of random access
  5. Difference between text and binary random access

 

Experiment 68

Title: Binary File Write

Objective: Write integer array to binary file.

Program Code:

#include <stdio.h>

int main() {

FILE *fp = fopen(“data.bin”,”wb”);

int arr[5]={10,20,30,40,50};

fwrite(arr,sizeof(int),5,fp);

fclose(fp);

printf(“Binary data written successfully.\n”);

return 0;

}

Viva Questions:

  1. Difference between text and binary file
  2. Explain fwrite parameters
  3. Can we write structures in binary file?
  4. How to read binary file?
  5. Applications of binary files

 

Experiment 69

Title: Binary File Read

Objective: Read integer array from binary file.

Program Code:

#include <stdio.h>

int main() {

FILE *fp = fopen(“data.bin”,”rb”);

int arr[5];

fread(arr,sizeof(int),5,fp);

fclose(fp);

printf(“Binary file contents: “);

for(int i=0;i<5;i++) printf(“%d “,arr[i]);

return 0;

}

Viva Questions:

  1. Difference between fread and fscanf
  2. Why binary file reading is faster
  3. Can we read partial data
  4. How to determine file size
  5. Applications of binary read

 

Experiment 70

Title: Copy Binary File

Objective: Copy contents of binary file to another.

Program Code:

#include <stdio.h>

int main() {

FILE *src = fopen(“data.bin”,”rb”);

FILE *dest = fopen(“copy.bin”,”wb”);

char ch;

while(fread(&ch,sizeof(char),1,src))

fwrite(&ch,sizeof(char),1,dest);

fclose(src); fclose(dest);

printf(“Binary file copied successfully.\n”);

return 0;

}

Viva Questions:

  1. Difference between copying text and binary files
  2. Explain fread/fwrite
  3. Can we copy structures
  4. Importance of closing files
  5. Applications in real world

 

UNIT VIII – ADVANCED TOPICS & MISC (EXPERIMENTS 71–100)

Experiment 71

Title: Recursive Factorial

Objective: Learn recursion by calculating factorial of a number.

Program Code:

#include <stdio.h>

int factorial(int n) {

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

else return n*factorial(n-1);

}

int main() {

int n;

printf(“Enter number: “);

scanf(“%d”,&n);

printf(“Factorial of %d = %d\n”, n, factorial(n));

return 0;

}

Viva Questions:

  1. What is recursion?
  2. Difference between recursion and iteration.
  3. Base case importance.
  4. Stack memory usage in recursion.
  5. Can factorial be implemented iteratively?

 

Experiment 72

Title: Recursive Fibonacci

Objective: Generate Fibonacci series using recursion.

Program Code:

#include <stdio.h>

int fib(int n) {

if(n==0) return 0;

if(n==1) return 1;

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

}

int main() {

int n;

printf(“Enter number of terms: “);

scanf(“%d”,&n);

printf(“Fibonacci series: “);

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

printf(“%d “, fib(i));

return 0;

}

Viva Questions:

  1. Recursion efficiency.
  2. How to optimize with memoization.
  3. Difference between recursive and iterative Fibonacci.
  4. Stack overflow in recursion.
  5. Applications of Fibonacci series.

 

Experiment 73

Title: Recursive Sum of Array

Objective: Find sum of array elements using recursion.

Program Code:

#include <stdio.h>

int sumArray(int arr[], int n) {

if(n==0) return 0;

return arr[n-1]+sumArray(arr,n-1);

}

int main() {

int arr[5]={1,2,3,4,5};

printf(“Sum of array = %d\n”, sumArray(arr,5));

return 0;

}

Viva Questions:

  1. How recursion works with arrays.
  2. Difference between passing array and pointer.
  3. Maximum recursion depth.
  4. Tail recursion.
  5. Applications of recursive sum.

 

Experiment 74

Title: Macros in C

Objective: Learn macro definition and usage.

Program Code:

#include <stdio.h>

#define PI 3.14159

#define SQUARE(x) ((x)*(x))

int main() {

int r=5;

printf(“PI = %.2f\n”, PI);

printf(“Square of %d = %d\n”, r, SQUARE(r));

return 0;

}

Viva Questions:

  1. Difference between macro and function.
  2. When to use macros.
  3. Advantages and disadvantages.
  4. Can macros take multiple parameters?
  5. Explain pitfalls of macros.

 

Experiment 75

Title: Preprocessor Directives

Objective: Learn #include, #define, #ifdef, #ifndef.

Program Code:

#include <stdio.h>

#define FLAG

int main() {

#ifdef FLAG

printf(“FLAG is defined\n”);

#else

printf(“FLAG not defined\n”);

#endif

return 0;

}

Viva Questions:

  1. Difference between compile-time and run-time.
  2. Explain conditional compilation.
  3. How to prevent multiple inclusions.
  4. Difference between #include<> and #include””.
  5. Applications of preprocessor directives.

 

Experiment 76

Title: Command Line Arguments

Objective: Use command line arguments in program.

Program Code:

#include <stdio.h>

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

printf(“Number of arguments: %d\n”, argc);

for(int i=0;i<argc;i++)

printf(“Argument %d: %s\n”, i, argv[i]);

return 0;

}

Viva Questions:

  1. Difference between argc and argv.
  2. Can we pass integers via command line?
  3. Applications of command line arguments.
  4. Difference between argv[0] and argv[1].
  5. Error handling in arguments.

 

Experiment 77

Title: String Reverse using Pointers

Objective: Reverse a string using pointer.

Program Code:

#include <stdio.h>

#include <string.h>

int main() {

char str[50], *ptr, temp;

printf(“Enter string: “);

gets(str);

int n = strlen(str);

ptr = str;

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

temp = *(ptr+i);

*(ptr+i) = *(ptr+n-i-1);

*(ptr+n-i-1) = temp;

}

printf(“Reversed string: %s\n”, str);

return 0;

}

Viva Questions:

  1. Difference between array and pointer for strings.
  2. Can we reverse string recursively?
  3. How strlen works internally.
  4. Difference between gets() and fgets().
  5. Applications of string reverse.

 

Experiment 78

Title: Palindrome Check (String & Number)**

Program Code (String):

#include <stdio.h>

#include <string.h>

int main() {

char str[50];

int flag=0;

printf(“Enter string: “); gets(str);

int n=strlen(str);

for(int i=0;i<n/2;i++)

if(str[i]!=str[n-i-1]) flag=1;

if(flag==0) printf(“Palindrome\n”);

else printf(“Not Palindrome\n”);

return 0;

}

Program Code (Number):

#include <stdio.h>

int main() {

int n, rev=0, temp;

printf(“Enter number: “); scanf(“%d”,&n);

temp = n;

while(temp!=0) {

rev = rev*10 + temp%10;

temp/=10;

}

if(n==rev) printf(“Palindrome\n”);

else printf(“Not Palindrome\n”);

return 0;

}

Viva Questions:

  1. Difference between string and number palindrome.
  2. Can we use recursion for palindrome?
  3. Time complexity.
  4. Applications in algorithms.
  5. Optimization techniques.

 

Experiment 79

Title: Linear Search Using Pointers

Program Code:

#include <stdio.h>

int main() {

int arr[5]={10,20,30,40,50}, *ptr=arr, key, flag=0;

printf(“Enter element to search: “); scanf(“%d”,&key);

for(int i=0;i<5;i++)

if(*(ptr+i)==key) { printf(“Found at %d\n”,i+1); flag=1; break; }

if(flag==0) printf(“Not found\n”);

return 0;

}

Viva Questions:

  1. How pointers improve efficiency.
  2. Difference from array indexing.
  3. Can it be applied to strings?
  4. Applications in memory-sensitive programs.
  5. Time complexity.

 

Experiment 80

Title: Binary Search Using Pointers

Program Code:

#include <stdio.h>

int main() {

int arr[5]={10,20,30,40,50}, *ptr=arr, key, low=0, high=4, mid, flag=0;

printf(“Enter element to search: “); scanf(“%d”,&key);

while(low<=high){

mid=(low+high)/2;

if(*(ptr+mid)==key) { printf(“Found at %d\n”,mid+1); flag=1; break; }

else if(*(ptr+mid)<key) low=mid+1;

else high=mid-1;

}

if(flag==0) printf(“Not found\n”);

return 0;

}

Viva Questions:

  1. Difference between linear and binary search.
  2. Pointer arithmetic in search.
  3. Precondition for binary search.
  4. Recursive implementation.
  5. Time complexity.

 

Experiment 81

Title: Matrix Multiplication

Program Code:

#include <stdio.h>

int main() {

int a[2][2]={{1,2},{3,4}}, b[2][2]={{5,6},{7,8}}, c[2][2]={0};

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

for(int k=0;k<2;k++)

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

printf(“Result matrix:\n”);

for(int i=0;i<2;i++){ for(int j=0;j<2;j++) printf(“%d “,c[i][j]); printf(“\n”); }

return 0;

}

Viva Questions:

  1. Rules for matrix multiplication.
  2. Can we multiply non-square matrices?
  3. Memory storage in 2D arrays.
  4. Time complexity.
  5. Applications in graphics.

 

Experiment 82

Title: Transpose of Matrix

Program Code:

#include <stdio.h>

int main() {

int a[2][3]={{1,2,3},{4,5,6}}, t[3][2];

for(int i=0;i<2;i++)

for(int j=0;j<3;j++)

t[j][i]=a[i][j];

printf(“Transpose:\n”);

for(int i=0;i<3;i++){ for(int j=0;j<2;j++) printf(“%d “,t[i][j]); printf(“\n”); }

return 0;

}

Viva Questions:

  1. Difference between in-place and new matrix transpose.
  2. Applications in image processing.
  3. Memory allocation considerations.
  4. Difference for square and rectangular matrices.
  5. Can transpose be recursive?

 

Experiment 83

Title: Upper Triangle / Lower Triangle of Matrix

Program Code:

#include <stdio.h>

int main() {

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

printf(“Upper Triangle:\n”);

for(int i=0;i<3;i++){

for(int j=0;j<3;j++)

if(j>=i) printf(“%d “,a[i][j]); else printf(”   “);

printf(“\n”);

}

printf(“Lower Triangle:\n”);

for(int i=0;i<3;i++){

for(int j=0;j<3;j++)

if(j<=i) printf(“%d “,a[i][j]); else printf(”   “);

printf(“\n”);

}

return 0;

}

Viva Questions:

  1. Applications in numerical methods.
  2. Difference between upper and lower triangle.
  3. Storage optimization.
  4. Can we generalize to n×n?
  5. Importance in linear algebra.

 

Experiment 84

Title: String Palindrome Using Function

Program Code:

#include <stdio.h>

#include <string.h>

int isPalindrome(char str[]){

int n=strlen(str);

for(int i=0;i<n/2;i++) if(str[i]!=str[n-i-1]) return 0;

return 1;

}

int main(){

char str[50];

printf(“Enter string: “); gets(str);

if(isPalindrome(str)) printf(“Palindrome\n”);

else printf(“Not Palindrome\n”);

return 0;

}

Viva Questions:

  1. Difference between function and macro.
  2. Why return 0 or 1.
  3. Applications in string validation.
  4. Complexity analysis.
  5. Recursive vs iterative palindrome check.

 

Experiment 85

Title: Count Vowels and Consonants in String

Program Code:

#include <stdio.h>

#include <ctype.h>

#include <string.h>

int main(){

char str[50]; int vowels=0, consonants=0;

printf(“Enter string: “); gets(str);

for(int i=0;i<strlen(str);i++){

char ch = tolower(str[i]);

if(ch>=’a’ && ch<=’z’){

if(ch==’a’||ch==’e’||ch==’i’||ch==’o’||ch==’u’) vowels++;

else consonants++;

}

}

printf(“Vowels=%d, Consonants=%d\n”, vowels, consonants);

return 0;

}

Viva Questions:

  1. How to count digits and spaces.
  2. Difference between isalpha() and isdigit().
  3. Applications in text processing.
  4. Case sensitivity handling.
  5. Alternative methods.

 

Experiment 86

Title: Merge Two Arrays

Program Code:

#include <stdio.h>

int main(){

int a[3]={1,2,3}, b[3]={4,5,6}, c[6], k=0;

for(int i=0;i<3;i++) c[k++]=a[i];

for(int i=0;i<3;i++) c[k++]=b[i];

printf(“Merged array: “);

for(int i=0;i<6;i++) printf(“%d “,c[i]);

return 0;

}

Viva Questions:

  1. Difference between merge and concatenation.
  2. Applications in sorting.
  3. Time complexity.
  4. Can we merge arrays of different types?
  5. How to merge dynamically allocated arrays.

 

Experiment 87

Title: Find Largest and Smallest in Array

Program Code:

#include <stdio.h>

int main(){

int arr[5]={10,20,5,30,15}, max=arr[0], min=arr[0];

for(int i=1;i<5;i++){

if(arr[i]>max) max=arr[i];

if(arr[i]<min) min=arr[i];

}

printf(“Max=%d, Min=%d\n”, max, min);

return 0;

}

Viva Questions:

  1. Difference between linear and pointer method.
  2. Can we do in single pass?
  3. Applications in data analysis.
  4. Complexity analysis.
  5. Handling empty arrays.

 

Experiment 88

Title: Bubble Sort

Program Code:

#include <stdio.h>

int main(){

int arr[5]={5,3,8,1,2}, temp;

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

for(int j=0;j<4-i;j++)

if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; }

printf(“Sorted array: “);

for(int i=0;i<5;i++) printf(“%d “, arr[i]);

return 0;

}

Viva Questions:

  1. Compare bubble sort with selection sort.
  2. Complexity analysis.
  3. Best and worst case scenarios.
  4. How to optimize bubble sort.
  5. Applications.

 

Experiment 89

Title: Selection Sort

Program Code:

#include <stdio.h>

int main(){

int arr[5]={5,3,8,1,2}, min, temp;

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

min=i;

for(int j=i+1;j<5;j++) if(arr[j]<arr[min]) min=j;

temp=arr[i]; arr[i]=arr[min]; arr[min]=temp;

}

printf(“Sorted array: “);

for(int i=0;i<5;i++) printf(“%d “,arr[i]);

return 0;

}

Viva Questions:

  1. Difference between bubble and selection sort.
  2. Complexity analysis.
  3. Is selection sort stable?
  4. Applications in small datasets.
  5. Difference with insertion sort.

 

Experiment 90

Title: Insertion Sort

Program Code:

#include <stdio.h>

int main(){

int arr[5]={5,3,8,1,2}, key,j;

for(int i=1;i<5;i++){

key=arr[i]; j=i-1;

while(j>=0 && arr[j]>key){ arr[j+1]=arr[j]; j–; }

arr[j+1]=key;

}

printf(“Sorted array: “);

for(int i=0;i<5;i++) printf(“%d “,arr[i]);

return 0;

}

Viva Questions:

  1. Best and worst case scenarios.
  2. Stable sort explanation.
  3. Time complexity.
  4. Applications in online sorting.
  5. Difference from bubble sort.

 

Experiment 91

Title: Search Character in String

Program Code:

#include <stdio.h>

#include <string.h>

int main(){

char str[50]; char ch; int flag=0;

printf(“Enter string: “); gets(str);

printf(“Enter character to search: “); scanf(“%c”,&ch);

for(int i=0;i<strlen(str);i++)

if(str[i]==ch) { flag=1; break; }

if(flag) printf(“Character found\n”); else printf(“Not found\n”);

return 0;

}

Viva Questions:

  1. Difference between strchr and manual search.
  2. Applications in parsing.
  3. Case sensitivity.
  4. Complexity.
  5. Can we use pointers?

 

Experiment 92

Title: Reverse Array

Program Code:

#include <stdio.h>

int main(){

int arr[5]={1,2,3,4,5}, temp;

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

temp=arr[i]; arr[i]=arr[5-i-1]; arr[5-i-1]=temp;

}

printf(“Reversed array: “);

for(int i=0;i<5;i++) printf(“%d “,arr[i]);

return 0;

}

Viva Questions:

  1. Difference between in-place and new array reverse.
  2. Pointer implementation.
  3. Complexity.
  4. Applications.
  5. Can it be recursive?

 

Experiment 93

Title: Sum of Diagonal Elements of Matrix

Program Code:

#include <stdio.h>

int main(){

int mat[3][3]={{1,2,3},{4,5,6},{7,8,9}}, sum=0;

for(int i=0;i<3;i++) sum+=mat[i][i];

printf(“Sum of diagonal elements=%d\n”, sum);

return 0;

}

Viva Questions:

  1. Difference between main diagonal and secondary diagonal.
  2. Applications in linear algebra.
  3. Memory allocation.
  4. Complexity.
  5. Can it be generalized to n×n?

 

Experiment 94

Title: Upper and Lower Case Conversion

Program Code:

#include <stdio.h>

#include <ctype.h>

int main(){

char str[50];

printf(“Enter string: “); gets(str);

for(int i=0;str[i];i++){

if(islower(str[i])) str[i]=toupper(str[i]);

else if(isupper(str[i])) str[i]=tolower(str[i]);

}

printf(“Converted string: %s\n”, str);

return 0;

}

Viva Questions:

  1. Difference between toupper and manual conversion.
  2. Applications in text processing.
  3. Handling non-alphabetic characters.
  4. ASCII values usage.
  5. Case sensitivity issues.

 

Experiment 95

Title: Remove Duplicate Elements from Array

Program Code:

#include <stdio.h>

int main(){

int arr[7]={1,2,2,3,4,4,5}, n=7, k=0;

int res[7];

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

int flag=0;

for(int j=0;j<k;j++) if(arr[i]==res[j]) {flag=1; break;}

if(flag==0) res[k++]=arr[i];

}

printf(“Array after removing duplicates: “);

for(int i=0;i<k;i++) printf(“%d “,res[i]);

return 0;

}

Viva Questions:

  1. Time complexity.
  2. Alternative methods using sorting.
  3. Using pointers for optimization.
  4. Applications in data cleaning.
  5. Handling large datasets.

 

Experiment 96

Title: Merge Two Sorted Arrays

Program Code:

#include <stdio.h>

int main(){

int a[3]={1,3,5}, b[3]={2,4,6}, c[6], i=0,j=0,k=0;

while(i<3 && j<3){

if(a[i]<b[j]) c[k++]=a[i++];

else c[k++]=b[j++];

}

while(i<3) c[k++]=a[i++];

while(j<3) c[k++]=b[j++];

printf(“Merged sorted array: “);

for(i=0;i<6;i++) printf(“%d “,c[i]);

return 0;

}

Viva Questions:

  1. Difference from normal merge.
  2. Complexity analysis.
  3. Applications in merge sort.
  4. Can it handle arrays of different sizes?
  5. Pointer implementation.

 

Experiment 97

Title: Matrix Addition

Program Code:

#include <stdio.h>

int main(){

int a[2][2]={{1,2},{3,4}}, b[2][2]={{5,6},{7,8}}, c[2][2];

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

c[i][j]=a[i][j]+b[i][j];

printf(“Sum matrix:\n”);

for(int i=0;i<2;i++){ for(int j=0;j<2;j++) printf(“%d “,c[i][j]); printf(“\n”); }

return 0;

}

Viva Questions:

  1. Rules of matrix addition.
  2. Applications in scientific computing.
  3. Handling different sizes.
  4. Complexity.
  5. Memory allocation.

 

Experiment 98

Title: Matrix Subtraction

Program Code:

#include <stdio.h>

int main(){

int a[2][2]={{5,6},{7,8}}, b[2][2]={{1,2},{3,4}}, c[2][2];

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

c[i][j]=a[i][j]-b[i][j];

printf(“Difference matrix:\n”);

for(int i=0;i<2;i++){ for(int j=0;j<2;j++) printf(“%d “,c[i][j]); printf(“\n”); }

return 0;

}

Viva Questions:

  1. Difference from addition.
  2. Applications.
  3. Complexity.
  4. Can we subtract matrices of different sizes?
  5. Memory storage considerations.

 

Experiment 99

Title: String Concatenation Using Pointers

Program Code:

#include <stdio.h>

int main(){

char str1[50], str2[50], *p=str1;

printf(“Enter first string: “); gets(str1);

printf(“Enter second string: “); gets(str2);

while(*p) p++;

char *q=str2;

while(*q){ *p=*q; p++; q++; }

*p=’\0′;

printf(“Concatenated string: %s\n”, str1);

return 0;

}

Viva Questions:

  1. Difference between strcat and pointer method.
  2. Memory considerations.
  3. Applications in text processing.
  4. Can we concatenate dynamically allocated strings?
  5. Difference between array and pointer concatenation.

 

Experiment 100

Title: Student Record Management (Project)

Objective: Implement file-based CRUD operations for student data.

Program Code:

#include <stdio.h>

#include <string.h>

struct Student { int id; char name[20]; float marks; };

void addRecord(){ struct Student s; FILE *fp=fopen(“students.dat”,”ab”); printf(“ID Name Marks: “); scanf(“%d %s %f”,&s.id,s.name,&s.marks); fwrite(&s,sizeof(s),1,fp); fclose(fp); }

void displayRecords(){ struct Student s; FILE *fp=fopen(“students.dat”,”rb”); while(fread(&s,sizeof(s),1,fp)) printf(“%d %s %.2f\n”,s.id,s.name,s.marks); fclose(fp); }

int main(){ int choice; do{ printf(“1.Add 2.Display 3.Exit: “); scanf(“%d”,&choice); switch(choice){ case 1: addRecord(); break; case 2: displayRecords(); break; } }while(choice!=3); return 0; }

Viva Questions:

  1. Explain file handling for records.
  2. Difference between binary and text files in project.
  3. How to update or delete records.
  4. Can we use structures in file operations?
  5. Applications in real-world systems.

 

UNIT X – MINI PROJECTS (Examples)

(Experiments 101–110)

Experiment 101: Student Record Management System

Problem Definition:

Design a C program to maintain student records (Name, Roll No, Marks) allowing operations such as Add, Display, Search, and Exit.

Algorithm:

  1. Start
  2. Display menu: Add / Display / Search / Exit
  3. Perform operation using file handling (students.dat)
  4. Use structure for student data
  5. Repeat until Exit
  6. Stop

Flowchart (Text Representation):

[Start]

|

[Display Menu]

|

+–+–+–+–+

|Add|Disp|Search|Exit|

|      |      |

[File operations]

|

[Repeat until Exit]

|

[Stop]

C Code:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Student {

int roll;

char name[50];

float marks;

};

void addRecord() {

FILE *fp = fopen(“students.dat”, “ab”);

struct Student s;

printf(“Enter Roll, Name, Marks: “);

scanf(“%d %s %f”, &s.roll, s.name, &s.marks);

fwrite(&s, sizeof(s), 1, fp);

fclose(fp);

printf(“Record added successfully!\n”);

}

void displayRecords() {

FILE *fp = fopen(“students.dat”, “rb”);

struct Student s;

printf(“\n— Student Records —\n”);

while(fread(&s, sizeof(s), 1, fp))

printf(“%d %s %.2f\n”, s.roll, s.name, s.marks);

fclose(fp);

}

void searchRecord() {

FILE *fp = fopen(“students.dat”, “rb”);

struct Student s;

int roll, found = 0;

printf(“Enter roll number to search: “);

scanf(“%d”, &roll);

while(fread(&s, sizeof(s), 1, fp)) {

if(s.roll == roll) {

printf(“Found: %d %s %.2f\n”, s.roll, s.name, s.marks);

found = 1; break;

}

}

if(!found) printf(“Record not found.\n”);

fclose(fp);

}

int main() {

int choice;

while(1) {

printf(“\n1.Add 2.Display 3.Search 4.Exit\nEnter choice: “);

scanf(“%d”, &choice);

switch(choice) {

case 1: addRecord(); break;

case 2: displayRecords(); break;

case 3: searchRecord(); break;

case 4: exit(0);

default: printf(“Invalid choice\n”);

}

}

return 0;

}

Viva Questions:

  1. What is the advantage of using structures in files?
  2. Why binary files are preferred for record management?
  3. How to handle deletion in such systems?
  4. Difference between sequential and random file access.
  5. What happens if two students have same roll number?

 

Experiment 102: Library Management System

Problem Definition:

Create a system to manage books in a library, supporting Add Book, Display Books, and Search by Title.

Algorithm:

  1. Start
  2. Use structure Book with ID, title, author, and price
  3. Perform file-based Add, Display, Search
  4. Repeat menu until Exit

Flowchart:

Start → Menu → Add/Display/Search → Perform Operation → Repeat → Exit

C Code:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Book {

int id;

char title[50];

char author[50];

float price;

};

void addBook() {

FILE *fp = fopen(“library.dat”, “ab”);

struct Book b;

printf(“Enter ID, Title, Author, Price: “);

scanf(“%d %s %s %f”, &b.id, b.title, b.author, &b.price);

fwrite(&b, sizeof(b), 1, fp);

fclose(fp);

}

void displayBooks() {

FILE *fp = fopen(“library.dat”, “rb”);

struct Book b;

printf(“\n— Library Books —\n”);

while(fread(&b, sizeof(b), 1, fp))

printf(“%d %s %s %.2f\n”, b.id, b.title, b.author, b.price);

fclose(fp);

}

void searchBook() {

FILE *fp = fopen(“library.dat”, “rb”);

struct Book b; char title[50];

int found=0;

printf(“Enter title to search: “);

scanf(“%s”, title);

while(fread(&b, sizeof(b), 1, fp)) {

if(strcmp(b.title,title)==0) {

printf(“Found: %d %s %s %.2f\n”, b.id,b.title,b.author,b.price);

found=1; break;

}

}

if(!found) printf(“Book not found.\n”);

fclose(fp);

}

int main() {

int ch;

while(1) {

printf(“\n1.Add 2.Display 3.Search 4.Exit\nChoice: “);

scanf(“%d”,&ch);

switch(ch) {

case 1: addBook(); break;

case 2: displayBooks(); break;

case 3: searchBook(); break;

case 4: exit(0);

}

}

}

Viva Questions:

  1. What data structure is used to represent a book?
  2. Can file size grow indefinitely?
  3. How to delete a book record?
  4. What is the difference between binary and text data storage?
  5. What would you add to make this system more realistic?

 

 Experiment 103: Payroll Management System

Problem Definition:

Develop a payroll system to store and calculate employee salary based on basic pay, DA, and HRA.

Algorithm:

  1. Start
  2. Input employee details and compute total salary
  3. Store and display data using structures
  4. Repeat for multiple employees

C Code:

#include <stdio.h>

struct Employee {

int id;

char name[30];

float basic, hra, da, total;

};

int main() {

int n; printf(“Enter number of employees: “); scanf(“%d”,&n);

struct Employee e[n];

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

printf(“Enter ID, Name, Basic: “);

scanf(“%d %s %f”,&e[i].id,e[i].name,&e[i].basic);

e[i].hra = e[i].basic*0.2;

e[i].da = e[i].basic*0.5;

e[i].total = e[i].basic + e[i].hra + e[i].da;

}

printf(“\nID\tName\tTotal Salary\n”);

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

printf(“%d\t%s\t%.2f\n”, e[i].id,e[i].name,e[i].total);

return 0;

}

Viva Questions:

  1. What is structure array?
  2. How to save payroll to a file?
  3. Explain DA and HRA computation.
  4. What happens if salary components change?
  5. Can we dynamically allocate employee records?

 

Experiment 104: Billing System

Problem Definition:

Design a billing system in C that allows users to enter items with quantity and price, then calculates the total bill with tax and discount.

Algorithm:

  1. Start
  2. Input number of items
  3. For each item: enter name, quantity, price
  4. Calculate total amount = quantity × price
  5. Add GST (e.g., 18%)
  6. Apply discount if applicable
  7. Display final bill

Flowchart:

[Start]

|

[Input items]

|

[Compute total]

|

[Add GST & Discount]

|

[Display bill]

|

[Stop]

C Code:

#include <stdio.h>

struct Item {

char name[20];

int qty;

float price, total;

};

int main() {

int n; float grandTotal = 0;

printf(“Enter number of items: “);

scanf(“%d”, &n);

struct Item items[n];

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

printf(“Enter name, qty, price: “);

scanf(“%s %d %f”, items[i].name, &items[i].qty, &items[i].price);

items[i].total = items[i].qty * items[i].price;

grandTotal += items[i].total;

}

float gst = grandTotal * 0.18;

float discount = (grandTotal > 1000) ? grandTotal * 0.1 : 0;

float net = grandTotal + gst – discount;

printf(“\nItem\tQty\tPrice\tTotal\n”);

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

printf(“%s\t%d\t%.2f\t%.2f\n”, items[i].name, items[i].qty, items[i].price, items[i].total);

printf(“\nSubtotal = %.2f\nGST = %.2f\nDiscount = %.2f\nNet Total = %.2f\n”,

grandTotal, gst, discount, net);

return 0;

}

Viva Questions:

  1. What is the purpose of structures here?
  2. How would you add file storage for bills?
  3. How can this be modularized with functions?
  4. What are typical data validation checks?
  5. What is the difference between subtotal and net total?


 Experiment 105: Tic-Tac-Toe Game

Problem Definition:

Implement a 2-player Tic-Tac-Toe game using arrays and conditional logic.

Algorithm:

  1. Start
  2. Initialize 3×3 board with numbers 1–9
  3. Players take turns to mark X or O
  4. Check for win/draw after each turn
  5. Display board after every move
  6. Stop when win/draw detected

Flowchart:

[Start]

|

[Initialize board]

|

[Player Move]

|

[Check Win/Draw]

|

[Display Result]

|

[Stop]

C Code:

#include <stdio.h>

char board[3][3];

void initBoard() {

char c=’1′;

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

board[i][j]=c++;

}

void display() {

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++)

printf(” %c “, board[i][j]);

printf(“\n”);

}

}

int checkWin() {

for(int i=0;i<3;i++)

if(board[i][0]==board[i][1] && board[i][1]==board[i][2]) return 1;

for(int j=0;j<3;j++)

if(board[0][j]==board[1][j] && board[1][j]==board[2][j]) return 1;

if(board[0][0]==board[1][1] && board[1][1]==board[2][2]) return 1;

if(board[0][2]==board[1][1] && board[1][1]==board[2][0]) return 1;

return 0;

}

int main() {

int move, turn=0; char mark;

initBoard();

while(turn<9) {

display();

mark = (turn%2==0)?’X’:’O’;

printf(“Player %d (%c), enter position: “, (turn%2)+1, mark);

scanf(“%d”, &move);

int r=(move-1)/3, c=(move-1)%3;

if(board[r][c]==’X’||board[r][c]==’O’) { printf(“Invalid move\n”); continue; }

board[r][c]=mark;

if(checkWin()) { display(); printf(“Player %d wins!\n”,(turn%2)+1); return 0; }

turn++;

}

display();

printf(“It’s a draw!\n”);

return 0;

}

Viva Questions:

  1. What data structure is used for the board?
  2. How do you check for a win condition?
  3. How can you add AI logic?
  4. What is difference between 1D and 2D array here?
  5. How can this be extended for multiplayer online?

 

 Experiment 106: Simple Calculator with File Logs

Problem Definition:

Create a calculator that performs arithmetic operations and logs results to a text file.

Algorithm:

  1. Start
  2. Input two numbers and operator
  3. Perform the operation
  4. Write input and result to log file
  5. Repeat or exit

C Code:

#include <stdio.h>

int main() {

FILE *fp = fopen(“calc_log.txt”,”a”);

float a,b,result; char op;

printf(“Enter expression (a op b): “);

scanf(“%f %c %f”,&a,&op,&b);

switch(op){

case ‘+’: result=a+b; break;

case ‘-‘: result=a-b; break;

case ‘*’: result=a*b; break;

case ‘/’: result=b!=0?a/b:0; break;

default: printf(“Invalid operator\n”); return 0;

}

printf(“Result = %.2f\n”, result);

fprintf(fp,”%.2f %c %.2f = %.2f\n”, a,op,b,result);

fclose(fp);

return 0;

}

Viva Questions:

  1. What is file mode used for logging?
  2. How can you store a timestamp in log?
  3. Why append mode is used?
  4. What happens if file doesn’t exist?
  5. How can logs be encrypted?

 

Experiment 107: Banking System

Problem Definition:

Develop a banking system to store account data, support deposit, withdrawal, and balance inquiry.

Algorithm:

  1. Start
  2. Use structure Account (accno, name, balance)
  3. Menu for Deposit, Withdraw, Display, Exit
  4. File storage for persistence

C Code:

#include <stdio.h>

#include <stdlib.h>

struct Account {

int accno;

char name[30];

float balance;

};

void addAccount() {

FILE *fp=fopen(“bank.dat”,”ab”);

struct Account a;

printf(“Enter accno, name, balance: “);

scanf(“%d %s %f”,&a.accno,a.name,&a.balance);

fwrite(&a,sizeof(a),1,fp);

fclose(fp);

}

void displayAll() {

FILE *fp=fopen(“bank.dat”,”rb”);

struct Account a;

while(fread(&a,sizeof(a),1,fp))

printf(“%d %s %.2f\n”,a.accno,a.name,a.balance);

fclose(fp);

}

int main() {

int ch;

while(1) {

printf(“\n1.Add 2.Display 3.Exit\nChoice: “);

scanf(“%d”,&ch);

switch(ch) {

case 1: addAccount(); break;

case 2: displayAll(); break;

case 3: exit(0);

}

}

}

Viva Questions:

  1. How to ensure unique account numbers?
  2. What is difference between deposit and withdraw logic?
  3. Why binary file preferred here?
  4. How can password protection be added?
  5. How to calculate interest automatically?

 

Experiment 108: Hospital Management System

Problem Definition:

Maintain patient data like ID, Name, Disease, and Room No with Add, Display, and Search features.

C Code:

#include <stdio.h>

#include <string.h>

struct Patient {

int id;

char name[30], disease[30];

int room;

};

int main() {

struct Patient p[100];

int n; printf(“Enter number of patients: “); scanf(“%d”,&n);

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

printf(“Enter ID, Name, Disease, Room: “);

scanf(“%d %s %s %d”,&p[i].id,p[i].name,p[i].disease,&p[i].room);

}

printf(“\n— Patient List —\n”);

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

printf(“%d %s %s %d\n”,p[i].id,p[i].name,p[i].disease,p[i].room);

return 0;

}

Viva Questions:

  1. How to sort patients by room?
  2. How can we store medical history?
  3. Can we link this with billing system?
  4. What structure element stores disease?
  5. Can we use nested structures?

Experiment 109: Quiz Application

Problem Definition:

Design a simple quiz program with MCQs, scoring system, and final result display.

C Code:

#include <stdio.h>

int main() {

int score=0, ans;

printf(“1. C language is developed by?\n1. Bjarne 2. Dennis 3. James 4. Ritchie\n”);

scanf(“%d”,&ans); if(ans==2) score++;

printf(“2. Keyword to declare integer?\n1. int 2. float 3. char 4. long\n”);

scanf(“%d”,&ans); if(ans==1) score++;

printf(“3. Header for printf()?\n1. conio.h 2. stdio.h 3. math.h 4. string.h\n”);

scanf(“%d”,&ans); if(ans==2) score++;

printf(“Your score = %d/3\n”,score);

return 0;

}

Viva Questions:

  1. How can you randomize questions?
  2. How to store results in file?
  3. What data type for answers?
  4. How can this become a GUI quiz?
  5. What is difference between array-based and file-based quiz?

 

Experiment 110: Result Processing System

Problem Definition:

Calculate total and grade for multiple students based on marks in 3 subjects.

C Code:

#include <stdio.h>

struct Student {

int id;

char name[30];

float m1,m2,m3,total;

char grade;

};

char findGrade(float avg) {

if(avg>=90) return ‘A’;

else if(avg>=75) return ‘B’;

else if(avg>=60) return ‘C’;

else return ‘F’;

}

int main() {

int n;

printf(“Enter number of students: “);

scanf(“%d”,&n);

struct Student s[n];

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

printf(“Enter ID, Name, Marks(3): “);

scanf(“%d %s %f %f %f”,&s[i].id,s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);

s[i].total = s[i].m1 + s[i].m2 + s[i].m3;

s[i].grade = findGrade(s[i].total/3);

}

printf(“\nID\tName\tTotal\tGrade\n”);

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

printf(“%d\t%s\t%.2f\t%c\n”,s[i].id,s[i].name,s[i].total,s[i].grade);

return 0;

}

Viva Questions:

  1. What is structure nesting?
  2. How is grade computed?
  3. What happens for invalid input?
  4. How can data be saved to file?
  5. How to compute class average?

 

Answers

C Programming Viva Questions and Answers (Concise)

(All 10 Units – 100 Experiments)

UNIT I – C Programming Basics

  1. Who developed C language? → Dennis Ritchie, Bell Labs, 1972.
  2. Extension of a C program file? → .c
  3. What is #include <stdio.h>? → Preprocessor directive for standard input/output functions.
  4. What is a variable? → Named memory location to store data.
  5. What is a constant? → A fixed value that doesn’t change during execution.
  6. Define keyword. → Reserved word with predefined meaning in C.
  7. Define identifier. → Name given to variables, functions, or arrays.
  8. What is the role of main()? → Entry point of every C program.
  9. What is a data type? → Defines the type and size of variable data.
  10. Difference between = and ==? → = assigns; == compares.

UNIT II – Control Statements and Loops

  1. What is control statement? → Controls program flow.
  2. Types of control statements? → Decision-making, looping, and branching.
  3. What is if statement? → Executes code if condition is true.
  4. What is if–else? → Executes one block if true, another if false.
  5. Purpose of switch? → Multi-way decision control.
  6. What is a loop? → Executes statements repeatedly.
  7. Types of loops? → for, while, do–while.
  8. Difference between while and do–while? → while checks before; do–while after.
  9. What is break? → Exits from loop or switch.
  10. What is continue? → Skips rest of loop and continues next iteration.

UNIT III – Arrays and Strings

  1. What is an array? → Collection of similar data items.
  2. Types of arrays? → 1D, 2D, and multi-dimensional.
  3. Index of first array element? → 0.
  4. What is a string? → Array of characters ending with \0.
  5. Function to find string length? → strlen().
  6. Function to copy string? → strcpy().
  7. Function to compare strings? → strcmp().
  8. Function to concatenate strings? → strcat().
  9. What is character array? → Array storing characters.
  10. What is difference between gets() and scanf()? → gets() reads full line; scanf() stops at space.

UNIT IV – Functions and Recursion

  1. What is a function? → Block of code performing specific task.
  2. Types of functions? → Library and user-defined.
  3. What is function prototype? → Declaration of function before use.
  4. What is recursion? → Function calling itself.
  5. Advantage of functions? → Reusability and modularity.
  6. What is return statement? → Returns value from function.
  7. What is function call by value? → Passes copy of variable.
  8. What is function call by reference? → Passes variable address.
  9. Can main() return a value? → Yes, usually return 0;.
  10. What is scope of a variable? → Region where variable is accessible.

UNIT V – Pointers

  1. What is a pointer? → Variable that stores address of another variable.
  2. Symbol used for pointer declaration? → *
  3. Operator used to access address? → &
  4. What is NULL pointer? → Pointer that points to nothing (0).
  5. What is pointer to pointer? → Pointer storing address of another pointer.
  6. Can a pointer store address of different data type? → No.
  7. What is dynamic memory allocation? → Allocating memory at runtime.
  8. Functions for DMA? → malloc(), calloc(), realloc(), free().
  9. What is pointer arithmetic? → Incrementing/decrementing pointer to access next memory.
  10. What is difference between array and pointer? → Array fixed; pointer dynamic.

UNIT VI – Structures and Unions

  1. What is a structure? → Collection of different data types under one name.
  2. How to access structure members? → Using dot operator (.).
  3. What is a union? → Stores different data types in same memory location.
  4. Difference between structure and union? → Structure stores all members; union stores one at a time.
  5. What is typedef? → Used to give alias name to data type.
  6. What is nested structure? → Structure inside another structure.
  7. What is array of structures? → Collection of multiple structure variables.
  8. What is pointer to structure? → Pointer that stores address of structure variable.
  9. What is -> operator? → Access structure member through pointer.
  10. What is structure padding? → Extra memory added for alignment.

UNIT VII – File Handling

  1. What is file handling? → Process of storing data permanently on disk.
  2. Functions to open file? → fopen().
  3. Functions to close file? → fclose().
  4. Modes in fopen()? → “r”, “w”, “a”, “r+”, “w+”.
  5. Function to read character? → fgetc().
  6. Function to write character? → fputc().
  7. Function to read string? → fgets().
  8. Function to write string? → fputs().
  9. What is EOF? → End Of File indicator.
  10. Why use files? → To store data beyond program execution.

UNIT VIII – Dynamic Memory and Storage Classes

  1. What is dynamic memory allocation? → Allocating memory during runtime.
  2. Functions for DMA? → malloc(), calloc(), realloc(), free().
  3. Difference between malloc() and calloc()? → malloc allocates uninitialized memory; calloc initializes with zero.
  4. What is realloc()? → Resizes previously allocated memory.
  5. What is free()? → Releases allocated memory.
  6. What are storage classes? → Define scope and lifetime of variables.
  7. Types of storage classes? → auto, static, register, extern.
  8. What is auto variable? → Default local variable.
  9. What is static variable? → Retains value between function calls.
  10. What is extern variable? → Declared globally, accessible across files.

UNIT IX – Preprocessor and Command Line Arguments

  1. What is preprocessor? → Program that processes source code before compilation.
  2. What is #define? → Defines constant or macro.
  3. What is macro? → Name representing a code fragment.
  4. What is conditional compilation? → Compiles specific part based on condition.
  5. What is header file? → File containing function declarations.
  6. What is command line argument? → Passing values to main() during program execution.
  7. Syntax for CLA main function? → int main(int argc, char *argv[])
  8. What is argc? → Argument count.
  9. What is argv? → Argument vector (array of strings).
  10. Advantage of CLA? → Allows dynamic input from command line.

UNIT X – Mini Projects (Applications)

  1. What is a mini project? → Small application combining all C concepts.
  2. Purpose of project? → Integrate logic, data, and file handling.
  3. Examples of mini projects? → Student Record, Payroll, Quiz App.
  4. What is algorithm? → Step-by-step method to solve a problem.
  5. What is flowchart? → Diagrammatic representation of algorithm.
  6. What is module? → Independent part of a large program.
  7. What is debugging? → Process of finding and fixing errors.
  8. What is testing? → Ensuring program works as intended.
  9. Why use functions in projects? → For modularity and code reusability.
  10. Why documentation is important? → For maintenance and understanding by others.

 

C Programming Viva – Detailed Answers (All Units)

UNIT I – C Programming Basics

  1. Who developed C language?
    C was developed by Dennis Ritchie at Bell Labs in 1972 to build the UNIX operating system. It is a structured, middle-level programming language combining the features of high- and low-level languages.
  2. Extension of a C program file
    Every C source file is saved with the extension .c. For example: main.c. During compilation it produces object files with .obj or .o.
  3. Purpose of #include <stdio.h>
    The #include directive adds the contents of the header file before compilation. stdio.h provides declarations for input/output functions such as printf() and scanf().
  4. What is a variable?
    A variable is a named memory location used to store data that may change during program execution.
    Example: int age = 25;
  5. What is a constant?
    Constants are fixed values that cannot change during execution. They can be numeric, character, or symbolic (#define PI 3.14).
  6. Define keyword.
    Keywords are reserved words with predefined meaning and cannot be used as identifiers, e.g., int, return, if, for.
  7. Define identifier.
    An identifier is a user-defined name for variables, functions, or arrays. It must begin with a letter or underscore and is case-sensitive.
  8. Role of main()
    main() is the entry point of every C program where execution begins.
    Example:
  9. int main() {
  10.           printf(“Hello”);
  11.     return 0;
  12. }
  13. What is a data type?
    Data type tells the compiler what type and size of data the variable will hold. Examples: int, float, char, double.
  14. Difference between = and ==
    = is the assignment operator, used to assign a value.
    == is the comparison operator, used in conditions to test equality.

UNIT II – Control Statements and Loops

  1. What are control statements?
    Statements that control program flow according to conditions or repetitions. Categories: decision-making (if, switch) and looping (for, while).
  2. Types of control statements
    • Decision making – if, if-else, switch
    • Looping – for, while, do-while
    • Jumping – break, continue, goto, return
  3. Explain if statement
    Executes a block if condition is true:
  4. if (a > b) printf(“A is larger”);
  5. Explain if-else
    Provides two alternative paths:
  6. if (marks >= 40) printf(“Pass”);
  7. else printf(“Fail”);
  8. Purpose of switch statement
    Used for multi-way branching based on expression value:
  9. switch(choice) { case 1: …; break; }
  10. What is a loop?
    A structure that executes a block repeatedly until a condition fails.
  11. Types of loops
    for, while, do-while. for is definite; others can be indefinite.
  12. Difference between while and do-while
    while checks condition before loop body; do-while executes at least once.
  13. What is break?
    Exits immediately from the loop or switch block.
  14. What is continue?
    Skips remaining statements of current iteration and proceeds to next loop cycle.

UNIT III – Arrays and Strings

  1. What is an array?
    A contiguous collection of elements of same data type accessed via index.
    Example: int a[5];
  2. Types of arrays
    • 1D – linear data storage
    • 2D – matrix form
    • Multi-dimensional – higher order arrays
  3. Index of first element
    Always 0; the last index is n-1.
  4. What is a string?
    An array of characters terminated by null character ‘\0’.
  5. strlen() function
    Returns number of characters excluding null terminator.
  6. strcpy() function
    Copies one string to another: strcpy(dest, src);
  7. strcmp() function
    Compares two strings lexicographically and returns 0 if equal.
  8. strcat() function
    Appends one string to another: strcat(a, b);
  9. Character array
    Declared as char name[20]; and can hold text.
  10. Difference between gets() and scanf()
    gets() reads entire line including spaces; scanf() stops at space.

UNIT IV – Functions and Recursion

  1. What is a function?
    A reusable block performing a specific task to make code modular and readable.
  2. Types of functions
    • Library – predefined (printf())
    • User-defined – created by programmer
  3. Function prototype
    Declaration before main() specifying return type and parameters:
    int add(int, int);
  4. What is recursion?
    When a function calls itself until a base condition is met. Example: factorial.
  5. Advantages of functions
    Code reuse, modularity, easier debugging, reduced redundancy.
  6. Purpose of return
    Sends a value back to the calling function; ends function execution.
  7. Call by value
    Passes copy of argument; original remains unchanged.
  8. Call by reference
    Passes address; original variable can be modified.
  9. Can main() return value?
    Yes; returning 0 denotes successful execution.
  10. Scope of variable
    Defines visibility; may be local, global, block, or file scope.

UNIT V – Pointers

  1. Definition
    Pointer is a variable storing address of another variable.
  2. Symbol used
    * dereferences pointer; & obtains address.
  3. Example
  4. int x=10, *p=&x;
  5. printf(“%d”, *p);
  6. NULL pointer
    Points to nothing; declared as int *p=NULL;
  7. Pointer to pointer
    Stores address of another pointer: int **pp;
  8. Type safety
    Pointer type must match variable type.
  9. Dynamic memory allocation
    Runtime allocation using malloc(), calloc().
  10. DMA functions
    malloc(), calloc() allocate; realloc() resizes; free() releases.
  11. Pointer arithmetic
    Adding/subtracting integer to pointer moves it by element size.
  12. Array vs pointer
    Array name fixed; pointer variable can change its target dynamically.

UNIT VI – Structures and Unions

  1. Structure
    User-defined data type combining different data types.
  2. struct student { int id; char name[20]; };
  3. Accessing members
    student1.id, student1.name
  4. Union
    Like structure but shares single memory location for all members.
  5. Difference between structure and union
    Structure stores all members simultaneously; union only one at a time.
  6. typedef
    Creates alias for a data type: typedef struct student STU;
  7. Nested structure
    Structure inside another structure for hierarchical data.
  8. Array of structures
    Multiple structure variables stored in array:
    struct student s[10];
  9. Pointer to structure
    struct student *ptr = &s1;
  10. -> operator
    Access structure member through pointer (ptr->id).
  11. Structure padding
    Compiler adds unused bytes for proper alignment of data.

UNIT VII – File Handling

  1. Definition
    File handling enables reading/writing data on disk for permanent storage.
  2. Open file
    fopen(“data.txt”, “r”);
  3. Close file
    fclose(fp);
  4. Modes
    “r”, “w”, “a”, “r+”, “w+”, “a+” for read/write/append combinations.
  5. fgetc()
    Reads one character.
  6. fputc()
    Writes one character.
  7. fgets()
    Reads string until newline or EOF.
  8. fputs()
    Writes string to file.
  9. EOF
    End-of-File constant indicating reading is finished.
  10. Why use files?
    To preserve data beyond program execution for reports or databases.

UNIT VIII – Dynamic Memory and Storage Classes

  1. Dynamic allocation
    Memory allocated during execution instead of compile time.
  2. Functions used
    malloc(), calloc(), realloc(), free().
  3. malloc() vs calloc()
    malloc() allocates uninitialized memory; calloc() initializes with zeros.
  4. realloc()
    Changes the size of previously allocated block while preserving contents.
  5. free()
    Frees the allocated block to avoid memory leaks.
  6. Storage classes
    Define variable scope, lifetime, and visibility: auto, static, register, extern.
  7. auto
    Default for local variables; memory allocated on stack.
  8. static
    Retains value between function calls.
  9. register
    Suggests storing variable in CPU register for faster access.
  10. extern
    Used to access global variable defined in another file.

UNIT IX – Preprocessor and Command Line Arguments

  1. Preprocessor
    Program that processes source code before compilation; handles macros, includes, and conditionals.
  2. #define
    Defines symbolic constant or macro.
    Example: #define PI 3.14
  3. Macro
    Text replacement during preprocessing; can include parameters.
  4. Conditional compilation
    Using directives like #ifdef, #endif to compile selectively.
  5. Header file
    Contains function prototypes and macro definitions reused in programs.
  6. Command line argument
    Passing inputs through command line to main() rather than using scanf().
  7. Syntax
    int main(int argc, char *argv[])
  8. argc meaning
    Number of arguments including program name.
  9. argv meaning
    Array of character pointers listing arguments.
  10. Advantages
    Makes program flexible and automatable by external scripts or shells.

UNIT X – Mini Projects and Applications

  1. What is a mini project?
    A small-scale application combining multiple C concepts such as functions, arrays, structures, and files.
  2. Purpose
    To implement real-life logic and develop problem-solving skills.
  3. Examples
    Student Record, Library, Payroll, Quiz, Calculator, etc.
  4. Algorithm
    Step-by-step logical sequence to solve problem.
  5. Flowchart
    Graphical diagram using symbols like process, decision, and arrow to represent logic.
  6. Module
    Independent part of program handling specific functionality.
  7. Debugging
    Identifying and fixing syntax or logical errors.
  8. Testing
    Executing program with test cases to validate correctness.
  9. Why functions in projects?
    Promote modularity, reduce complexity, enable reuse.
  10. Importance of documentation
    Essential for future maintenance, readability, and collaboration.

 

Leave a Reply

Your email address will not be published. Required fields are marked *