📚 About the Lab Exam
In the practical exam, you'll be asked to write, compile, and run C programs on a computer. You must understand each program completely — the logic, syntax, and be able to explain the output. Below are the most important programs you need to master, with line-by-line explanations.
💻 Prime Number Check
A prime number is a number greater than 1 that is divisible only by 1 and itself. Examples: 2, 3, 5, 7, 11, 13, 17...
Logic: Check if the number is divisible by any number from 2 to n/2. If yes, it's NOT prime. If none divide it evenly, it IS prime.
#include <stdio.h>
int main() {
int n, i, isPrime = 1; // isPrime flag: 1 = assume prime initially
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0; // 0 and 1 are NOT prime
} else {
for (i = 2; i <= n / 2; i++) { // Check divisibility from 2 to n/2
if (n % i == 0) { // If remainder is 0, it's divisible
isPrime = 0; // So it's NOT prime
break; // No need to check further
}
}
}
if (isPrime)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
return 0;
}
Enter a number: 7
7 is a prime number.
Enter a number: 10
10 is not a prime number. (because 10%2==0)
💻 Generate Fibonacci Series
The Fibonacci series: each number is the sum of the two before it. Starts with 0 and 1.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
#include <stdio.h>
int main() {
int n, i;
int a = 0, b = 1, next; // First two terms
printf("How many terms? ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; i++) {
printf("%d ", a); // Print current term
next = a + b; // Calculate next term
a = b; // Shift: a takes b's value
b = next; // b takes the new sum
}
printf("\n");
return 0;
}
How many terms? 8
Fibonacci Series: 0 1 1 2 3 5 8 13
💻 Factorial (Recursive)
Factorial: n! = n × (n-1) × (n-2) × ... × 1. Example: 5! = 5×4×3×2×1 = 120. Also: 0! = 1 (by definition).
#include <stdio.h>
// Recursive function
int factorial(int n) {
if (n == 0 || n == 1) // BASE CASE: stops recursion
return 1;
return n * factorial(n - 1); // RECURSIVE CASE: calls itself with n-1
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}
factorial(4) = 4 × factorial(3)
factorial(3) = 3 × factorial(2)
factorial(2) = 2 × factorial(1)
factorial(1) = 1 (base case!)
= 2 × 1 = 2
= 3 × 2 = 6
= 4 × 6 = 24
💻 String Reversal
#include <stdio.h>
#include <string.h>
int main() {
char str[100], reversed[100];
int len, i, j;
printf("Enter a string: ");
gets(str); // Read string (including spaces)
len = strlen(str); // Get length of string
// Copy characters in reverse order
j = 0;
for (i = len - 1; i >= 0; i--) {
reversed[j] = str[i]; // Last char goes first
j++;
}
reversed[j] = '\0'; // Must add null terminator!
printf("Reversed: %s\n", reversed);
return 0;
}
Enter a string: Hello World
Reversed: dlroW olleH
💻 Palindrome Check (Number)
A palindrome reads the same forward and backward. Examples: 121, 1331, 12321. Not palindromes: 123, 456.
#include <stdio.h>
int main() {
int num, original, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
original = num; // Save original because we'll modify num
while (num != 0) {
remainder = num % 10; // Extract last digit
reversed = reversed * 10 + remainder; // Build reversed number
num = num / 10; // Remove last digit
}
if (original == reversed)
printf("%d is a palindrome.\n", original);
else
printf("%d is not a palindrome.\n", original);
return 0;
}
Step 1: remainder=1, reversed=0*10+1=1, num=12
Step 2: remainder=2, reversed=1*10+2=12, num=1
Step 3: remainder=1, reversed=12*10+1=121, num=0
original(121) == reversed(121) → Palindrome!
💻 Bubble Sort
Bubble Sort repeatedly compares adjacent elements and swaps them if they're in the wrong order. The largest element "bubbles" to the end after each pass.
#include <stdio.h>
int main() {
int arr[100], n, i, j, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
// Bubble Sort - n-1 passes
for (i = 0; i < n - 1; i++) { // Outer: number of passes
for (j = 0; j < n - 1 - i; j++) { // Inner: comparisons per pass
if (arr[j] > arr[j + 1]) { // Compare adjacent elements
temp = arr[j]; // SWAP them
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Pass 1: [3,5,8,1,2] → [3,5,8,1,2] → [3,5,1,8,2] → [3,5,1,2,8]
Pass 2: [3,5,1,2,8] → [3,1,5,2,8] → [3,1,2,5,8]
Pass 3: [1,3,2,5,8] → [1,2,3,5,8]
Pass 4: [1,2,3,5,8] ✔ Sorted!
💻 Adding Two Matrices
Add corresponding elements from two matrices of the same size: C[i][j] = A[i][j] + B[i][j]
#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int rows, cols, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
printf("Enter Matrix A:\n");
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
scanf("%d", &a[i][j]);
printf("Enter Matrix B:\n");
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
scanf("%d", &b[i][j]);
// Add corresponding elements
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("Sum Matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%d\t", sum[i][j]);
printf("\n");
}
return 0;
}
💻 Linear Search
Linear Search checks each element one by one from start to end until the target is found or the array is exhausted.
#include <stdio.h>
int main() {
int arr[100], n, key, i, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter element to search: ");
scanf("%d", &key);
for (i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element %d found at position %d (index %d).\n", key, i+1, i);
found = 1;
break;
}
}
if (!found)
printf("Element %d not found in the array.\n", key);
return 0;
}
💻 Pointer-Based Swap
Demonstrates call by reference using pointers, where the function actually changes the original variables.
#include <stdio.h>
void swap(int *a, int *b) { // Receives ADDRESSES
int temp = *a; // *a = value at address a
*a = *b; // Value at a = value at b
*b = temp; // Value at b = old value of a
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y); // Pass ADDRESSES using &
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Why this works: We pass memory addresses. The function modifies the actual memory locations, not copies.
💻 Check Armstrong Number
An Armstrong number (narcissistic number) is a number where the sum of its digits each raised to the power of the number of digits equals the number itself.
Examples: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✔
370 = 3³ + 7³ + 0³ = 27 + 343 + 0 = 370 ✔
#include <stdio.h>
#include <math.h>
int main() {
int num, original, remainder, sum = 0, digits = 0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
// Count number of digits
int temp = num;
while (temp != 0) {
digits++;
temp /= 10;
}
// Calculate sum of digits^(number of digits)
temp = num;
while (temp != 0) {
remainder = temp % 10;
sum += (int)pow(remainder, digits); // pow() needs math.h
temp /= 10;
}
if (sum == original)
printf("%d is an Armstrong number.\n", original);
else
printf("%d is not an Armstrong number.\n", original);
return 0;
}
💻 Writing to and Reading from a File
#include <stdio.h>
int main() {
FILE *fp;
char name[50];
int age;
// === WRITE TO FILE ===
fp = fopen("student.txt", "w"); // Open for writing
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Enter name: ");
gets(name);
printf("Enter age: ");
scanf("%d", &age);
fprintf(fp, "Name: %s\n", name); // Write to file
fprintf(fp, "Age: %d\n", age);
fclose(fp); // Close file
printf("Data written to student.txt\n\n");
// === READ FROM FILE ===
fp = fopen("student.txt", "r"); // Open for reading
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char line[100];
printf("Contents of student.txt:\n");
while (fgets(line, 100, fp) != NULL) { // Read line by line
printf("%s", line); // Print each line
}
fclose(fp);
return 0;
}
Enter name: Sajid Khan
Enter age: 20
Data written to student.txt
Contents of student.txt:
Name: Sajid Khan
Age: 20
💻 Using Structures to Store Student Data
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int roll;
float marks[3]; // Marks in 3 subjects
float percentage;
};
int main() {
struct Student s;
float total = 0;
printf("Enter Name: ");
gets(s.name);
printf("Enter Roll Number: ");
scanf("%d", &s.roll);
printf("Enter marks in 3 subjects:\n");
for (int i = 0; i < 3; i++) {
printf("Subject %d: ", i + 1);
scanf("%f", &s.marks[i]);
total += s.marks[i];
}
s.percentage = total / 3.0;
printf("\n--- Student Record ---\n");
printf("Name: %s\n", s.name);
printf("Roll: %d\n", s.roll);
printf("Marks: %.1f, %.1f, %.1f\n", s.marks[0], s.marks[1], s.marks[2]);
printf("Percentage: %.2f%%\n", s.percentage);
if (s.percentage >= 60)
printf("Result: FIRST DIVISION\n");
else if (s.percentage >= 45)
printf("Result: SECOND DIVISION\n");
else if (s.percentage >= 33)
printf("Result: THIRD DIVISION\n");
else
printf("Result: FAIL\n");
return 0;
}
💻 Common Star Patterns
Right Triangle:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
/* Output:
*
* *
* * *
* * * *
* * * * *
*/
Pyramid (center-aligned):
int n = 5;
for (int i = 1; i <= n; i++) {
// Print spaces for alignment
for (int j = 1; j <= n - i; j++)
printf(" ");
// Print stars
for (int j = 1; j <= 2 * i - 1; j++)
printf("*");
printf("\n");
}
/* Output:
*
***
*****
*******
*********
*/
Inverted Triangle:
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
/* Output:
* * * * *
* * * *
* * *
* *
*
*/
Number Pattern:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
/* Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
📚 Important Tips for the Practical Exam
- Always include headers: <stdio.h> for printf/scanf, <string.h> for string functions, <math.h> for math functions, <stdlib.h> for dynamic memory
- Every statement ends with semicolon (;) — forgetting this is the #1 beginner error
- Curly braces { } must match — every opening brace needs a closing brace
- Use %d for int, %f for float, %c for char, %s for string in printf and scanf
- scanf needs & for all types EXCEPT strings: scanf("%d", &n) but scanf("%s", name) (no &)
- Array indices start from 0, not 1. An array of size 5 has indices 0,1,2,3,4
- Test your code with edge cases: 0, negative numbers, very large numbers, empty strings
- Comment your code: Viva examiners appreciate well-commented programs
- Practice dry runs: Trace through the code with specific input values on paper
- Common compilation errors: missing semicolons, undeclared variables, wrong format specifiers, mismatched parentheses/braces