← Return to Learning Hub
C Programming 2025-26

Practical File
PGDCA-105

Complete C Programming practicals with algorithms, flowcharts, code & sample outputs — Session 2025-26

47
Programs
6
Sections
50
Total Marks
3hrs
Duration

📋 Marks Distribution

Component Marks
Programme 1 (with flowchart & algorithm) 10
Programme 2 (with flowchart & algorithm) 10
Programme 3 (with flowchart & algorithm) 10
Viva-Voice 10
Practical Copy + Internal Record 10
Total 50
⌨️

Section 1: Input & Output, Formatting

1 program
P–01 Declare variables of all C data types, take user input, print with alignment (left, right, width 10). Real numbers with 2 decimal places.
  1. START
  2. Declare variables: int i, float f, double d, char c, long l, short s
  3. INPUT values for each variable from user
  4. PRINT int with %-10d (left) and %10d (right)
  5. PRINT float with %-10.2f and %10.2f
  6. PRINT double with %-10.2lf and %10.2lf
  7. PRINT char with %-10c and %10c
  8. PRINT long with %-10ld and %10ld
  9. PRINT short with %-10hd and %10hd
  10. STOP
START Declare all data types INPUT all variables Print left-aligned (%-10...) each value Print right-aligned (%10...) each value Real numbers: 2 decimal places (%.2f / %.2lf) STOP
/* Program 1: All data types with formatting */
/* Author: [Your Name] | PGDCA-105 */
#include <stdio.h>

int main() {
    /* Declare all basic C data types */
    int i;
    float f;
    double d;
    char c;
    long l;
    short s;

    /* Input section */
    printf("Enter an integer: ");  scanf("%d", &i);
    printf("Enter a float: ");    scanf("%f", &f);
    printf("Enter a double: ");   scanf("%lf", &d);
    printf("Enter a char: ");     scanf(" %c", &c);
    printf("Enter a long: ");     scanf("%ld", &l);
    printf("Enter a short: ");    scanf("%hd", &s);

    /* Print with column width 10, left aligned */
    printf("\n--- LEFT ALIGNED (width 10) ---\n");
    printf("int    : %-10d\n", i);
    printf("float  : %-10.2f\n", f);
    printf("double : %-10.2lf\n", d);
    printf("char   : %-10c\n", c);
    printf("long   : %-10ld\n", l);
    printf("short  : %-10hd\n", s);

    /* Print with column width 10, right aligned */
    printf("\n--- RIGHT ALIGNED (width 10) ---\n");
    printf("int    : %10d\n", i);
    printf("float  : %10.2f\n", f);
    printf("double : %10.2lf\n", d);
    printf("char   : %10c\n", c);
    printf("long   : %10ld\n", l);
    printf("short  : %10hd\n", s);
    return 0;
}
Enter an integer: 42
Enter a float: 3.14
Enter a double: 2.71828
Enter a char: A
Enter a long: 123456789
Enter a short: 100
 
--- LEFT ALIGNED (width 10) ---
int : 42
float : 3.14
double : 2.72
char : A
long : 123456789
short : 100
 
--- RIGHT ALIGNED (width 10) ---
int : 42
float : 3.14
double : 2.72
char : A
long : 123456789
short : 100
🔄

Section 2: Loops & Decisions

Programs 2–8
P–02 Print all combinations of 1, 2, 3.
  1. START
  2. Use three nested loops: i, j, k from 1 to 3
  3. FOR i = 1 to 3
  4.   FOR j = 1 to 3
  5.     FOR k = 1 to 3
  6.       IF i ≠ j AND j ≠ k AND i ≠ k
  7.         PRINT i, j, k
  8.       END IF
  9.     END FOR k
  10.   END FOR j
  11. END FOR i
  12. STOP
START i=1, j=1, k=1 i≤3 && j≤3 && k≤3? No→END Yes i≠j && j≠k && i≠k? Yes PRINT i, j, k k++; if k>3 j++; if j>3 i++ STOP
/* Program 2: All combinations of 1 2 3 */
#include <stdio.h>

int main() {
    int i, j, k, count = 0;
    printf("All combinations of 1 2 3:\n");
    /* Three nested loops for each position */
    for (i = 1; i <= 3; i++) {
        for (j = 1; j <= 3; j++) {
            for (k = 1; k <= 3; k++) {
                /* Ensure all three are distinct */
                if (i != j && j != k && i != k) {
                    printf("%d %d %d\n", i, j, k);
                    count++;
                }
            }
        }
    }
    printf("Total combinations: %d\n", count);
    return 0;
}
All combinations of 1 2 3:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Total combinations: 6
P–03 Generate patterns: (a) descending stars, (b) numbered triangle, (c) pyramid stars, (d) number pyramid.
  1. START
  2. /* Pattern A: Descending Stars */
  3. FOR i = 5 downto 1: print (6-i) stars, newline
  4. /* Pattern B: Numbered Triangle */
  5. FOR i = 1 to 4: print numbers 1 to (i*(i+1)/2)
  6. /* Pattern C: Star Pyramid */
  7. FOR i = 1 to 5: print (5-i) spaces, then (2*i-1) stars
  8. /* Pattern D: Number Pyramid */
  9. FOR i = 1 to 4: print spaces, then i..1..i
  10. STOP
START i = 5 (outer row counter) i >= 1 ? Yes PRINT i stars, newline k++; if k>3 j++; if j>3 i++ No→END STOP
/* Program 3: Pattern Generation */
#include <stdio.h>

int main() {
    int i, j, n = 5, num;

    /* Pattern (a): Descending star triangle */
    printf("Pattern A:\n");
    for (i = n; i >= 1; i--) {
        for (j = 1; j <= i; j++)
            printf("* ");
        printf("\n");
    }

    /* Pattern (b): Number staircase */
    printf("\nPattern B:\n");
    num = 1;
    for (i = 1; i <= 4; i++) {
        for (j = 1; j <= i * 2 - 1; j++)
            printf("%d ", num++);
        printf("\n");
    }

    /* Pattern (c): Star pyramid (centered) */
    printf("\nPattern C:\n");
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= n - i; j++) printf(" ");
        for (j = 1; j <= 2 * i - 1; j++) printf("*");
        printf("\n");
    }

    /* Pattern (d): Number pyramid with mirror */
    printf("\nPattern D:\n");
    for (i = 1; i <= 4; i++) {
        for (j = 4; j > i; j--) printf(" ");
        for (j = i; j >= 1; j--) printf("%d ", j);
        for (j = 2; j <= i; j++) printf("%d ", j);
        printf("\n");
    }
    return 0;
}
Pattern A:
* * * * *
* * * *
* * *
* *
*
 
Pattern B:
1
2 3
4 5 6
7 8 9 10
 
Pattern C:
*
***
*****
*******
*********
 
Pattern D:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
P–04 Menu-driven pattern program using switch: 11=for loop, 12=while loop, 13=do-while, 21=second pattern using for, etc.
  1. START
  2. INPUT choice (11, 12, 13, 21, 22, 23...)
  3. SWITCH choice
  4.   CASE 11: Print Pattern 1 using for loop
  5.   CASE 12: Print Pattern 1 using while loop
  6.   CASE 13: Print Pattern 1 using do-while loop
  7.   CASE 21: Print Pattern 2 using for loop
  8.   DEFAULT: Invalid choice
  9. END SWITCH
  10. STOP
START INPUT choice SWITCH choice 11 for loop Pat1 12 while loop Pat1 21 for loop Pat2 STOP
/* Program 4: Menu-driven pattern generator */
#include <stdio.h>

void pattern1_for() {
    int i, j;
    /* Descending stars using for */
    for (i = 5; i >= 1; i--) {
        for (j = 1; j <= i; j++) printf("* ");
        printf("\n");
    }
}
void pattern1_while() {
    int i = 5, j;
    /* Descending stars using while */
    while (i >= 1) {
        j = 1;
        while (j <= i) { printf("* "); j++; }
        printf("\n"); i--;
    }
}
void pattern1_dowhile() {
    int i = 5, j;
    /* Descending stars using do-while */
    do {
        j = 1;
        do { printf("* "); j++; } while (j <= i);
        printf("\n"); i--;
    } while (i >= 1);
}
void pattern2_for() {
    int i, j;
    /* Ascending stars using for */
    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= i; j++) printf("* ");
        printf("\n");
    }
}
int main() {
    int choice;
    printf("11=Pat1/for 12=Pat1/while 13=Pat1/dowhile 21=Pat2/for: ");
    scanf("%d", &choice);
    switch (choice) {
        case 11: pattern1_for(); break;
        case 12: pattern1_while(); break;
        case 13: pattern1_dowhile(); break;
        case 21: pattern2_for(); break;
        default: printf("Invalid choice!\n");
    }
    return 0;
}
11=Pat1/for 12=Pat1/while 13=Pat1/dowhile 21=Pat2/for: 11
* * * * *
* * * *
* * *
* *
*
P–05 Display numbers 1 to 10 in octal, decimal, and hexadecimal.
  1. START
  2. Print header: Decimal | Octal | Hexadecimal
  3. FOR i = 1 to 10
  4.   PRINT i with %d (decimal), %o (octal), %x (hex)
  5. END FOR
  6. STOP
START PRINT header row i = 1 i <= 10? Yes PRINT i,%d,%o,%x i = i + 1 No→END STOP
/* Program 5: Numbers in Octal, Decimal, Hexadecimal */
#include <stdio.h>

int main() {
    int i;
    /* Print table header */
    printf("%-12s %-12s %-12s\n", "Decimal", "Octal", "Hexadecimal");
    printf("------------------------------------\n");
    /* Loop 1 to 10 */
    for (i = 1; i <= 10; i++) {
        printf("%-12d %-12o %-12x\n", i, i, i);
    }
    return 0;
}
Decimal Octal Hexadecimal
------------------------------------
1 1 1
2 2 2
8 10 8
9 11 9
10 12 a
P–06 Convert a number between any two number systems (user specifies input base and output base).
  1. START
  2. INPUT fromBase (2/8/10/16), number as string, toBase
  3. Convert number from fromBase to decimal (intermediate)
  4.   FOR each digit: decimal = decimal * fromBase + digit_value
  5. Convert decimal to toBase
  6.   WHILE decimal > 0: remainder = decimal % toBase; build result
  7. PRINT result in toBase
  8. STOP
START INPUT fromBase, num, toBase Convert num to decimal (using fromBase) Convert decimal to toBase (repeated division) PRINT result STOP
/* Program 6: Number System Conversion */
#include <stdio.h>
#include <string.h>
#include <math.h>

/* Convert any base string to decimal */
long toDecimal(char *num, int base) {
    long dec = 0;
    int len = strlen(num);
    for (int i = 0; i < len; i++) {
        int d = (num[i] >= '0' && num[i] <= '9') ?
                  num[i] - '0' : num[i] - 'A' + 10;
        dec += d * (long)pow(base, len - i - 1);
    }
    return dec;
}
/* Convert decimal to any base */
void fromDecimal(long dec, int base) {
    char res[64]; int idx = 0;
    if (dec == 0) { printf("0"); return; }
    while (dec > 0) {
        int r = dec % base;
        res[idx++] = (r < 10) ? r + '0' : r - 10 + 'A';
        dec /= base;
    }
    for (int i = idx - 1; i >= 0; i--) printf("%c", res[i]);
}
int main() {
    char num[64];
    int fromBase, toBase;
    printf("Enter source base (2/8/10/16): "); scanf("%d", &fromBase);
    printf("Enter number: ");              scanf("%s", num);
    printf("Enter target base (2/8/10/16): "); scanf("%d", &toBase);
    long dec = toDecimal(num, fromBase);
    printf("Result (base %d): ", toBase);
    fromDecimal(dec, toBase);
    printf("\n");
    return 0;
}
Enter source base (2/8/10/16): 10
Enter number: 255
Enter target base (2/8/10/16): 16
Result (base 16): FF
P–07 Menu-driven: factorial, Fibonacci, sin series, exponential series, prime numbers, leap year using switch/loops/conditional.
  1. START
  2. INPUT choice (a/b/c/d/e/f)
  3. SWITCH choice
  4.  CASE a: Factorial: result=1; FOR i=1 to n: result*=i
  5.  CASE b: Fibonacci: a=0,b=1; PRINT; FOR n-2 times: c=a+b; a=b; b=c
  6.  CASE c: Sin series: sin(x) = x - x³/3! + x⁵/5! - ...
  7.  CASE d: Exp series: e^x = 1 + x + x²/2! + x³/3! + ...
  8.  CASE e: Primes: check divisibility for each num
  9.  CASE f: Leap year: (y%4==0 && y%100!=0) || y%400==0
  10. STOP
START INPUT choice & n SWITCH Factorial Fibonacci Sin/Exp Prime/Leap STOP
/* Program 7: Mathematical series menu */
#include <stdio.h>
#include <math.h>

int main() {
    int choice, n, i, isPrime;
    double x, term, sum, num1, num2, temp;
    long fact;

    printf("a)Factorial b)Fibonacci c)Sin d)Exp e)Primes f)LeapYear: ");
    scanf(" %c", (char*)&choice);

    switch(choice) {
        case 'a': /* Factorial */
            printf("Enter n: "); scanf("%d", &n);
            fact = 1;
            for(i = 1; i <= n; i++) fact *= i;
            printf("%d! = %ld\n", n, fact); break;
        case 'b': /* Fibonacci */
            printf("Enter n: "); scanf("%d", &n);
            num1 = 0; num2 = 1;
            printf("Fibonacci: 0 1 "); sum = 1;
            for(i = 2; i < n; i++) {
                temp = num1 + num2; printf("%.0f ", temp);
                sum += temp; num1 = num2; num2 = temp;
            }
            printf("\nSum = %.0f\n", sum); break;
        case 'c': /* Sin series */
            printf("Enter x(radians) and n terms: "); scanf("%lf %d", &x, &n);
            sum = 0; term = x; fact = 1;
            for(i = 1; i <= n; i++) {
                sum += term;
                term = -term * x * x / ((2*i) * (2*i+1));
            }
            printf("sin(%.2f) = %.6f\n", x, sum); break;
        case 'd': /* Exponential e^x */
            printf("Enter x and n terms: "); scanf("%lf %d", &x, &n);
            sum = 1; term = 1;
            for(i = 1; i <= n; i++) { term *= x/i; sum += term; }
            printf("e^%.2f = %.6f\n", x, sum); break;
        case 'e': /* Primes up to n */
            printf("Enter n: "); scanf("%d", &n);
            printf("Primes: ");
            for(i = 2; i <= n; i++) {
                isPrime = 1;
                for(int j = 2; j * j <= i; j++) if(i%j==0) { isPrime=0; break; }
                if(isPrime) printf("%d ", i);
            }
            printf("\n"); break;
        case 'f': /* Leap year */
            printf("Enter year: "); scanf("%d", &n);
            ((n%4==0 && n%100!=0) || n%400==0) ?
                printf("%d is a Leap Year\n", n) :
                printf("%d is NOT a Leap Year\n", n);
            break;
        default: printf("Invalid choice\n");
    }
    return 0;
}
a)Factorial b)Fibonacci c)Sin d)Exp e)Primes f)LeapYear: b
Enter n: 8
Fibonacci: 0 1 1 2 3 5 8 13
Sum = 33
P–08 Same as Program 7 but use library functions (pow, sin, exp, etc.).
  1. START
  2. Same menu as P7, but use <math.h> library functions
  3. For Factorial: use tgamma(n+1)
  4. For Sin series: use sin(x) directly
  5. For Exp: use exp(x) directly
  6. For prime: use sqrt(n) for optimization
  7. STOP
START INPUT choice & values Call math.h library functions: sin(), exp(), sqrt(), tgamma() PRINT result STOP
/* Program 8: Using library functions */
#include <stdio.h>
#include <math.h>

int main() {
    int choice, n;
    double x;
    printf("a)Factorial b)Sin c)Exp d)Primes e)LeapYear: ");
    scanf(" %c", (char*)&choice);

    switch(choice) {
        case 'a': /* Factorial using tgamma (n! = tgamma(n+1)) */
            printf("Enter n: "); scanf("%d", &n);
            printf("%d! = %.0f\n", n, tgamma(n + 1)); break;
        case 'b': /* sin() from math.h */
            printf("Enter x (radians): "); scanf("%lf", &x);
            printf("sin(%.4f) = %.6f\n", x, sin(x)); break;
        case 'c': /* exp() from math.h */
            printf("Enter x: "); scanf("%lf", &x);
            printf("e^%.4f = %.6f\n", x, exp(x)); break;
        case 'd': /* Primes with sqrt optimization */
            printf("Enter n: "); scanf("%d", &n);
            printf("Primes up to %d: ", n);
            for(int i=2; i<=n; i++) {
                int p=1;
                for(int j=2; j<=(int)sqrt(i); j++) if(i%j==0){p=0;break;}
                if(p) printf("%d ",i);
            }
            printf("\n"); break;
        case 'e':
            printf("Enter year: "); scanf("%d", &n);
            printf("%d is%s a leap year\n", n, ((n%4==0&&n%100!=0)||n%400==0)?"":" NOT");
            break;
        default: printf("Invalid\n");
    }
    return 0;
}
a)Factorial b)Sin c)Exp d)Primes e)LeapYear: c
Enter x: 2
e^2.0000 = 7.389056
📦

Section 3: Arrays

Programs 9–13
P–09 String operations without library: reverse, count chars, copy, palindrome, vowels/consonants/punctuation, sort alphabets.
  1. START
  2. INPUT choice (a-f), string
  3. CASE a – Reverse: i=0, j=len-1; WHILE i<j swap s[i],s[j]
  4. CASE b – Count: count=0; WHILE s[i]!='\0' count++
  5. CASE c – Copy: FOR each char: dest[i]=src[i]; dest[i]='\0'
  6. CASE d – Palindrome: reverse copy; compare char by char
  7. CASE e – Vowels/Consonants: check each char against aeiou
  8. CASE f – Sort: bubble sort on char array
  9. STOP
START INPUT choice, string s[] SWITCH(choice) Reverse Count Palindrome Sort STOP
/* Program 9: String operations WITHOUT library */
#include <stdio.h>

int mylen(char s[]) { int i=0; while(s[i]) i++; return i; }

int main() {
    char s[100], dest[100], rev[100];
    int ch, i, j, len, vowels=0, cons=0, punc=0;
    printf("a)Rev b)Count c)Copy d)Palindrome e)Vowels f)Sort: ");
    scanf(" %c", (char*)&ch);
    printf("Enter string: "); scanf(" %[^\n]", s);
    len = mylen(s);

    switch(ch) {
        case 'a': /* Reverse */
            i=0; j=len-1;
            while(i<j){ char t=s[i]; s[i]=s[j]; s[j]=t; i++; j--; }
            printf("Reversed: %s\n", s); break;
        case 'b': /* Count characters */
            printf("Length: %d\n", len); break;
        case 'c': /* Copy string */
            for(i=0; i<=len; i++) dest[i]=s[i];
            printf("Copied: %s\n", dest); break;
        case 'd': /* Palindrome */
            for(i=0; i<len; i++) rev[i]=s[len-1-i]; rev[len]='\0';
            i=0; while(i<len && s[i]==rev[i]) i++;
            printf("%s %s palindrome\n", s, i==len?"IS":"is NOT"); break;
        case 'e': /* Count vowels, consonants, punctuation */
            for(i=0; i<len; i++) {
                char c = s[i]|32; /* lowercase */
                if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') vowels++;
                else if(c>='a' && c<='z') cons++;
                else if(s[i]!=' ') punc++;
            }
            printf("Vowels:%d Consonants:%d Punct:%d\n", vowels, cons, punc); break;
        case 'f': /* Sort alphabets (bubble sort) */
            for(i=0; i<len-1; i++)
                for(j=0; j<len-i-1; j++)
                    if(s[j]>s[j+1]){ char t=s[j]; s[j]=s[j+1]; s[j+1]=t; }
            printf("Sorted: %s\n", s); break;
        default: printf("Invalid\n");
    }
    return 0;
}
a)Rev b)Count c)Copy d)Palindrome e)Vowels f)Sort: d
Enter string: madam
madam IS palindrome
P–10 Integer array: sort elements, linear search, binary search using switch/if-else/loop.
  1. START
  2. INPUT n, array a[n]
  3. CASE Sort: Bubble Sort – FOR i=0 to n-2: FOR j=0 to n-i-2: IF a[j]>a[j+1] swap
  4. CASE Linear Search: FOR each element IF a[i]==key: found
  5. CASE Binary Search: Sort first; low=0, high=n-1
  6.   WHILE low <= high: mid=(low+high)/2
  7.     IF a[mid]==key: found; ELIF a[mid]<key: low=mid+1; ELSE high=mid-1
  8. STOP
START INPUT n, array a[] Choice? Bubble Sort Linear Search Binary Search STOP
/* Program 10: Array Sort and Search */
#include <stdio.h>

/* Bubble sort */
void bubbleSort(int a[], int n) {
    for(int i=0; i<n-1; i++)
        for(int j=0; j<n-i-1; j++)
            if(a[j]>a[j+1]){ int t=a[j]; a[j]=a[j+1]; a[j+1]=t; }
}
/* Linear search */
int linearSearch(int a[], int n, int key) {
    for(int i=0; i<n; i++) if(a[i]==key) return i;
    return -1;
}
/* Binary search */
int binarySearch(int a[], int n, int key) {
    int low=0, high=n-1;
    while(low<=high) {
        int mid=(low+high)/2;
        if(a[mid]==key) return mid;
        else if(a[mid]<key) low=mid+1;
        else high=mid-1;
    }
    return -1;
}
int main() {
    int a[50], n, ch, key, pos;
    printf("Enter n: "); scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for(int i=0; i<n; i++) scanf("%d", &a[i]);
    printf("1)Sort 2)LinearSearch 3)BinarySearch: "); scanf("%d", &ch);
    switch(ch) {
        case 1: bubbleSort(a,n);
            printf("Sorted: ");
            for(int i=0; i<n; i++) printf("%d ",a[i]); printf("\n"); break;
        case 2: printf("Key: "); scanf("%d",&key);
            pos = linearSearch(a,n,key);
            pos!=-1 ? printf("Found at index %d\n",pos) : printf("Not found\n"); break;
        case 3: bubbleSort(a,n); printf("Key: "); scanf("%d",&key);
            pos = binarySearch(a,n,key);
            pos!=-1 ? printf("Found at index %d\n",pos) : printf("Not found\n"); break;
    }
    return 0;
}
Enter n: 5
Enter 5 elements: 64 34 25 12 22
1)Sort 2)LinearSearch 3)BinarySearch: 1
Sorted: 12 22 25 34 64
P–11 Read afternoon temperature for each day of a month; find average, hottest day, and coolest day.
  1. START
  2. Declare temp[31], n (days in month)
  3. INPUT n
  4. FOR i=0 to n-1: INPUT temp[i]
  5. sum=0; max=temp[0]; min=temp[0]; hotDay=0; coolDay=0
  6. FOR i=0 to n-1:
  7.   sum += temp[i]
  8.   IF temp[i] > max: max=temp[i]; hotDay=i+1
  9.   IF temp[i] < min: min=temp[i]; coolDay=i+1
  10. avg = sum / n
  11. PRINT avg, hotDay, max, coolDay, min
  12. STOP
START INPUT n, temp[0..n-1] sum=0, max=min=temp[0] i < n ? Yes sum+=temp[i] update max/min/hotDay/coolDay i++ No→Calc avg PRINT avg, hotDay, coolDay STOP
/* Program 11: Monthly Temperature Analysis */
#include <stdio.h>

int main() {
    float temp[31], sum = 0, avg, maxT, minT;
    int n, hotDay, coolDay;

    printf("Enter number of days in month: "); scanf("%d", &n);
    printf("Enter afternoon temperatures:\n");
    for(int i = 0; i < n; i++) {
        printf("Day %d: ", i+1); scanf("%f", &temp[i]);
    }

    /* Initialize max, min */
    maxT = minT = temp[0]; hotDay = coolDay = 1;

    for(int i = 0; i < n; i++) {
        sum += temp[i];
        if(temp[i] > maxT) { maxT = temp[i]; hotDay = i + 1; }
        if(temp[i] < minT) { minT = temp[i]; coolDay = i + 1; }
    }
    avg = sum / n;

    printf("\nMonthly Average Temp: %.2f°C\n", avg);
    printf("Hottest Day: Day %d (%.2f°C)\n", hotDay, maxT);
    printf("Coolest Day: Day %d (%.2f°C)\n", coolDay, minT);
    return 0;
}
Monthly Average Temp: 34.50°C
Hottest Day: Day 5 (42.00°C)
Coolest Day: Day 2 (28.00°C)
P–12 3×3 matrix operations: addition, subtraction, multiplication, inverse, transpose, diagonal sum.
  1. START
  2. INPUT matrix A[3][3] and B[3][3]
  3. CASE Add: C[i][j] = A[i][j] + B[i][j]
  4. CASE Sub: C[i][j] = A[i][j] - B[i][j]
  5. CASE Mul: C[i][j] = Σ A[i][k]*B[k][j] for k=0..2
  6. CASE Transpose: T[i][j] = A[j][i]
  7. CASE Diagonal: sum = A[0][0]+A[1][1]+A[2][2]
  8. CASE Inverse: det = a(ei-fh)-b(di-fg)+c(dh-eg); inv[i][j] = cofactor/det
  9. STOP
START INPUT A[3][3] & B[3][3] SWITCH op Add/Sub Multiply Transpose Inverse STOP
/* Program 12: 3x3 Matrix Operations */
#include <stdio.h>

void printMatrix(float m[3][3]) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%8.2f", m[i][j]);
        printf("\n");
    }
}
int main() {
    float A[3][3], B[3][3], C[3][3];
    int ch;
    printf("Enter Matrix A (9 values):\n");
    for(int i=0;i<3;i++) for(int j=0;j<3;j++) scanf("%f",&A[i][j]);
    printf("Enter Matrix B (9 values):\n");
    for(int i=0;i<3;i++) for(int j=0;j<3;j++) scanf("%f",&B[i][j]);
    printf("1)Add 2)Sub 3)Mul 4)Transpose 5)Diagonal 6)Inverse: ");
    scanf("%d",&ch);
    switch(ch) {
        case 1: /* Addition */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[i][j]+B[i][j];
            printf("A+B:\n"); printMatrix(C); break;
        case 2: /* Subtraction */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[i][j]-B[i][j];
            printf("A-B:\n"); printMatrix(C); break;
        case 3: /* Multiplication */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
                C[i][j]=0;
                for(int k=0;k<3;k++) C[i][j]+=A[i][k]*B[k][j];
            }
            printf("A*B:\n"); printMatrix(C); break;
        case 4: /* Transpose */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[j][i];
            printf("Transpose A:\n"); printMatrix(C); break;
        case 5: /* Diagonal Sum */
            printf("Diagonal sum = %.2f\n", A[0][0]+A[1][1]+A[2][2]); break;
        case 6: /* Inverse (3x3 cofactor method) */
            { float det = A[0][0]*(A[1][1]*A[2][2]-A[1][2]*A[2][1])
                       -A[0][1]*(A[1][0]*A[2][2]-A[1][2]*A[2][0])
                       +A[0][2]*(A[1][0]*A[2][1]-A[1][1]*A[2][0]);
              if(det==0) { printf("Singular matrix\n"); break; }
              C[0][0]=(A[1][1]*A[2][2]-A[1][2]*A[2][1])/det;
              C[0][1]=-(A[0][1]*A[2][2]-A[0][2]*A[2][1])/det;
              C[0][2]=(A[0][1]*A[1][2]-A[0][2]*A[1][1])/det;
              C[1][0]=-(A[1][0]*A[2][2]-A[1][2]*A[2][0])/det;
              C[1][1]=(A[0][0]*A[2][2]-A[0][2]*A[2][0])/det;
              C[1][2]=-(A[0][0]*A[1][2]-A[0][2]*A[1][0])/det;
              C[2][0]=(A[1][0]*A[2][1]-A[1][1]*A[2][0])/det;
              C[2][1]=-(A[0][0]*A[2][1]-A[0][1]*A[2][0])/det;
              C[2][2]=(A[0][0]*A[1][1]-A[0][1]*A[1][0])/det;
              printf("Inverse A:\n"); printMatrix(C); }
            break;
    }
    return 0;
}
1)Add 2)Sub 3)Mul 4)Transpose 5)Diagonal 6)Inverse: 3
A*B:
30.00 36.00 42.00
66.00 81.00 96.00
102.00 126.00 150.00
P–13 5×40 character array: sort strings, find largest/smallest string, search for string.
  1. START
  2. Declare str[5][40], n=5
  3. INPUT 5 strings
  4. CASE Sort: Bubble sort comparing strings (strcmp without library: char by char)
  5. CASE Largest: Compare each string with max; if greater update max
  6. CASE Smallest: Compare each string with min; if smaller update min
  7. CASE Search: Compare key with each string; char by char
  8. STOP
START INPUT 5 strings Sort strings (bubble sort) Largest = str[0], Smallest=str[0] PRINT results STOP
/* Program 13: 2D Character Array String Operations */
#include <stdio.h>

/* Custom strcmp: returns <0 if a<b, 0 if equal, >0 if a>b */
int mycmp(char *a, char *b) {
    while(*a && *a == *b) { a++; b++; }
    return *a - *b;
}
void mycpy(char *d, char *s) { while(*s) *d++ = *s++; *d = '\0'; }

int main() {
    char str[5][40], temp[40], key[40];
    int ch, found;

    printf("Enter 5 strings:\n");
    for(int i=0; i<5; i++) { printf("%d: ",i+1); scanf("%s",str[i]); }

    printf("1)Sort 2)Largest 3)Smallest 4)Search: "); scanf("%d",&ch);

    switch(ch) {
        case 1: /* Bubble sort strings */
            for(int i=0;i<4;i++) for(int j=0;j<4-i;j++)
                if(mycmp(str[j],str[j+1])>0) { mycpy(temp,str[j]); mycpy(str[j],str[j+1]); mycpy(str[j+1],temp); }
            printf("Sorted:\n"); for(int i=0;i<5;i++) printf("%s\n",str[i]); break;
        case 2: /* Largest string */
            mycpy(temp,str[0]);
            for(int i=1;i<5;i++) if(mycmp(str[i],temp)>0) mycpy(temp,str[i]);
            printf("Largest: %s\n",temp); break;
        case 3: /* Smallest string */
            mycpy(temp,str[0]);
            for(int i=1;i<5;i++) if(mycmp(str[i],temp)<0) mycpy(temp,str[i]);
            printf("Smallest: %s\n",temp); break;
        case 4: /* Search for string */
            printf("Enter search key: "); scanf("%s",key);
            found = -1;
            for(int i=0;i<5;i++) if(mycmp(str[i],key)==0) { found=i; break; }
            found!=-1 ? printf("Found at index %d\n",found) : printf("Not found\n"); break;
    }
    return 0;
}
Enter 5 strings:
1)Sort 2)Largest 3)Smallest 4)Search: 2
Largest: zebra
🔧

Section 4: Functions

Programs 14–19
P–14 Function power(a, b) to calculate a raised to b.
  1. START
  2. FUNCTION power(a, b): result=1
  3.   FOR i=1 to b: result = result * a
  4.   RETURN result
  5. In main: INPUT a, b
  6. PRINT power(a, b)
  7. STOP
START INPUT a, b Call power(a, b) power(): result=1 i <= b? result*=a; i++ No→RETURN STOP
/* Program 14: Power function a^b */
#include <stdio.h>

/* Function to compute a raised to power b */
double power(double a, int b) {
    double result = 1.0;
    int neg = (b < 0);
    if(neg) b = -b;
    for(int i = 1; i <= b; i++)
        result *= a;
    return neg ? 1.0 / result : result;
}

int main() {
    double a;
    int b;
    printf("Enter base (a): ");  scanf("%lf", &a);
    printf("Enter exponent (b): "); scanf("%d", &b);
    printf("%.2f ^ %d = %.4f\n", a, b, power(a, b));
    return 0;
}
Enter base (a): 2
Enter exponent (b): 10
2.00 ^ 10 = 1024.0000
P–15 Demonstrate difference between static and auto variable.
  1. START
  2. Define function demo() with static int s=0 and auto int a=0
  3.   s++; a++; PRINT s and a
  4. In main: Call demo() 3 times
  5. Observe: static s retains value, auto a resets each call
  6. STOP
START Call demo() — 1st call Call demo() — 2nd call Call demo() — 3rd call PRINT static vs auto values STOP
/* Program 15: Static vs Auto variable */
#include <stdio.h>

void demo() {
    /* static: initialised once, retains value between calls */
    static int s = 0;
    /* auto (default): re-initialised every call */
    int a = 0;
    s++; a++;
    printf("static s = %d  |  auto a = %d\n", s, a);
}

int main() {
    printf("--- Calling demo() 3 times ---\n");
    demo(); /* Call 1 */
    demo(); /* Call 2 */
    demo(); /* Call 3 */
    return 0;
}
--- Calling demo() 3 times ---
static s = 1 | auto a = 1
static s = 2 | auto a = 1
static s = 3 | auto a = 1
P–16 Demonstrate difference between local and global variables.
  1. START
  2. Declare global variable x = 100
  3. In function show(): PRINT global x
  4. In function modify(): local x = 50; PRINT local x
  5. In main: PRINT global x; call modify(); call show(); PRINT global x
  6. Observe: local x in modify() doesn't affect global x
  7. STOP
START Global x = 100 PRINT global x (=100) Call modify(): local x=50 Call show(): global x=100 STOP
/* Program 16: Local vs Global Variable */
#include <stdio.h>

/* Global variable visible everywhere */
int x = 100;

void show() {
    /* Access global x */
    printf("Inside show(): global x = %d\n", x);
}
void modify() {
    /* Local x shadows global x */
    int x = 50;
    printf("Inside modify(): local x = %d\n", x);
}

int main() {
    printf("In main before calls: global x = %d\n", x);
    modify();
    show();
    printf("In main after calls: global x = %d\n", x);
    return 0;
}
In main before calls: global x = 100
Inside modify(): local x = 50
Inside show(): global x = 100
In main after calls: global x = 100
P–17 Functions: factorial, Fibonacci, Sin series, exponential series using switch/loops/functions.
  1. START
  2. Define separate functions: factorial(n), fibonacci(n), sinSeries(x,n), expSeries(x,n)
  3. In main: INPUT choice; use switch to call appropriate function
  4. factorial: returns long, iterative loop
  5. fibonacci: prints series using loop
  6. sinSeries: x - x³/3! + x⁵/5! - ... using loop
  7. expSeries: 1 + x + x²/2! + ... using loop
  8. STOP
START INPUT choice, n or x SWITCH choice factorial(n) fibonacci(n) sinSeries(x,n) expSeries(x,n)
/* Program 17: Functions for mathematical series */
#include <stdio.h>

long factorial(int n) {
    long f = 1; for(int i=2;i<=n;i++) f*=i; return f;
}
void fibonacci(int n) {
    double a=0,b=1,s=1,t;
    printf("Fib: 0 1 ");
    for(int i=2;i<n;i++){t=a+b;a=b;b=t;s+=t;printf("%.0f ",t);}
    printf("\nSum=%.0f\n",s);
}
void sinSeries(double x, int n) {
    double s=0,t=x; long f=1;
    for(int i=1;i<=n;i++) {
        s+=t;
        t=-t*x*x/((2*i)*(2*i+1));
    }
    printf("sin(%.4f) = %.6f\n",x,s);
}
void expSeries(double x, int n) {
    double s=1,t=1;
    for(int i=1;i<=n;i++) { t*=x/i; s+=t; }
    printf("e^%.4f = %.6f\n",x,s);
}
int main() {
    int ch, n; double x;
    printf("1)Fact 2)Fib 3)Sin 4)Exp: "); scanf("%d",&ch);
    switch(ch){
        case 1: printf("n: ");scanf("%d",&n);printf("%d!=%ld\n",n,factorial(n));break;
        case 2: printf("n: ");scanf("%d",&n);fibonacci(n);break;
        case 3: printf("x n: ");scanf("%lf %d",&x,&n);sinSeries(x,n);break;
        case 4: printf("x n: ");scanf("%lf %d",&x,&n);expSeries(x,n);break;
    }
    return 0;
}
1)Fact 2)Fib 3)Sin 4)Exp: 1
n: 6
6! = 720
P–18 Recursive functions: factorial, Fibonacci, sin/exp series, natural series.
  1. START
  2. recursive_factorial(n): IF n==0 RETURN 1 ELSE RETURN n*factorial(n-1)
  3. recursive_fib(n): IF n<=1 RETURN n ELSE RETURN fib(n-1)+fib(n-2)
  4. factorial_helper(n): returns n! = n * (n-1)!
  5. sum_natural(n): IF n==0 RETURN 0 ELSE RETURN n + sum_natural(n-1)
  6. STOP
START: factorial(n) n == 0? Yes Ret 1 No RETURN n * factorial(n-1) [Recursive call] Result propagates up call stack STOP
/* Program 18: Recursive Functions */
#include <stdio.h>

/* Recursive factorial */
long rfact(int n) { return (n==0)?1:n*rfact(n-1); }

/* Recursive Fibonacci */
long rfib(int n) { return (n<=1)?n:rfib(n-1)+rfib(n-2); }

/* Recursive sum of natural numbers */
long rsum(int n) { return (n==0)?0:n+rsum(n-1); }

/* Recursive power a^b */
double rpow(double a, int b) {
    if(b==0) return 1;
    return a * rpow(a, b-1);
}

int main() {
    int ch, n; double a;
    printf("1)Fact 2)Fibonacci 3)SumNatural 4)Power: "); scanf("%d",&ch);
    switch(ch){
        case 1: printf("n: ");scanf("%d",&n);printf("%d!=%ld\n",n,rfact(n));break;
        case 2: printf("n: ");scanf("%d",&n);
            for(int i=0;i<n;i++) printf("%ld ",rfib(i)); printf("\n");break;
        case 3: printf("n: ");scanf("%d",&n);printf("Sum=%ld\n",rsum(n));break;
        case 4: printf("a b: ");scanf("%lf %d",&a,&n);
            printf("%.2f^%d=%.4f\n",a,n,rpow(a,n));break;
    }
    return 0;
}
1)Fact 2)Fibonacci 3)SumNatural 4)Power: 2
n: 8
0 1 1 2 3 5 8 13
P–19 Function to accept 10 characters and classify each as digit, uppercase, or lowercase letter.
  1. START
  2. FUNCTION classify(ch):
  3.   IF ch >= '0' && ch <= '9': RETURN "Digit"
  4.   ELIF ch >= 'A' && ch <= 'Z': RETURN "Uppercase"
  5.   ELIF ch >= 'a' && ch <= 'z': RETURN "Lowercase"
  6.   ELSE: RETURN "Special"
  7. In main: FOR i=0 to 9: INPUT char c; PRINT classify(c)
  8. STOP
START INPUT char c '0'≤c≤'9'? Yes→Digit No 'A'≤c≤'Z'? Yes→Upper No→Lower/Special STOP
/* Program 19: Character Classification */
#include <stdio.h>

char* classify(char c) {
    if(c >= '0' && c <= '9') return "Digit";
    if(c >= 'A' && c <= 'Z') return "Uppercase Letter";
    if(c >= 'a' && c <= 'z') return "Lowercase Letter";
    return "Special Character";
}

int main() {
    char c;
    printf("Enter 10 characters (one per line):\n");
    for(int i = 0; i < 10; i++) {
        printf("Char %2d: ", i+1); scanf(" %c", &c);
        printf("  '%c' -> %s\n", c, classify(c));
    }
    return 0;
}
Char 1: 'A' -> Uppercase Letter
Char 2: 'z' -> Lowercase Letter
Char 3: '5' -> Digit
Char 4: '#' -> Special Character
⚙️

Section 5: Array & Function

Programs 20–23 — Matrix & string operations using user-defined functions
P–20 Matrix (Function): multiply two matrices.
  1. START
  2. INPUT matrix A[3][3] and B[3][3]
  3. CASE Add: C[i][j] = A[i][j] + B[i][j]
  4. CASE Sub: C[i][j] = A[i][j] - B[i][j]
  5. CASE Mul: C[i][j] = Σ A[i][k]*B[k][j] for k=0..2
  6. CASE Transpose: T[i][j] = A[j][i]
  7. CASE Diagonal: sum = A[0][0]+A[1][1]+A[2][2]
  8. CASE Inverse: det = a(ei-fh)-b(di-fg)+c(dh-eg); inv[i][j] = cofactor/det
  9. STOP
START INPUT A[3][3] & B[3][3] SWITCH op Add/Sub Multiply Transpose Inverse STOP
/* Program 20: Matrix (Function): multiply two matrices */
#include <stdio.h>

void printMatrix(float m[3][3]) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%8.2f", m[i][j]);
        printf("\n");
    }
}
int main() {
    float A[3][3], B[3][3], C[3][3];
    int ch;
    printf("Enter Matrix A (9 values):\n");
    for(int i=0;i<3;i++) for(int j=0;j<3;j++) scanf("%f",&A[i][j]);
    printf("Enter Matrix B (9 values):\n");
    for(int i=0;i<3;i++) for(int j=0;j<3;j++) scanf("%f",&B[i][j]);
    printf("1)Add 2)Sub 3)Mul 4)Transpose 5)Diagonal 6)Inverse: ");
    scanf("%d",&ch);
    switch(ch) {
        case 1: /* Addition */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[i][j]+B[i][j];
            printf("A+B:\n"); printMatrix(C); break;
        case 2: /* Subtraction */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[i][j]-B[i][j];
            printf("A-B:\n"); printMatrix(C); break;
        case 3: /* Multiplication */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
                C[i][j]=0;
                for(int k=0;k<3;k++) C[i][j]+=A[i][k]*B[k][j];
            }
            printf("A*B:\n"); printMatrix(C); break;
        case 4: /* Transpose */
            for(int i=0;i<3;i++) for(int j=0;j<3;j++) C[i][j]=A[j][i];
            printf("Transpose A:\n"); printMatrix(C); break;
        case 5: /* Diagonal Sum */
            printf("Diagonal sum = %.2f\n", A[0][0]+A[1][1]+A[2][2]); break;
        case 6: /* Inverse (3x3 cofactor method) */
            { float det = A[0][0]*(A[1][1]*A[2][2]-A[1][2]*A[2][1])
                       -A[0][1]*(A[1][0]*A[2][2]-A[1][2]*A[2][0])
                       +A[0][2]*(A[1][0]*A[2][1]-A[1][1]*A[2][0]);
              if(det==0) { printf("Singular matrix\n"); break; }
              C[0][0]=(A[1][1]*A[2][2]-A[1][2]*A[2][1])/det;
              C[0][1]=-(A[0][1]*A[2][2]-A[0][2]*A[2][1])/det;
              C[0][2]=(A[0][1]*A[1][2]-A[0][2]*A[1][1])/det;
              C[1][0]=-(A[1][0]*A[2][2]-A[1][2]*A[2][0])/det;
              C[1][1]=(A[0][0]*A[2][2]-A[0][2]*A[2][0])/det;
              C[1][2]=-(A[0][0]*A[1][2]-A[0][2]*A[1][0])/det;
              C[2][0]=(A[1][0]*A[2][1]-A[1][1]*A[2][0])/det;
              C[2][1]=-(A[0][0]*A[2][1]-A[0][1]*A[2][0])/det;
              C[2][2]=(A[0][0]*A[1][1]-A[0][1]*A[1][0])/det;
              printf("Inverse A:\n"); printMatrix(C); }
            break;
    }
    return 0;
}
1)Add 2)Sub 3)Mul 4)Transpose 5)Diagonal 6)Inverse: 3
A*B:
30.00 36.00 42.00
66.00 81.00 96.00
102.00 126.00 150.00
P–21 String (Function): count vowels, consonants, punctuation, sort alphabets.
  1. START
  2. INPUT string
  3. CASE Count: count=0; WHILE s[i]!='\0' count++
  4. CASE Copy: FOR each char: dest[i]=src[i]; dest[i]='\0'
  5. CASE Palindrome: reverse copy; compare char by char
  6. CASE Vowels/Consonants: check each char against aeiou
  7. CASE Sort: bubble sort on char array
  8. STOP
START INPUT string SWITCH choice Count Copy Palindrome Vowels/Consonants STOP
/* Program 21: String (Function): count vowels, consonants, punctuation, sort alphabets */
#include <stdio.h>

int mylen(char s[]) { int i=0; while(s[i]) i++; return i; }

int main() {
    char s[100], dest[100], rev[100];
    int ch, i, j, len, vowels=0, cons=0, punc=0;
    printf("a)Rev b)Count c)Copy d)Palindrome e)Vowels f)Sort: ");
    scanf(" %c", (char*)&ch);
    printf("Enter string: "); scanf(" %[^\n]", s);
    len = mylen(s);

    switch(ch) {
        case 'a': /* Reverse */
            i=0; j=len-1;
            while(i<j){ char t=s[i]; s[i]=s[j]; s[j]=t; i++; j--; }
            printf("Reversed: %s\n", s); break;
        case 'b': /* Count characters */
            printf("Length: %d\n", len); break;
        case 'c': /* Copy string */
            for(i=0; i<=len; i++) dest[i]=s[i];
            printf("Copied: %s\n", dest); break;
        case 'd': /* Palindrome */
            for(i=0; i<len; i++) rev[i]=s[len-1-i]; rev[len]='\0';
            i=0; while(i<len && s[i]==rev[i]) i++;
            printf("%s %s palindrome\n", s, i==len?"IS":"is NOT"); break;
        case 'e': /* Count vowels, consonants, punctuation */
            for(i=0; i<len; i++) {
                char c = s[i]|32; /* lowercase */
                if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') vowels++;
                else if(c>='a' && c<='z') cons++;
                else if(s[i]!=' ') punc++;
            }
            printf("Vowels:%d Consonants:%d Punct:%d\n", vowels, cons, punc); break;
        case 'f': /* Sort alphabets (bubble sort) */
            for(i=0; i<len-1; i++)
                for(j=0; j<len-i-1; j++)
                    if(s[j]>s[j+1]){ char t=s[j]; s[j]=s[j+1]; s[j+1]=t; }
            printf("Sorted: %s\n", s); break;
        default: printf("Invalid\n");
    }
    return 0;
}
a)Rev b)Count c)Copy d)Palindrome e)Vowels f)Sort: d
Enter string: madam
madam IS palindrome
P–22 Array (Function): sort elements, linear search, binary search using switch/if-else/loop.
  1. START
  2. INPUT n, array a[n]
  3. CASE Sort: Bubble Sort – FOR i=0 to n-2: FOR j=0 to n-i-2: IF a[j]>a[j+1] swap
  4. CASE Linear Search: FOR each element IF a[i]==key: found
  5. CASE Binary Search: Sort first; low=0, high=n-1
  6.   WHILE low <= high: mid=(low+high)/2
  7.     IF a[mid]==key: found; ELIF a[mid]<key: low=mid+1; ELSE high=mid-1
  8. STOP
START INPUT n, array a[] Call power(a, b) power(): result=1 i <= b? result*=a; i++ No→RETURN STOP
/* Program 22: Array Sort and Search */
#include <stdio.h>

/* Bubble sort */
void bubbleSort(int a[], int n) {
    for(int i=0; i<n-1; i++)
        for(int j=0; j<n-i-1; j++)
            if(a[j]>a[j+1]){ int t=a[j]; a[j]=a[j+1]; a[j+1]=t; }
}
/* Linear search */
int linearSearch(int a[], int n, int key) {
    for(int i=0; i<n; i++) if(a[i]==key) return i;
    return -1;
}
/* Binary search */
int binarySearch(int a[], int n, int key) {
    int low=0, high=n-1;
    while(low<=high) {
        int mid=(low+high)/2;
        if(a[mid]==key) return mid;
        else if(a[mid]<key) low=mid+1;
        else high=mid-1;
    }
    return -1;
}
int main() {
    int a[50], n, ch, key, pos;
    printf("Enter n: "); scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for(int i=0; i<n; i++) scanf("%d", &a[i]);
    printf("1)Sort 2)LinearSearch 3)BinarySearch: "); scanf("%d", &ch);
    switch(ch) {
        case 1: bubbleSort(a,n);
            printf("Sorted: ");
            for(int i=0; i<n; i++) printf("%d ",a[i]); printf("\n"); break;
        case 2: printf("Key: "); scanf("%d",&key);
            pos = linearSearch(a,n,key);
            pos!=-1 ? printf("Found at index %d\n",pos) : printf("Not found\n"); break;
        case 3: bubbleSort(a,n); printf("Key: "); scanf("%d",&key);
            pos = binarySearch(a,n,key);
            pos!=-1 ? printf("Found at index %d\n",pos) : printf("Not found\n"); break;
    }
    return 0;
}
Enter n: 5
Enter 5 elements: 64 34 25 12 22
1)Sort 2)LinearSearch 3)BinarySearch: 1
Sorted: 12 22 25 34 64
P–23 String Array (Function): sort, largest, smallest, search in a 5x40 char array.
  1. START
  2. INPUT 5 strings into arr[5][40]
  3. MENU choice = 1-Sort, 2-Largest, 3-Smallest, 4-Search
  4. IF choice == 1, sort strings and display
  5. ELSE IF choice == 2, find largest string and display
  6. ELSE IF choice == 3, find smallest string and display
  7. ELSE IF choice == 4, search string and display result
  8. STOP
START READ 5 strings READ choice choice? PROCESS STOP
/* Program 23: 5x40 string array operations */
#include <stdio.h>
#include <string.h>

void sortStrings(char arr[][40], int n) {
    for(int i=0; i<n-1; i++) {
        for(int j=0; j<n-i-1; j++) {
            if(strcmp(arr[j], arr[j+1]) > 0) {
                char temp[40];
                strcpy(temp, arr[j]);
                strcpy(arr[j], arr[j+1]);
                strcpy(arr[j+1], temp);
            }
        }
    }
}

void printStrings(char arr[][40], int n) {
    for(int i=0; i<n; i++) printf("%s\n", arr[i]);
}

int main() {
    char arr[5][40];
    int choice;
    printf("Enter 5 strings:\n");
    for(int i=0; i<5; i++) gets(arr[i]);
    printf("1)Sort 2)Largest 3)Smallest 4)Search: ");
    scanf("%d", &choice);
    getchar();
    switch(choice) {
        case 1:
            sortStrings(arr, 5);
            printStrings(arr, 5);
            break;
        case 2:
            char *largest = arr[0];
            for(int i=1; i<5; i++)
                if(strcmp(arr[i], largest) > 0) largest = arr[i];
            printf("Largest: %s\n", largest);
            break;
        case 3:
            char *smallest = arr[0];
            for(int i=1; i<5; i++)
                if(strcmp(arr[i], smallest) < 0) smallest = arr[i];
            printf("Smallest: %s\n", smallest);
            break;
        case 4:
            char key[40];
            printf("Search string: ");
            gets(key);
            int found=0;
            for(int i=0; i<5; i++)
                if(strcmp(arr[i], key)==0) { found = 1; break; }
            printf(found ? "Found\n" : "Not found\n");
            break;
    }
    return 0;
}
Enter 5 strings:
apple
orange
banana
grape
mango
1)Sort 2)Largest 3)Smallest 4)Search: 1
Sorted strings:
apple
banana
grape
mango
orange
📦

Section 6: Structures & Unions

Programs 24–27 — Struct Student, Struct Date/Employee, Complex numbers
P–24 Structure Student: roll, name, 3 subjects, marks, result.
  1. START
  2. Define STRUCT Student with: roll, name, sub1, sub2, sub3, maxmarks, minmarks, obtmarks
  3. Declare struct variable s1
  4. Read roll, name, subject names, marks
  5. Calculate: total = sub1+sub2+sub3; avg = total/3; percent = (total/maxmarks)*100
  6. Display: roll, name, subjects, marks, total, average, percentage, result (Pass/Fail)
  7. STOP
START INPUT roll, name, marks Calculate total, avg, % % >= 40? PASS FAIL DISPLAY result STOP
/* Program 24: Structure Student */
#include <stdio.h>

struct Student {
    int roll;
    char name[50];
    char sub1[30], sub2[30], sub3[30];
    float mark1, mark2, mark3;
    float maxmarks, minmarks, obtmarks;
};

int main() {
    struct Student s;
    printf("Enter roll: "); scanf("%d", &s.roll);
    printf("Enter name: "); scanf("%s", s.name);
    printf("Enter 3 subject names: ");
    scanf("%s %s %s", s.sub1, s.sub2, s.sub3);
    printf("Enter 3 marks: ");
    scanf("%f %f %f", &s.mark1, &s.mark2, &s.mark3);
    printf("Enter max marks: "); scanf("%f", &s.maxmarks);
    printf("Enter min marks: "); scanf("%f", &s.minmarks);
    
    float total = s.mark1 + s.mark2 + s.mark3;
    float avg = total / 3;
    float percent = (total / s.maxmarks) * 100;
    
    printf("\n===== STUDENT RESULT =====\n");
    printf("Roll: %d\nName: %s\n", s.roll, s.name);
    printf("%s: %.1f\n%s: %.1f\n%s: %.1f\n", s.sub1, s.mark1, s.sub2, s.mark2, s.sub3, s.mark3);
    printf("Total: %.1f\nAverage: %.1f\nPercentage: %.2f%%\n", total, avg, percent);
    printf("Result: %s\n", percent >= 40 ? "PASS" : "FAIL");
    
    return 0;
}
Enter roll: 101
Enter name: John
Enter 3 subject names: Math English Science
Enter 3 marks: 85 75 90
Enter max marks: 300
Enter min marks: 120
===== STUDENT RESULT =====
Roll: 101
Name: John
Math: 85.0
English: 75.0
Science: 90.0
Total: 250.0
Average: 83.33
Percentage: 83.33%
Result: PASS
P–25 Nested Structure: Date (dd,mm,yy) inside Employee.
  1. START
  2. Define STRUCT Date with: dd, mm, yy
  3. Define STRUCT Employee with: name, emp_id, doj (of type struct Date)
  4. Declare struct Employee variable e1
  5. Read employee name, id, date of joining (dd, mm, yy)
  6. Display all employee details with formatted date
  7. STOP
START INPUT emp name, id, date Store in nested struct DISPLAY all fields STOP
/* Program 25: Nested Structure - Date in Employee */
#include <stdio.h>

struct Date {
    int dd, mm, yy;
};

struct Employee {
    char name[50];
    int emp_id;
    struct Date doj;
};

int main() {
    struct Employee e;
    
    printf("Enter employee name: "); scanf("%s", e.name);
    printf("Enter employee id: "); scanf("%d", &e.emp_id);
    printf("Enter date of joining (dd mm yy): ");
    scanf("%d %d %d", &e.doj.dd, &e.doj.mm, &e.doj.yy);
    
    printf("\n===== EMPLOYEE DATA =====\n");
    printf("Name: %s\n", e.name);
    printf("Employee ID: %d\n", e.emp_id);
    printf("Date of Joining: %02d/%02d/%d\n", e.doj.dd, e.doj.mm, e.doj.yy);
    
    return 0;
}
Enter employee name: Alice
Enter employee id: 5001
Enter date of joining (dd mm yy): 15 3 2020
===== EMPLOYEE DATA =====
Name: Alice
Employee ID: 5001
Date of Joining: 15/03/2020
P–26 Array of Structures: 3 students, display all & specific results.
  1. START
  2. Define STRUCT Student (roll, name, marks)
  3. Declare ARRAY of 3 struct Student
  4. FOR i=0 to 2: Read roll, name, marks for each student
  5. Display menu: 1-Show all results, 2-Search by roll
  6. IF choice==1: Display all students' data
  7. ELSE IF choice==2: Read roll number and display that student's data
  8. STOP
START Create array of 3 students Input data for 3 students choice? Show All Search DISPLAY results STOP
/* Program 26: Array of Structures - Students */
#include <stdio.h>

struct Student {
    int roll;
    char name[50];
    float m1, m2, m3;
    float total, percent;
};

void displayAll(struct Student s[], int n) {
    for(int i=0; i<n; i++) {
        printf("\nRoll: %d | Name: %s | Total: %.1f | Percentage: %.1f%%\n", 
               s[i].roll, s[i].name, s[i].total, s[i].percent);
    }
}

void searchByRoll(struct Student s[], int n, int roll) {
    for(int i=0; i<n; i++) {
        if(s[i].roll == roll) {
            printf("\nRoll: %d\nName: %s\nMarks: %.1f, %.1f, %.1f\nTotal: %.1f\nPercentage: %.1f%%\n",
                   s[i].roll, s[i].name, s[i].m1, s[i].m2, s[i].m3, s[i].total, s[i].percent);
            return;
        }
    }
    printf("Student not found!\n");
}

int main() {
    struct Student s[3];
    
    printf("Enter data for 3 students:\n");
    for(int i=0; i<3; i++) {
        printf("\nStudent %d:\n", i+1);
        printf("Roll: "); scanf("%d", &s[i].roll);
        printf("Name: "); scanf("%s", s[i].name);
        printf("Marks: "); scanf("%f %f %f", &s[i].m1, &s[i].m2, &s[i].m3);
        s[i].total = s[i].m1 + s[i].m2 + s[i].m3;
        s[i].percent = (s[i].total / 300) * 100;
    }
    
    int choice;
    printf("\n1)Show All  2)Search: "); scanf("%d", &choice);
    if(choice == 1) displayAll(s, 3);
    else {
        int roll;
        printf("Enter roll to search: "); scanf("%d", &roll);
        searchByRoll(s, 3, roll);
    }
    
    return 0;
}
Enter data for 3 students:
Student 1: Roll: 101 Name: Alice Marks: 85 90 88
Student 2: Roll: 102 Name: Bob Marks: 75 80 82
Student 3: Roll: 103 Name: Carol Marks: 92 88 95
1)Show All 2)Search: 1
Roll: 101 | Name: Alice | Total: 263.0 | Percentage: 87.67%
Roll: 102 | Name: Bob | Total: 237.0 | Percentage: 79.00%
Roll: 103 | Name: Carol | Total: 275.0 | Percentage: 91.67%
P–27 Complex Numbers: add, subtract, multiply, divide using structures.
  1. START
  2. Define STRUCT complex with: real, imag
  3. Read two complex numbers c1, c2
  4. Menu: 1-Add, 2-Subtract, 3-Multiply, 4-Divide
  5. FOR Add: result.real = c1.real + c2.real; result.imag = c1.imag + c2.imag
  6. FOR Subtract: result.real = c1.real - c2.real; result.imag = c1.imag - c2.imag
  7. FOR Multiply: (a+bi)*(c+di) = (ac-bd) + (ad+bc)i
  8. FOR Divide: Use conjugate method
  9. Display result in form: real +/- imag i
  10. STOP
START INPUT c1, c2 (complex) Operation? Add Mul/Div DISPLAY result STOP
/* Program 27: Complex Numbers using Structures */
#include <stdio.h>

struct complex {
    float real, imag;
};

struct complex add(struct complex c1, struct complex c2) {
    struct complex res;
    res.real = c1.real + c2.real;
    res.imag = c1.imag + c2.imag;
    return res;
}

struct complex sub(struct complex c1, struct complex c2) {
    struct complex res;
    res.real = c1.real - c2.real;
    res.imag = c1.imag - c2.imag;
    return res;
}

struct complex mul(struct complex c1, struct complex c2) {
    struct complex res;
    res.real = (c1.real * c2.real) - (c1.imag * c2.imag);
    res.imag = (c1.real * c2.imag) + (c1.imag * c2.real);
    return res;
}

struct complex divd(struct complex c1, struct complex c2) {
    struct complex res;
    float denom = (c2.real * c2.real) + (c2.imag * c2.imag);
    res.real = ((c1.real * c2.real) + (c1.imag * c2.imag)) / denom;
    res.imag = ((c1.imag * c2.real) - (c1.real * c2.imag)) / denom;
    return res;
}

int main() {
    struct complex c1, c2, result;
    int op;
    
    printf("Enter c1 (real imag): "); scanf("%f %f", &c1.real, &c1.imag);
    printf("Enter c2 (real imag): "); scanf("%f %f", &c2.real, &c2.imag);
    printf("1)Add 2)Sub 3)Mul 4)Div: "); scanf("%d", &op);
    
    switch(op) {
        case 1: result = add(c1, c2); break;
        case 2: result = sub(c1, c2); break;
        case 3: result = mul(c1, c2); break;
        case 4: result = divd(c1, c2); break;
    }
    
    printf("\nResult: %.1f %c %.1fi\n", result.real, result.imag >= 0 ? '+' : '-', 
           result.imag >= 0 ? result.imag : -result.imag);
    
    return 0;
}
Enter c1 (real imag): 3 4
Enter c2 (real imag): 1 2
1)Add 2)Sub 3)Mul 4)Div: 1
Result: 4.0 + 6.0i
For Multiply (3+4i) * (1+2i):
Result: -5.0 + 10.0i

Section 7: Pointers & Unions

Programs 28–42 — Union, Enum, Pointers, Pointer arithmetic, Linked Lists
P–28 Union Emp: test union with int, float, char array.
  1. START
  2. Define UNION Emp with: one int, one float, one char[20]
  3. Declare union variable e
  4. Assign value to e.i (int)
  5. Display: e.i, size of union, address of e
  6. Assign value to e.f (float) - overwrites e.i
  7. Display: e.f, e.i (now corrupted)
  8. Assign value to e.s (string) - overwrites e.f
  9. Display: e.s, e.f (now corrupted)
  10. STOP
START Declare union variable Assign int value Display int value Assign float, then string Display all values STOP
/* Program 28: Union Test */
#include <stdio.h>

union Emp {
    int i;
    float f;
    char s[20];
};

int main() {
    union Emp e;
    
    printf("Size of union: %lu bytes\n", sizeof(e));
    
    e.i = 100;
    printf("\nAfter assigning int = 100:\n");
    printf("e.i = %d\n", e.i);
    printf("e.f = %f\n", e.f);
    printf("e.s = %s\n", e.s);
    
    e.f = 3.14;
    printf("\nAfter assigning float = 3.14:\n");
    printf("e.i = %d (overwritten)\n", e.i);
    printf("e.f = %f\n", e.f);
    
    strcpy(e.s, "Hello");
    printf("\nAfter assigning string = \"Hello\":\n");
    printf("e.i = %d (overwritten)\n", e.i);
    printf("e.f = %f (overwritten)\n", e.f);
    printf("e.s = %s\n", e.s);
    
    return 0;
}
Size of union: 20 bytes
After assigning int = 100:
e.i = 100
e.f = 0.000000
e.s =
After assigning float = 3.14:
e.i = 1074339225 (overwritten)
e.f = 3.140000
After assigning string = "Hello":
e.i = 1819042664 (overwritten)
e.f = 3.766226 (overwritten)
e.s = Hello
P–29 Enum DaysOfWeek: declare and test enum variable.
  1. START
  2. Define ENUM DaysOfWeek with: SUNDAY=0 to SATURDAY=6
  3. Declare enum variable day
  4. Assign values and display day names corresponding to enum values
  5. Use switch to print day name for each enum value
  6. STOP
START Declare enum variable Assign enum values Display day names STOP
/* Program 29: Enum Days of Week */
#include <stdio.h>

enum DaysOfWeek {
    SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
};

void printDay(enum DaysOfWeek day) {
    char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", 
                      "Thursday", "Friday", "Saturday"};
    printf("%s\n", days[day]);
}

int main() {
    enum DaysOfWeek day;
    
    printf("Days of the week:\n");
    for(day = SUNDAY; day <= SATURDAY; day++) {
        printf("%d: ", day);
        printDay(day);
    }
    
    printf("\nEnter day number (0-6): ");
    int d; scanf("%d", &d);
    if(d >= 0 && d <= 6) {
        printf("Selected day: ");
        printDay((enum DaysOfWeek)d);
    }
    
    return 0;
}
Days of the week:
0: Sunday
1: Monday
2: Tuesday
3: Wednesday
4: Thursday
5: Friday
6: Saturday
Enter day number (0-6): 3
Selected day: Wednesday
P–30 Swap: call by value vs call by reference.
  1. START
  2. Read two numbers a, b
  3. Display: Original a, b
  4. Call swapByValue(a, b) - values copied, original unchanged
  5. Display: After call by value (no change)
  6. Call swapByReference(&a, &b) - addresses passed, original changed
  7. Display: After call by reference (swapped)
  8. STOP
START INPUT a, b DISPLAY original a, b swapByValue(a, b) DISPLAY (still a, b) swapByReference(&a, &b) STOP
/* Program 30: Call by Value vs Call by Reference */
#include <stdio.h>

void swapByValue(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
    printf("  Inside swapByValue: x=%d, y=%d\n", x, y);
}

void swapByReference(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
    printf("  Inside swapByReference: x=%d, y=%d\n", *x, *y);
}

int main() {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    
    printf("\nOriginal: a=%d, b=%d\n", a, b);
    
    printf("\nCall by Value:\n");
    swapByValue(a, b);
    printf("  After return: a=%d, b=%d (no change)\n", a, b);
    
    printf("\nCall by Reference:\n");
    swapByReference(&a, &b);
    printf("  After return: a=%d, b=%d (swapped!)\n", a, b);
    
    return 0;
}
Enter two numbers: 10 20
Original: a=10, b=20
Call by Value:
Inside swapByValue: x=20, y=10
After return: a=10, b=20 (no change)
Call by Reference:
Inside swapByReference: x=20, y=10
After return: a=20, b=10 (swapped!)
P–43 Linked List: self-referential structure, create and print.
  1. START
  2. Define STRUCT Node with: data (int), *next pointer to Node
  3. Create nodes dynamically using malloc
  4. Link nodes: n1->next = n2, n2->next = n3, n3->next = NULL
  5. Traverse list from head using while(temp != NULL)
  6. Print each node's data
  7. Free all allocated memory
  8. STOP
START Create 3 nodes Link nodes temp = head temp != NULL? PRINT & TRAVERSE STOP
/* Program 43: Linked List */
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

struct Node* createNode(int val) {
    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = val;
    newNode->next = NULL;
    return newNode;
}

void printList(struct Node *head) {
    struct Node *temp = head;
    printf("Linked List: ");
    while(temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}

int main() {
    struct Node *n1 = createNode(10);
    struct Node *n2 = createNode(20);
    struct Node *n3 = createNode(30);
    
    n1->next = n2;
    n2->next = n3;
    
    printList(n1);
    
    free(n1); free(n2); free(n3);
    
    return 0;
}
Linked List: 10 -> 20 -> 30 -> NULL
📄

Section 8: File Streams

Programs 44–47 — File I/O operations
P–44 Copy file removing extra spaces (from command line args).
  1. START
  2. Check command line: argc must be >= 3
  3. Open source file argv[1] for reading
  4. Open destination file argv[2] for writing
  5. Read character by character from source
  6. IF current char is space AND previous was space, skip
  7. ELSE write character to destination
  8. Close both files
  9. STOP
START Check argc >= 3 argc >= 3? Yes No Open files and copy text Space and prev_space? Yes Write char if not duplicate STOP
/* Program 44: Copy file removing extra spaces */
#include <stdio.h>

int main(int argc, char *argv[]) {
    if(argc != 3) {
        printf("Usage: %s source.txt dest.txt\n", argv[0]);
        return 1;
    }
    
    FILE *src = fopen(argv[1], "r");
    FILE *dst = fopen(argv[2], "w");
    
    if(src == NULL || dst == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    int ch, prev_space = 0;
    while((fgetc(src)) != EOF) {
        if(ch == ' ') {
            if(!prev_space) fputc(ch, dst);
            prev_space = 1;
        } else {
            fputc(ch, dst);
            prev_space = 0;
        }
    }
    
    fclose(src);
    fclose(dst);
    printf("File copied successfully!\n");
    
    return 0;
}
$ gcc p44.c -o p44
$ ./p44 input.txt output.txt
File copied successfully!
P–45 Count all even numbers in a file "data".
  1. START
  2. Open file "data" for reading
  3. Initialize count = 0
  4. Read integers from file while not EOF
  5. IF number % 2 == 0, increment count
  6. Close file and display count
  7. STOP
START Open file data.txt Set count = 0 Read next number? Yes No Even number? Yes Increment count Print total even count STOP
/* Program 45: Count even numbers in file */
#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "r");
    
    if(fp == NULL) {
        printf("Error: Cannot open file\n");
        return 1;
    }
    
    int num, even_count = 0;
    while(fscanf(fp, "%d", &num) != EOF) {
        if(num % 2 == 0) even_count++;
    }
    
    fclose(fp);
    printf("Total even numbers: %d\n", even_count);
    
    return 0;
}
File content: 10 15 20 25 30 35 40
Total even numbers: 4
P–46 Count tabs, newlines, characters, spaces in a file.
  1. START
  2. Open file for reading
  3. Initialize: tabs=0, newlines=0, chars=0, spaces=0
  4. Read each character using fgetc()
  5. IF ch == '\t', increment tabs
  6. ELSE IF ch == '\n', increment newlines
  7. ELSE IF ch == ' ', increment spaces
  8. ELSE increment chars
  9. Display all counts
  10. STOP
START Open file for reading Initialize counters Read next character? Yes No Tab / newline / space? Yes Update appropriate count Print file statistics STOP
/* Program 46: Count tabs, newlines, chars, spaces */
#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "r");
    
    if(fp == NULL) {
        printf("Error: Cannot open file\n");
        return 1;
    }
    
    int tabs = 0, newlines = 0, chars = 0, spaces = 0;
    int ch;
    
    while((fgetc(fp)) != EOF) {
        if(ch == '\t') tabs++;
        else if(ch == '\n') newlines++;
        else if(ch == ' ') spaces++;
        else chars++;
    }
    
    fclose(fp);
    
    printf("===== FILE STATISTICS =====\n");
    printf("Tabs: %d\n", tabs);
    printf("Newlines: %d\n", newlines);
    printf("Spaces: %d\n", spaces);
    printf("Characters: %d\n", chars);
    
    return 0;
}
===== FILE STATISTICS =====
Tabs: 3
Newlines: 5
Spaces: 12
Characters: 42
P–47 Inventory: items with qty>5, total cost (from file).
  1. START
  2. Open inventory file for reading
  3. Read: item_number, rate, quantity
  4. Initialize: total_cost = 0
  5. Display all items with quantity > 5
  6. Calculate and add to total_cost = rate * quantity
  7. Display total cost of entire inventory
  8. Close file
  9. STOP
START Open inventory file Initialize total_cost = 0 Read next item? Yes No Compute cost and add total Qty > 5? Yes Print item line Print total inventory cost STOP
/* Program 47: Inventory File Processing */
#include <stdio.h>

int main() {
    FILE *fp = fopen("inventory.txt", "r");
    
    if(fp == NULL) {
        printf("Error: Cannot open file\n");
        return 1;
    }
    
    int item_no, qty;
    float rate, total_cost = 0;
    
    printf("===== ITEMS WITH QUANTITY > 5 =====\n");
    printf("Item#\tRate\tQty\tCost\n");
    printf("-----\t-----\t---\t-----\n");
    
    float item_cost;
    while(fscanf(fp, "%d %f %d", &item_no, &rate, &qty) != EOF) {
        item_cost = rate * qty;
        total_cost += item_cost;
        
        if(qty > 5) {
            printf("%d\t%.2f\t%d\t%.2f\n", item_no, rate, qty, item_cost);
        }
    }
    
    printf("\n===== INVENTORY SUMMARY =====\n");
    printf("Total Cost: Rs. %.2f\n", total_cost);
    
    fclose(fp);
    return 0;
}
===== ITEMS WITH QUANTITY > 5 =====
Item# Rate Qty Cost
----- ----- --- -----
101 50.00 10 500.00
102 100.00 8 800.00
104 25.00 15 375.00
===== INVENTORY SUMMARY =====
Total Cost: Rs. 2250.00