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:
- Start program
- Write #include <stdio.h>
- Define main() function
- Use printf() to display “Hello World”
- 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:
- What is the purpose of #include <stdio.h>?
- What does return 0; signify?
- Can a C program have multiple main() functions?
- What is the difference between printf and scanf?
- 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:
- Start program
- Include stdio.h
- Define main()
- Declare variables
- Prompt user for input
- Read input using scanf()
- Display input using printf()
- 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:
- How does scanf work internally?
- What is the significance of & before the variable?
- Can we read multiple variables in one scanf statement?
- What happens if the input type does not match the format specifier?
- 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:
- Start
- Include stdio.h
- Declare two integer variables
- Input values from user
- Add numbers
- Display sum
- 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:
- List all arithmetic operators in C.
- What is operator precedence?
- How is % operator different from /?
- Can arithmetic operations be done on float types?
- 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:
- Start
- Include stdio.h
- Declare variables
- Input two numbers
- Perform subtraction, multiplication, division
- Display results
- 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:
- What is integer division?
- How does operator precedence work?
- Can you divide by zero in C?
- Difference between integer division and float division?
- 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:
- Start
- Input two numbers a and b
- Use temporary variable temp = a; a = b; b = temp;
- Display swapped values
- 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:
- Can swapping be done without a temporary variable?
- Explain XOR swap technique.
- Difference between swapping integers and swapping floats?
- Can we swap two numbers using pointers?
- 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:
- Start
- Input two numbers a and b
- If a > b, print a is larger
- Else, print b is larger
- 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:
- Difference between if and if-else statements.
- Can multiple conditions be checked using nested if?
- What happens if the condition is false?
- Explain logical operators in conditional statements.
- 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:
- Start
- Input three numbers a, b, c
- Compare a with b and c
- Print the largest number
- 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:
- How do logical AND (&&) and OR (||) operators work?
- Can we implement this without nested if?
- Difference between else if and multiple if statements.
- How to find the smallest number instead?
- 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:
- Start
- Input number num
- If num % 2 == 0, print “Even”
- Else, print “Odd”
- 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:
- What does % operator do?
- Can this program work for negative numbers?
- Difference between == and =?
- Can we check even/odd using bitwise operators?
- 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:
- Start
- Input year y
- If (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) then leap year
- Else, not leap year
- 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:
- Explain the rules for leap year.
- Why is year divisible by 100 not a leap year?
- Can a leap year be negative?
- How to modify program for multiple years?
- 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:
- Start
- Input two numbers a and b
- Input choice (1-add, 2-subtract, 3-multiply, 4-divide)
- Use switch-case to perform operation
- Display result
- 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:
- What is the purpose of break in switch-case?
- Can we use if-else instead of switch?
- What happens if break is omitted?
- How to extend calculator for modulo and power?
- 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:
- Start
- Input number num
- If num > 0, print “Positive”
- Else if num < 0, print “Negative”
- Else print “Zero”
- 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:
- What is multi-way selection?
- Difference between if-else and nested if?
- Can switch-case be used here?
- How does C evaluate conditional expressions?
- 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:
- Start
- Input three numbers a, b, c
- Compare a with b and c
- Print the largest number
- 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:
- Explain nested if vs multiple if-else.
- How does operator precedence affect logical expressions?
- Can ternary operator be used here?
- What is the difference between >= and >?
- 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:
- Start
- Input marks
- If marks ≥ 90, Grade = A
- Else if marks ≥ 80, Grade = B
- Else if marks ≥ 70, Grade = C
- Else Grade = F
- 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:
- What are decision-making statements?
- Difference between multiple if and if-else-if.
- Can switch-case be used here?
- How to handle invalid marks (<0 or >100)?
- 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:
- Start
- Input principal P, rate R, time T
- Choose option: 1-Calculate SI, 2-Display details
- Use switch-case
- 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:
- Difference between if-else and switch-case.
- Can switch handle float values?
- What happens if break is omitted?
- Can default case be omitted?
- 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:
- Start
- Input N
- For i = 1 to N, print i
- 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:
- Difference between for, while, and do-while.
- What happens if increment is missing?
- Can we write a for loop without initialization?
- Can i be float?
- 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:
Algorithm / Flowchart:
- Start
- Input integer n
- Initialize sum = 0
- For i = 1 to n, add i to sum
- Display sum
- 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:
- What is the difference between sum += i and sum = sum + i?
- Can we use while loop instead of for loop?
- What happens if n = 0 or negative?
- What is the time complexity of this loop?
- 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:
- Start
- Input number n
- Initialize fact = 1
- For i = 1 to n, multiply fact *= i
- Display fact
- 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:
- What is factorial used for?
- What data type is best for large factorials?
- Can factorial be computed recursively?
- What is overflow in factorial computation?
- 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:
- Start
- Input number n
- Initialize rev = 0
- While n > 0
- Extract rem = n % 10
- rev = rev * 10 + rem
- n = n / 10
- Display rev
- 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:
- What happens if number ends with zero?
- Can this logic be applied to negative numbers?
- Difference between integer division and floating division?
- How can we check if a number is palindrome using this?
- 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:
- Start
- Input number n
- Store temp = n
- Reverse number as in previous experiment
- If temp == rev, print palindrome
- Else not palindrome
- 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:
- What is a palindrome?
- Can strings also be palindromes?
- How can this be modified for strings?
- What is the use of temporary variable here?
- 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:
- Start
- Input N
- Initialize a=0, b=1
- Print first two numbers
- For i = 3 to N, compute c = a + b, print c, then update a=b, b=c
- 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:
- What is Fibonacci sequence?
- Difference between iterative and recursive approach?
- How to generate only even Fibonacci numbers?
- What happens if N = 1?
- 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:
- Start
- Define function add(a, b) returning sum
- Input two numbers
- Call function add(a,b)
- Display result
- 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:
- What are the advantages of functions?
- Difference between user-defined and library functions?
- Can a function return multiple values?
- What is the difference between call by value and call by reference?
- 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:
- Start
- Define function factorial(n)
- Input number n
- Call factorial(n)
- Display result
- 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:
- Difference between iterative and recursive factorial.
- Can we use global variables inside functions?
- What is function prototype?
- Can a function call itself?
- 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:
- Start
- Define function largest(a,b,c)
- Input three numbers
- Call largest(a,b,c)
- Display result
- 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:
- Can we return multiple values from a function?
- Difference between call by value and call by reference.
- Can a function call another function?
- What is the scope of variables inside a function?
- 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:
- Start
- Define factorial(n) recursively
- Input n
- Call factorial(n)
- Display result
- 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:
- Difference between recursion and iteration.
- What is base case and why is it necessary?
- Can recursion be memory-intensive?
- Explain stack overflow in recursion.
- 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:
- Start
- Define fib(n) recursively
- Input number of terms n
- Call fib(i) in loop for i = 0 to n-1
- Display result
- 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:
- Compare recursive and iterative Fibonacci.
- Explain time complexity of recursive Fibonacci.
- What is memoization?
- Can recursion be avoided?
- 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:
- Start
- Define function isPrime(n)
- Input n
- Call isPrime(n)
- Display result
- 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:
- What is a prime number?
- How to optimize prime check?
- Can recursion be used here?
- Difference between prime and composite numbers?
- 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:
- Start
- Input array of size n
- Define function sumArray(arr, n)
- Loop through array to sum elements
- Display sum
- 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:
- How are arrays passed to functions?
- Difference between arr[] and *arr in function argument.
- Can function modify array elements?
- What is array indexing?
- 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:
- Start
- Input array of size n
- Define function maxArray(arr, n)
- Loop to find maximum
- Display maximum
- 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:
- Difference between local and global max.
- Can we return index of maximum?
- How to modify function for 2D arrays?
- How to handle empty arrays?
- 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:
- Start
- Define sum(n) recursively
- Input n
- Call sum(n)
- Display result
- 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:
- Difference between iterative and recursive sum.
- Explain base case importance.
- Can negative numbers be handled?
- What is recursion depth?
- 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:
- Start
- Input array of size n
- Define function reverseArray(arr, n)
- Swap elements: arr[i] ↔ arr[n-i-1] for i = 0 to n/2
- Display reversed array
- 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:
- How are arrays passed to functions in C?
- Difference between pass by value and pass by reference for arrays?
- Can this function be used for strings?
- What is the time complexity?
- 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:
- Start
- Input size of array n
- Input array elements
- Display array elements
- 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:
- Difference between 1D and 2D arrays.
- Can arrays have variable size?
- How is memory allocated for arrays?
- Can array elements be float?
- 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:
- Start
- Input array elements
- Initialize sum = 0
- Loop through array, add elements to sum
- Calculate average = sum / n
- Display sum and average
- 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:
- What is the data type of average?
- Can average be integer type?
- Difference between sum of int and float arrays.
- What happens if array size is zero?
- 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:
- Start
- Input array size n and elements
- Initialize i=0, j=n-1
- Swap arr[i] and arr[j], increment i, decrement j
- Repeat until i<j
- Display reversed array
- 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:
- How to reverse array recursively?
- Difference between original and reversed array.
- Can this work for character arrays?
- Time complexity of array reversal.
- 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:
- Start
- Input array size n and elements
- Input key element
- Loop through array: if arr[i]==key, return i
- If not found, print “Not found”
- 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:
- Difference between linear and binary search.
- What is best, worst, and average case?
- Can linear search work for unsorted arrays?
- Time complexity of linear search.
- 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:
- Start
- Input sorted array
- Input key
- Initialize low=0, high=n-1
- While low ≤ high
- mid = (low+high)/2
- If arr[mid]==key, found
- Else if arr[mid]<key, low=mid+1
- Else, high=mid-1
- If not found, print “Not found”
- 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:
- Difference between linear and binary search.
- Why array must be sorted?
- Time complexity comparison.
- Can binary search be implemented recursively?
- 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:
- Start
- Input array size n and elements
- For i = 0 to n-2
- For j = 0 to n-i-2
- If arr[j] > arr[j+1], swap
- For j = 0 to n-i-2
- Display sorted array
- 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:
- What is the time complexity of bubble sort?
- How to optimize bubble sort?
- Difference between bubble sort and selection sort.
- Can it sort in descending order?
- 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:
- Start
- Input array size n and elements
- 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]
- Display sorted array
- 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:
- Difference between bubble and selection sort.
- Time complexity of selection sort.
- Can it sort in descending order?
- Number of swaps in worst case?
- 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:
- Start
- Input rows m and columns n
- Input array elements
- Display array elements
- 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:
- Difference between 1D and 2D arrays.
- How is memory allocated for 2D arrays?
- Can 2D arrays be passed to functions?
- Difference between row-major and column-major storage.
- 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:
- Start
- Input 2D array
- Loop through rows to compute row sum
- Loop through columns to compute column sum
- Display results
- 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:
- Difference between row sum and column sum.
- Can this be generalized for any m×n matrix?
- How to find diagonal sum?
- Applications of matrix sums.
- 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:
- Start
- Input two strings
- Compute length of first string
- Copy second string to another variable
- Concatenate two strings
- Display results
- 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:
- Difference between gets() and scanf().
- Explain strlen, strcpy, strcat.
- How to compare strings?
- What is null character \0?
- 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:
- Start
- Declare integer variable a
- Declare pointer int *ptr
- Assign ptr = &a
- Display address using ptr
- Display value using *ptr
- 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:
- What is a pointer?
- Difference between pointer and normal variable.
- What is NULL pointer?
- What happens if you dereference an uninitialized pointer?
- 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:
- Start
- Declare array of integers
- Assign pointer to array
- Perform pointer arithmetic to access array elements
- Display values
- 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:
- What is difference between ptr and &ptr?
- Can we subtract two pointers?
- How does pointer arithmetic depend on data type?
- Can pointer arithmetic be done with void pointers?
- 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:
- Start
- Declare variable a
- Declare pointer ptr = &a
- Declare double pointer pptr = &ptr
- Access value using *pptr
- 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:
- How many levels of pointers can we have?
- Difference between single and double pointers.
- Applications of pointer to pointer.
- How is memory accessed via double pointer?
- 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:
- Start
- Define function void modify(int *p)
- In main, declare a and pass &a to function
- Modify value using pointer
- Display modified value in main
- 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:
- Difference between call by value and call by reference.
- Can arrays be modified using pointers in function?
- What happens if pointer is NULL?
- Explain pointer dereferencing in function.
- 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:
- Start
- Input size n
- Allocate memory for n integers using malloc
- Input elements into allocated memory
- Display elements
- Free memory
- 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:
- Difference between malloc and calloc.
- Why free() is necessary?
- What happens if malloc fails?
- How to check for memory leaks?
- 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:
- Difference between malloc and calloc.
- What happens if calloc memory not freed?
- Applications of dynamic memory.
- Can we use calloc for strings?
- 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:
- Difference between realloc and malloc.
- Can realloc shrink memory?
- What happens if realloc fails?
- Applications of realloc.
- 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:
- Difference between arr and &arr
- How pointer arithmetic works for arrays
- Can we pass array pointer to function
- Difference between arr[i] and *(arr+i)
- 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:
- Difference between array of integers and array of pointers
- Applications of array of pointers
- Can we have pointer to array of pointers?
- How memory is stored?
- 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:
- Difference between char array and char pointer
- How to pass string to function using pointer
- Explain *ptr++ in context of strings
- Can we modify string using pointer
- 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:
- Difference between structure and array.
- Can structure members be of different data types?
- How to access structure members?
- Can structure be passed to function?
- 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:
- Difference between structure and array of structures.
- How to input multiple structure records.
- How memory is allocated for array of structures.
- Can array of structures be passed to a function?
- 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:
- What is nested structure?
- How to access members of nested structure?
- Can a structure have pointer to another structure?
- Difference between nested structure and array of structures.
- 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:
- Can we pass structure by reference?
- Difference between passing by value and pointer.
- Can a function return a structure?
- How is memory managed for structure in function?
- 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:
- Difference between . and -> operators.
- Can we have pointer to array of structures?
- How to dynamically allocate memory for structure?
- Difference between pointer to structure and array of structures.
- 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:
- Difference between structure and union.
- Memory allocation in union.
- Can multiple members store value simultaneously?
- Applications of unions.
- 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:
- Why union occupies less memory?
- Explain memory alignment in structures.
- Can structure size be optimized?
- Applications where memory optimization is critical.
- 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:
- What is bit field?
- How many bits are used for each member?
- Difference between normal member and bit field member.
- Applications of bit fields.
- 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:
- Difference between nested union and nested structure.
- How memory is allocated for nested union?
- Can we access all members simultaneously?
- Applications of nested unions.
- 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:
- Advantages of typedef.
- Difference between typedef structure and normal structure.
- Can we use typedef for union arrays?
- Applications of typedef in large programs.
- 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:
- Difference between text and binary files.
- Explain fopen modes (r, w, a, rb, wb).
- Why fclose() is necessary?
- What is file pointer?
- 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:
- Difference between fgetc() and fscanf().
- What is EOF?
- How to read line by line?
- Difference between binary and text read.
- 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:
- Difference between write and append mode.
- Can we append binary data?
- What happens if file does not exist in append mode?
- How to combine reading and appending?
- 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:
- How to copy binary file?
- Difference between fgetc/fputc and fread/fwrite.
- Can we overwrite destination file?
- How to check file size?
- 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:
- How to count punctuation marks?
- Difference between text file and binary file.
- Can word count be done using fscanf?
- Why add 1 to words and lines?
- 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:
- Explain argc and argv.
- How to handle errors in command line files?
- Difference between argv[0] and argv[1].
- Can this work for binary files?
- 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:
- Difference between SEEK_SET, SEEK_CUR, SEEK_END
- How to find current file position?
- Can we modify file using fseek?
- Applications of random access
- 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:
- Difference between text and binary file
- Explain fwrite parameters
- Can we write structures in binary file?
- How to read binary file?
- 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:
- Difference between fread and fscanf
- Why binary file reading is faster
- Can we read partial data
- How to determine file size
- 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:
- Difference between copying text and binary files
- Explain fread/fwrite
- Can we copy structures
- Importance of closing files
- 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:
- What is recursion?
- Difference between recursion and iteration.
- Base case importance.
- Stack memory usage in recursion.
- 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:
- Recursion efficiency.
- How to optimize with memoization.
- Difference between recursive and iterative Fibonacci.
- Stack overflow in recursion.
- 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:
- How recursion works with arrays.
- Difference between passing array and pointer.
- Maximum recursion depth.
- Tail recursion.
- 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:
- Difference between macro and function.
- When to use macros.
- Advantages and disadvantages.
- Can macros take multiple parameters?
- 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:
- Difference between compile-time and run-time.
- Explain conditional compilation.
- How to prevent multiple inclusions.
- Difference between #include<> and #include””.
- 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:
- Difference between argc and argv.
- Can we pass integers via command line?
- Applications of command line arguments.
- Difference between argv[0] and argv[1].
- 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:
- Difference between array and pointer for strings.
- Can we reverse string recursively?
- How strlen works internally.
- Difference between gets() and fgets().
- 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:
- Difference between string and number palindrome.
- Can we use recursion for palindrome?
- Time complexity.
- Applications in algorithms.
- 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:
- How pointers improve efficiency.
- Difference from array indexing.
- Can it be applied to strings?
- Applications in memory-sensitive programs.
- 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:
- Difference between linear and binary search.
- Pointer arithmetic in search.
- Precondition for binary search.
- Recursive implementation.
- 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:
- Rules for matrix multiplication.
- Can we multiply non-square matrices?
- Memory storage in 2D arrays.
- Time complexity.
- 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:
- Difference between in-place and new matrix transpose.
- Applications in image processing.
- Memory allocation considerations.
- Difference for square and rectangular matrices.
- 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:
- Applications in numerical methods.
- Difference between upper and lower triangle.
- Storage optimization.
- Can we generalize to n×n?
- 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:
- Difference between function and macro.
- Why return 0 or 1.
- Applications in string validation.
- Complexity analysis.
- 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:
- How to count digits and spaces.
- Difference between isalpha() and isdigit().
- Applications in text processing.
- Case sensitivity handling.
- 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:
- Difference between merge and concatenation.
- Applications in sorting.
- Time complexity.
- Can we merge arrays of different types?
- 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:
- Difference between linear and pointer method.
- Can we do in single pass?
- Applications in data analysis.
- Complexity analysis.
- 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:
- Compare bubble sort with selection sort.
- Complexity analysis.
- Best and worst case scenarios.
- How to optimize bubble sort.
- 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:
- Difference between bubble and selection sort.
- Complexity analysis.
- Is selection sort stable?
- Applications in small datasets.
- 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:
- Best and worst case scenarios.
- Stable sort explanation.
- Time complexity.
- Applications in online sorting.
- 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:
- Difference between strchr and manual search.
- Applications in parsing.
- Case sensitivity.
- Complexity.
- 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:
- Difference between in-place and new array reverse.
- Pointer implementation.
- Complexity.
- Applications.
- 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:
- Difference between main diagonal and secondary diagonal.
- Applications in linear algebra.
- Memory allocation.
- Complexity.
- 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:
- Difference between toupper and manual conversion.
- Applications in text processing.
- Handling non-alphabetic characters.
- ASCII values usage.
- 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:
- Time complexity.
- Alternative methods using sorting.
- Using pointers for optimization.
- Applications in data cleaning.
- 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:
- Difference from normal merge.
- Complexity analysis.
- Applications in merge sort.
- Can it handle arrays of different sizes?
- 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:
- Rules of matrix addition.
- Applications in scientific computing.
- Handling different sizes.
- Complexity.
- 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:
- Difference from addition.
- Applications.
- Complexity.
- Can we subtract matrices of different sizes?
- 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:
- Difference between strcat and pointer method.
- Memory considerations.
- Applications in text processing.
- Can we concatenate dynamically allocated strings?
- 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:
- Explain file handling for records.
- Difference between binary and text files in project.
- How to update or delete records.
- Can we use structures in file operations?
- 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:
- Start
- Display menu: Add / Display / Search / Exit
- Perform operation using file handling (students.dat)
- Use structure for student data
- Repeat until Exit
- 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:
- What is the advantage of using structures in files?
- Why binary files are preferred for record management?
- How to handle deletion in such systems?
- Difference between sequential and random file access.
- 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:
- Start
- Use structure Book with ID, title, author, and price
- Perform file-based Add, Display, Search
- 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:
- What data structure is used to represent a book?
- Can file size grow indefinitely?
- How to delete a book record?
- What is the difference between binary and text data storage?
- 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:
- Start
- Input employee details and compute total salary
- Store and display data using structures
- 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:
- What is structure array?
- How to save payroll to a file?
- Explain DA and HRA computation.
- What happens if salary components change?
- 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:
- Start
- Input number of items
- For each item: enter name, quantity, price
- Calculate total amount = quantity × price
- Add GST (e.g., 18%)
- Apply discount if applicable
- 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:
- What is the purpose of structures here?
- How would you add file storage for bills?
- How can this be modularized with functions?
- What are typical data validation checks?
- 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:
- Start
- Initialize 3×3 board with numbers 1–9
- Players take turns to mark X or O
- Check for win/draw after each turn
- Display board after every move
- 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:
- What data structure is used for the board?
- How do you check for a win condition?
- How can you add AI logic?
- What is difference between 1D and 2D array here?
- 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:
- Start
- Input two numbers and operator
- Perform the operation
- Write input and result to log file
- 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:
- What is file mode used for logging?
- How can you store a timestamp in log?
- Why append mode is used?
- What happens if file doesn’t exist?
- 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:
- Start
- Use structure Account (accno, name, balance)
- Menu for Deposit, Withdraw, Display, Exit
- 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:
- How to ensure unique account numbers?
- What is difference between deposit and withdraw logic?
- Why binary file preferred here?
- How can password protection be added?
- 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:
- How to sort patients by room?
- How can we store medical history?
- Can we link this with billing system?
- What structure element stores disease?
- 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:
- How can you randomize questions?
- How to store results in file?
- What data type for answers?
- How can this become a GUI quiz?
- 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:
- What is structure nesting?
- How is grade computed?
- What happens for invalid input?
- How can data be saved to file?
- How to compute class average?
Answers
C Programming Viva Questions and Answers (Concise)
(All 10 Units – 100 Experiments)
UNIT I – C Programming Basics
- Who developed C language? → Dennis Ritchie, Bell Labs, 1972.
- Extension of a C program file? → .c
- What is #include <stdio.h>? → Preprocessor directive for standard input/output functions.
- What is a variable? → Named memory location to store data.
- What is a constant? → A fixed value that doesn’t change during execution.
- Define keyword. → Reserved word with predefined meaning in C.
- Define identifier. → Name given to variables, functions, or arrays.
- What is the role of main()? → Entry point of every C program.
- What is a data type? → Defines the type and size of variable data.
- Difference between = and ==? → = assigns; == compares.
UNIT II – Control Statements and Loops
- What is control statement? → Controls program flow.
- Types of control statements? → Decision-making, looping, and branching.
- What is if statement? → Executes code if condition is true.
- What is if–else? → Executes one block if true, another if false.
- Purpose of switch? → Multi-way decision control.
- What is a loop? → Executes statements repeatedly.
- Types of loops? → for, while, do–while.
- Difference between while and do–while? → while checks before; do–while after.
- What is break? → Exits from loop or switch.
- What is continue? → Skips rest of loop and continues next iteration.
UNIT III – Arrays and Strings
- What is an array? → Collection of similar data items.
- Types of arrays? → 1D, 2D, and multi-dimensional.
- Index of first array element? → 0.
- What is a string? → Array of characters ending with \0.
- Function to find string length? → strlen().
- Function to copy string? → strcpy().
- Function to compare strings? → strcmp().
- Function to concatenate strings? → strcat().
- What is character array? → Array storing characters.
- What is difference between gets() and scanf()? → gets() reads full line; scanf() stops at space.
UNIT IV – Functions and Recursion
- What is a function? → Block of code performing specific task.
- Types of functions? → Library and user-defined.
- What is function prototype? → Declaration of function before use.
- What is recursion? → Function calling itself.
- Advantage of functions? → Reusability and modularity.
- What is return statement? → Returns value from function.
- What is function call by value? → Passes copy of variable.
- What is function call by reference? → Passes variable address.
- Can main() return a value? → Yes, usually return 0;.
- What is scope of a variable? → Region where variable is accessible.
UNIT V – Pointers
- What is a pointer? → Variable that stores address of another variable.
- Symbol used for pointer declaration? → *
- Operator used to access address? → &
- What is NULL pointer? → Pointer that points to nothing (0).
- What is pointer to pointer? → Pointer storing address of another pointer.
- Can a pointer store address of different data type? → No.
- What is dynamic memory allocation? → Allocating memory at runtime.
- Functions for DMA? → malloc(), calloc(), realloc(), free().
- What is pointer arithmetic? → Incrementing/decrementing pointer to access next memory.
- What is difference between array and pointer? → Array fixed; pointer dynamic.
UNIT VI – Structures and Unions
- What is a structure? → Collection of different data types under one name.
- How to access structure members? → Using dot operator (.).
- What is a union? → Stores different data types in same memory location.
- Difference between structure and union? → Structure stores all members; union stores one at a time.
- What is typedef? → Used to give alias name to data type.
- What is nested structure? → Structure inside another structure.
- What is array of structures? → Collection of multiple structure variables.
- What is pointer to structure? → Pointer that stores address of structure variable.
- What is -> operator? → Access structure member through pointer.
- What is structure padding? → Extra memory added for alignment.
UNIT VII – File Handling
- What is file handling? → Process of storing data permanently on disk.
- Functions to open file? → fopen().
- Functions to close file? → fclose().
- Modes in fopen()? → “r”, “w”, “a”, “r+”, “w+”.
- Function to read character? → fgetc().
- Function to write character? → fputc().
- Function to read string? → fgets().
- Function to write string? → fputs().
- What is EOF? → End Of File indicator.
- Why use files? → To store data beyond program execution.
UNIT VIII – Dynamic Memory and Storage Classes
- What is dynamic memory allocation? → Allocating memory during runtime.
- Functions for DMA? → malloc(), calloc(), realloc(), free().
- Difference between malloc() and calloc()? → malloc allocates uninitialized memory; calloc initializes with zero.
- What is realloc()? → Resizes previously allocated memory.
- What is free()? → Releases allocated memory.
- What are storage classes? → Define scope and lifetime of variables.
- Types of storage classes? → auto, static, register, extern.
- What is auto variable? → Default local variable.
- What is static variable? → Retains value between function calls.
- What is extern variable? → Declared globally, accessible across files.
UNIT IX – Preprocessor and Command Line Arguments
- What is preprocessor? → Program that processes source code before compilation.
- What is #define? → Defines constant or macro.
- What is macro? → Name representing a code fragment.
- What is conditional compilation? → Compiles specific part based on condition.
- What is header file? → File containing function declarations.
- What is command line argument? → Passing values to main() during program execution.
- Syntax for CLA main function? → int main(int argc, char *argv[])
- What is argc? → Argument count.
- What is argv? → Argument vector (array of strings).
- Advantage of CLA? → Allows dynamic input from command line.
UNIT X – Mini Projects (Applications)
- What is a mini project? → Small application combining all C concepts.
- Purpose of project? → Integrate logic, data, and file handling.
- Examples of mini projects? → Student Record, Payroll, Quiz App.
- What is algorithm? → Step-by-step method to solve a problem.
- What is flowchart? → Diagrammatic representation of algorithm.
- What is module? → Independent part of a large program.
- What is debugging? → Process of finding and fixing errors.
- What is testing? → Ensuring program works as intended.
- Why use functions in projects? → For modularity and code reusability.
- Why documentation is important? → For maintenance and understanding by others.
C Programming Viva – Detailed Answers (All Units)
UNIT I – C Programming Basics
- 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. - 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. - 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(). - 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; - What is a constant?
Constants are fixed values that cannot change during execution. They can be numeric, character, or symbolic (#define PI 3.14). - Define keyword.
Keywords are reserved words with predefined meaning and cannot be used as identifiers, e.g., int, return, if, for. - 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. - Role of main()
main() is the entry point of every C program where execution begins.
Example: - int main() {
- printf(“Hello”);
- return 0;
- }
- 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. - 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
- What are control statements?
Statements that control program flow according to conditions or repetitions. Categories: decision-making (if, switch) and looping (for, while). - Types of control statements
- Decision making – if, if-else, switch
- Looping – for, while, do-while
- Jumping – break, continue, goto, return
- Explain if statement
Executes a block if condition is true: - if (a > b) printf(“A is larger”);
- Explain if-else
Provides two alternative paths: - if (marks >= 40) printf(“Pass”);
- else printf(“Fail”);
- Purpose of switch statement
Used for multi-way branching based on expression value: - switch(choice) { case 1: …; break; }
- What is a loop?
A structure that executes a block repeatedly until a condition fails. - Types of loops
for, while, do-while. for is definite; others can be indefinite. - Difference between while and do-while
while checks condition before loop body; do-while executes at least once. - What is break?
Exits immediately from the loop or switch block. - What is continue?
Skips remaining statements of current iteration and proceeds to next loop cycle.
UNIT III – Arrays and Strings
- What is an array?
A contiguous collection of elements of same data type accessed via index.
Example: int a[5]; - Types of arrays
- 1D – linear data storage
- 2D – matrix form
- Multi-dimensional – higher order arrays
- Index of first element
Always 0; the last index is n-1. - What is a string?
An array of characters terminated by null character ‘\0’. - strlen() function
Returns number of characters excluding null terminator. - strcpy() function
Copies one string to another: strcpy(dest, src); - strcmp() function
Compares two strings lexicographically and returns 0 if equal. - strcat() function
Appends one string to another: strcat(a, b); - Character array
Declared as char name[20]; and can hold text. - Difference between gets() and scanf()
gets() reads entire line including spaces; scanf() stops at space.
UNIT IV – Functions and Recursion
- What is a function?
A reusable block performing a specific task to make code modular and readable. - Types of functions
- Library – predefined (printf())
- User-defined – created by programmer
- Function prototype
Declaration before main() specifying return type and parameters:
int add(int, int); - What is recursion?
When a function calls itself until a base condition is met. Example: factorial. - Advantages of functions
Code reuse, modularity, easier debugging, reduced redundancy. - Purpose of return
Sends a value back to the calling function; ends function execution. - Call by value
Passes copy of argument; original remains unchanged. - Call by reference
Passes address; original variable can be modified. - Can main() return value?
Yes; returning 0 denotes successful execution. - Scope of variable
Defines visibility; may be local, global, block, or file scope.
UNIT V – Pointers
- Definition
Pointer is a variable storing address of another variable. - Symbol used
* dereferences pointer; & obtains address. - Example
- int x=10, *p=&x;
- printf(“%d”, *p);
- NULL pointer
Points to nothing; declared as int *p=NULL; - Pointer to pointer
Stores address of another pointer: int **pp; - Type safety
Pointer type must match variable type. - Dynamic memory allocation
Runtime allocation using malloc(), calloc(). - DMA functions
malloc(), calloc() allocate; realloc() resizes; free() releases. - Pointer arithmetic
Adding/subtracting integer to pointer moves it by element size. - Array vs pointer
Array name fixed; pointer variable can change its target dynamically.
UNIT VI – Structures and Unions
- Structure
User-defined data type combining different data types. - struct student { int id; char name[20]; };
- Accessing members
student1.id, student1.name - Union
Like structure but shares single memory location for all members. - Difference between structure and union
Structure stores all members simultaneously; union only one at a time. - typedef
Creates alias for a data type: typedef struct student STU; - Nested structure
Structure inside another structure for hierarchical data. - Array of structures
Multiple structure variables stored in array:
struct student s[10]; - Pointer to structure
struct student *ptr = &s1; - -> operator
Access structure member through pointer (ptr->id). - Structure padding
Compiler adds unused bytes for proper alignment of data.
UNIT VII – File Handling
- Definition
File handling enables reading/writing data on disk for permanent storage. - Open file
fopen(“data.txt”, “r”); - Close file
fclose(fp); - Modes
“r”, “w”, “a”, “r+”, “w+”, “a+” for read/write/append combinations. - fgetc()
Reads one character. - fputc()
Writes one character. - fgets()
Reads string until newline or EOF. - fputs()
Writes string to file. - EOF
End-of-File constant indicating reading is finished. - Why use files?
To preserve data beyond program execution for reports or databases.
UNIT VIII – Dynamic Memory and Storage Classes
- Dynamic allocation
Memory allocated during execution instead of compile time. - Functions used
malloc(), calloc(), realloc(), free(). - malloc() vs calloc()
malloc() allocates uninitialized memory; calloc() initializes with zeros. - realloc()
Changes the size of previously allocated block while preserving contents. - free()
Frees the allocated block to avoid memory leaks. - Storage classes
Define variable scope, lifetime, and visibility: auto, static, register, extern. - auto
Default for local variables; memory allocated on stack. - static
Retains value between function calls. - register
Suggests storing variable in CPU register for faster access. - extern
Used to access global variable defined in another file.
UNIT IX – Preprocessor and Command Line Arguments
- Preprocessor
Program that processes source code before compilation; handles macros, includes, and conditionals. - #define
Defines symbolic constant or macro.
Example: #define PI 3.14 - Macro
Text replacement during preprocessing; can include parameters. - Conditional compilation
Using directives like #ifdef, #endif to compile selectively. - Header file
Contains function prototypes and macro definitions reused in programs. - Command line argument
Passing inputs through command line to main() rather than using scanf(). - Syntax
int main(int argc, char *argv[]) - argc meaning
Number of arguments including program name. - argv meaning
Array of character pointers listing arguments. - Advantages
Makes program flexible and automatable by external scripts or shells.
UNIT X – Mini Projects and Applications
- What is a mini project?
A small-scale application combining multiple C concepts such as functions, arrays, structures, and files. - Purpose
To implement real-life logic and develop problem-solving skills. - Examples
Student Record, Library, Payroll, Quiz, Calculator, etc. - Algorithm
Step-by-step logical sequence to solve problem. - Flowchart
Graphical diagram using symbols like process, decision, and arrow to represent logic. - Module
Independent part of program handling specific functionality. - Debugging
Identifying and fixing syntax or logical errors. - Testing
Executing program with test cases to validate correctness. - Why functions in projects?
Promote modularity, reduce complexity, enable reuse. - Importance of documentation
Essential for future maintenance, readability, and collaboration.