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.
- START
- Declare variables: int i, float f, double d, char c, long l, short s
- INPUT values for each variable from user
- PRINT int with %-10d (left) and %10d (right)
- PRINT float with %-10.2f and %10.2f
- PRINT double with %-10.2lf and %10.2lf
- PRINT char with %-10c and %10c
- PRINT long with %-10ld and %10ld
- PRINT short with %-10hd and %10hd
- 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.
- START
- Use three nested loops: i, j, k from 1 to 3
- FOR i = 1 to 3
- FOR j = 1 to 3
- FOR k = 1 to 3
- IF i ≠ j AND j ≠ k AND i ≠ k
- PRINT i, j, k
- END IF
- END FOR k
- END FOR j
- END FOR 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.
- START
- /* Pattern A: Descending Stars */
- FOR i = 5 downto 1: print (6-i) stars, newline
- /* Pattern B: Numbered Triangle */
- FOR i = 1 to 4: print numbers 1 to (i*(i+1)/2)
- /* Pattern C: Star Pyramid */
- FOR i = 1 to 5: print (5-i) spaces, then (2*i-1) stars
- /* Pattern D: Number Pyramid */
- FOR i = 1 to 4: print spaces, then i..1..i
- 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.
- START
- INPUT choice (11, 12, 13, 21, 22, 23...)
- SWITCH choice
- CASE 11: Print Pattern 1 using for loop
- CASE 12: Print Pattern 1 using while loop
- CASE 13: Print Pattern 1 using do-while loop
- CASE 21: Print Pattern 2 using for loop
- DEFAULT: Invalid choice
- END SWITCH
- 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.
- START
- Print header: Decimal | Octal | Hexadecimal
- FOR i = 1 to 10
- PRINT i with %d (decimal), %o (octal), %x (hex)
- END FOR
- 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).
- START
- INPUT fromBase (2/8/10/16), number as string, toBase
- Convert number from fromBase to decimal (intermediate)
- FOR each digit: decimal = decimal * fromBase + digit_value
- Convert decimal to toBase
- WHILE decimal > 0: remainder = decimal % toBase; build result
- PRINT result in toBase
- 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.
- START
- INPUT choice (a/b/c/d/e/f)
- SWITCH choice
- CASE a: Factorial: result=1; FOR i=1 to n: result*=i
- CASE b: Fibonacci: a=0,b=1; PRINT; FOR n-2 times: c=a+b; a=b; b=c
- CASE c: Sin series: sin(x) = x - x³/3! + x⁵/5! - ...
- CASE d: Exp series: e^x = 1 + x + x²/2! + x³/3! + ...
- CASE e: Primes: check divisibility for each num
- CASE f: Leap year: (y%4==0 && y%100!=0) || y%400==0
- 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.).
- START
- Same menu as P7, but use <math.h> library functions
- For Factorial: use tgamma(n+1)
- For Sin series: use sin(x) directly
- For Exp: use exp(x) directly
- For prime: use sqrt(n) for optimization
- 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.
- START
- INPUT choice (a-f), string
- CASE a – Reverse: i=0, j=len-1; WHILE i<j swap s[i],s[j]
- CASE b – Count: count=0; WHILE s[i]!='\0' count++
- CASE c – Copy: FOR each char: dest[i]=src[i]; dest[i]='\0'
- CASE d – Palindrome: reverse copy; compare char by char
- CASE e – Vowels/Consonants: check each char against aeiou
- CASE f – Sort: bubble sort on char array
- 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.
- START
- INPUT n, array a[n]
- CASE Sort: Bubble Sort – FOR i=0 to n-2: FOR j=0 to n-i-2: IF a[j]>a[j+1] swap
- CASE Linear Search: FOR each element IF a[i]==key: found
- CASE Binary Search: Sort first; low=0, high=n-1
- WHILE low <= high: mid=(low+high)/2
- IF a[mid]==key: found; ELIF a[mid]<key: low=mid+1; ELSE high=mid-1
- 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.
- START
- Declare temp[31], n (days in month)
- INPUT n
- FOR i=0 to n-1: INPUT temp[i]
- sum=0; max=temp[0]; min=temp[0]; hotDay=0; coolDay=0
- FOR i=0 to n-1:
- sum += temp[i]
- IF temp[i] > max: max=temp[i]; hotDay=i+1
- IF temp[i] < min: min=temp[i]; coolDay=i+1
- avg = sum / n
- PRINT avg, hotDay, max, coolDay, min
- 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.
- START
- INPUT matrix A[3][3] and B[3][3]
- CASE Add: C[i][j] = A[i][j] + B[i][j]
- CASE Sub: C[i][j] = A[i][j] - B[i][j]
- CASE Mul: C[i][j] = Σ A[i][k]*B[k][j] for k=0..2
- CASE Transpose: T[i][j] = A[j][i]
- CASE Diagonal: sum = A[0][0]+A[1][1]+A[2][2]
- CASE Inverse: det = a(ei-fh)-b(di-fg)+c(dh-eg); inv[i][j] = cofactor/det
- 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.
- START
- Declare str[5][40], n=5
- INPUT 5 strings
- CASE Sort: Bubble sort comparing strings (strcmp without library: char by char)
- CASE Largest: Compare each string with max; if greater update max
- CASE Smallest: Compare each string with min; if smaller update min
- CASE Search: Compare key with each string; char by char
- 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.
- START
- FUNCTION power(a, b): result=1
- FOR i=1 to b: result = result * a
- RETURN result
- In main: INPUT a, b
- PRINT power(a, b)
- 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.
- START
- Define function demo() with static int s=0 and auto int a=0
- s++; a++; PRINT s and a
- In main: Call demo() 3 times
- Observe: static s retains value, auto a resets each call
- 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.
- START
- Declare global variable x = 100
- In function show(): PRINT global x
- In function modify(): local x = 50; PRINT local x
- In main: PRINT global x; call modify(); call show(); PRINT global x
- Observe: local x in modify() doesn't affect global x
- 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.
- START
- Define separate functions: factorial(n), fibonacci(n), sinSeries(x,n), expSeries(x,n)
- In main: INPUT choice; use switch to call appropriate function
- factorial: returns long, iterative loop
- fibonacci: prints series using loop
- sinSeries: x - x³/3! + x⁵/5! - ... using loop
- expSeries: 1 + x + x²/2! + ... using loop
- STOP
/* 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.
- START
- recursive_factorial(n): IF n==0 RETURN 1 ELSE RETURN n*factorial(n-1)
- recursive_fib(n): IF n<=1 RETURN n ELSE RETURN fib(n-1)+fib(n-2)
- factorial_helper(n): returns n! = n * (n-1)!
- sum_natural(n): IF n==0 RETURN 0 ELSE RETURN n + sum_natural(n-1)
- 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.
- START
- FUNCTION classify(ch):
- IF ch >= '0' && ch <= '9': RETURN "Digit"
- ELIF ch >= 'A' && ch <= 'Z': RETURN "Uppercase"
- ELIF ch >= 'a' && ch <= 'z': RETURN "Lowercase"
- ELSE: RETURN "Special"
- In main: FOR i=0 to 9: INPUT char c; PRINT classify(c)
- 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.
- START
- INPUT matrix A[3][3] and B[3][3]
- CASE Add: C[i][j] = A[i][j] + B[i][j]
- CASE Sub: C[i][j] = A[i][j] - B[i][j]
- CASE Mul: C[i][j] = Σ A[i][k]*B[k][j] for k=0..2
- CASE Transpose: T[i][j] = A[j][i]
- CASE Diagonal: sum = A[0][0]+A[1][1]+A[2][2]
- CASE Inverse: det = a(ei-fh)-b(di-fg)+c(dh-eg); inv[i][j] = cofactor/det
- 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.
- START
- INPUT string
- CASE Count: count=0; WHILE s[i]!='\0' count++
- CASE Copy: FOR each char: dest[i]=src[i]; dest[i]='\0'
- CASE Palindrome: reverse copy; compare char by char
- CASE Vowels/Consonants: check each char against aeiou
- CASE Sort: bubble sort on char array
- 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.
- START
- INPUT n, array a[n]
- CASE Sort: Bubble Sort – FOR i=0 to n-2: FOR j=0 to n-i-2: IF a[j]>a[j+1] swap
- CASE Linear Search: FOR each element IF a[i]==key: found
- CASE Binary Search: Sort first; low=0, high=n-1
- WHILE low <= high: mid=(low+high)/2
- IF a[mid]==key: found; ELIF a[mid]<key: low=mid+1; ELSE high=mid-1
- 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.
- START
- INPUT 5 strings into arr[5][40]
- MENU choice = 1-Sort, 2-Largest, 3-Smallest, 4-Search
- IF choice == 1, sort strings and display
- ELSE IF choice == 2, find largest string and display
- ELSE IF choice == 3, find smallest string and display
- ELSE IF choice == 4, search string and display result
- 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.
- START
- Define STRUCT Student with: roll, name, sub1, sub2, sub3, maxmarks, minmarks, obtmarks
- Declare struct variable s1
- Read roll, name, subject names, marks
- Calculate: total = sub1+sub2+sub3; avg = total/3; percent = (total/maxmarks)*100
- Display: roll, name, subjects, marks, total, average, percentage, result (Pass/Fail)
- 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.
- START
- Define STRUCT Date with: dd, mm, yy
- Define STRUCT Employee with: name, emp_id, doj (of type struct Date)
- Declare struct Employee variable e1
- Read employee name, id, date of joining (dd, mm, yy)
- Display all employee details with formatted date
- 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.
- START
- Define STRUCT Student (roll, name, marks)
- Declare ARRAY of 3 struct Student
- FOR i=0 to 2: Read roll, name, marks for each student
- Display menu: 1-Show all results, 2-Search by roll
- IF choice==1: Display all students' data
- ELSE IF choice==2: Read roll number and display that student's data
- 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.
- START
- Define STRUCT complex with: real, imag
- Read two complex numbers c1, c2
- Menu: 1-Add, 2-Subtract, 3-Multiply, 4-Divide
- FOR Add: result.real = c1.real + c2.real; result.imag = c1.imag + c2.imag
- FOR Subtract: result.real = c1.real - c2.real; result.imag = c1.imag - c2.imag
- FOR Multiply: (a+bi)*(c+di) = (ac-bd) + (ad+bc)i
- FOR Divide: Use conjugate method
- Display result in form: real +/- imag i
- 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.
- START
- Define UNION Emp with: one int, one float, one char[20]
- Declare union variable e
- Assign value to e.i (int)
- Display: e.i, size of union, address of e
- Assign value to e.f (float) - overwrites e.i
- Display: e.f, e.i (now corrupted)
- Assign value to e.s (string) - overwrites e.f
- Display: e.s, e.f (now corrupted)
- 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.
- START
- Define ENUM DaysOfWeek with: SUNDAY=0 to SATURDAY=6
- Declare enum variable day
- Assign values and display day names corresponding to enum values
- Use switch to print day name for each enum value
- 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.
- START
- Read two numbers a, b
- Display: Original a, b
- Call swapByValue(a, b) - values copied, original unchanged
- Display: After call by value (no change)
- Call swapByReference(&a, &b) - addresses passed, original changed
- Display: After call by reference (swapped)
- 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.
- START
- Define STRUCT Node with: data (int), *next pointer to Node
- Create nodes dynamically using malloc
- Link nodes: n1->next = n2, n2->next = n3, n3->next = NULL
- Traverse list from head using while(temp != NULL)
- Print each node's data
- Free all allocated memory
- 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).
- START
- Check command line: argc must be >= 3
- Open source file argv[1] for reading
- Open destination file argv[2] for writing
- Read character by character from source
- IF current char is space AND previous was space, skip
- ELSE write character to destination
- Close both files
- 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".
- START
- Open file "data" for reading
- Initialize count = 0
- Read integers from file while not EOF
- IF number % 2 == 0, increment count
- Close file and display 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.
- START
- Open file for reading
- Initialize: tabs=0, newlines=0, chars=0, spaces=0
- Read each character using fgetc()
- IF ch == '\t', increment tabs
- ELSE IF ch == '\n', increment newlines
- ELSE IF ch == ' ', increment spaces
- ELSE increment chars
- Display all counts
- 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).
- START
- Open inventory file for reading
- Read: item_number, rate, quantity
- Initialize: total_cost = 0
- Display all items with quantity > 5
- Calculate and add to total_cost = rate * quantity
- Display total cost of entire inventory
- Close file
- 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