Course Overview
This course is designed to provide complete knowledge of the C programming language. Students will develop logical thinking skills that enable them to create programs and applications in C. Mastering the fundamental programming constructs also makes it easier to switch to any other programming language in the future.
Target Audience
Students from other allied disciplines (Minor Course)
Credits
Theory: 3 Credits (45 Hours)
Practical: 1 Credit (30 Hours)
Focus
Problem solving, algorithm design, structured programming, and real-life applications
Course Objective
The course aims to equip learners with a thorough understanding of C language so that they can:
- Develop strong problem-solving skills using top-down design principles
- Design simple algorithms and draw flowcharts
- Translate algorithms into working C programs
- Organize code using functional hierarchical decomposition
- Solve real-life problems by writing simple yet effective C programs
Course Learning Outcomes
After successful completion of the course, a student will be able to:
- Develop problem solving skills coupled with top-down design principles.
- Become skilled at developing simple algorithms and flow charts.
- Convert the algorithms into simple C programs.
- Understand code organization and functional hierarchical decomposition.
- Develop simple C programs for solving real life problems.
Top-Down Design Visualized
Syllabus Structure 45 Hours
| Unit | Topics | Hours |
|---|---|---|
| 1 | Introduction, Character sets, Keywords, Identifiers, Constants, Variables, Data Types, Program Structure, Operators (Arithmetic, Relational, Logical, Assignment, Increment, Decrement, Conditional), Operator Precedence, Expressions, Type conversion, Formatted I/O | 15 |
| 2 | Conditional statements, Branching and looping, Arrays | 15 |
| 3 | Functions (arguments, return values, recursion), String handling, Enumerated data types, Structures, Arrays of structures, Arrays within structures, Unions | 10 |
| 4 | File handling: Opening, Closing, I/O operations | 5 |
1. Introduction to C
Basic Structure of a C Program
Every C program follows a standard structure. Comments help others (and your future self) understand the code.
/*
* File : hello.c
* Purpose: Demonstrate the basic structure of a C program
* Author : COMP 4021 Student
*/
#include <stdio.h> /* Preprocessor directive:
Includes the Standard Input/Output library
so we can use printf() and scanf() */
/* Optional: Global variables or function prototypes can go here */
int main(void) { /* main() is the entry point of every C program.
'void' means main takes no arguments.
Returns an int (exit status to the OS). */
/* ----- Variable declarations (must come before statements in older C) ----- */
int age = 20; /* Integer variable initialized to 20 */
float height = 5.9f; /* Floating-point variable (f suffix = float literal) */
char grade = 'A'; /* Character variable storing a single character */
/* ----- Executable statements ----- */
printf("Hello, World!\n"); /* \n = newline character */
printf("Age : %d\n", age); /* %d = format specifier for int */
printf("Height : %.1f\n", height); /* %.1f = float with 1 decimal place */
printf("Grade : %c\n", grade); /* %c = format specifier for char */
return 0; /* Returning 0 tells the operating system that the program
ended successfully. Non-zero usually means an error. */
}
Directives] --> B[Global Declarations] B --> C[main function] C --> D[Local Variables] D --> E[Statements] E --> F[return] style C fill:#2b6cb0,color:#fff
Character Set
Letters (A–Z, a–z), Digits (0–9), Special symbols (+ - * / = < > ! & | etc.), and White spaces (space, tab, newline).
Keywords & Identifiers
- Keywords: Reserved words with special meaning (
int,float,if,while,return,for,switch,case,break,continue,void,struct,union,enum, etc.). Cannot be used as identifiers. - Identifiers: Names given to variables, functions, arrays, etc. Rules:
- Must start with a letter (A–Z / a–z) or underscore (
_) - Can contain letters, digits, and underscores
- Case-sensitive (
Age≠age) - Cannot be a keyword
- Must start with a letter (A–Z / a–z) or underscore (
Constants, Variables & Data Types
| Type | Size (typical) | Range / Example | Format Specifier |
|---|---|---|---|
char | 1 byte | −128 to 127 | %c |
int | 2 or 4 bytes | −32,768 to 32,767 (2 bytes) | %d or %i |
float | 4 bytes | ±3.4e−38 to ±3.4e+38 | %f |
double | 8 bytes | ±1.7e−308 to ±1.7e+308 | %lf |
void | — | No value | — |
/* Examples of variable declarations and initializations */
int count = 0; /* Integer, starts at zero */
float pi = 3.14159f; /* Approximate value of π */
double bigNum = 1.7e10; /* Scientific notation: 1.7 × 10^10 */
char ch = 'Z'; /* Single character in single quotes */
const int MAX = 100; /* Constant – value cannot be changed later */
2. Operators in C
Categories of Operators
- Arithmetic:
+-*/%(modulus – remainder) - Relational:
==!=<><=>=(result is 1 for true, 0 for false) - Logical:
&&(AND)||(OR)!(NOT) - Assignment:
=+=-=*=/=%= - Increment / Decrement:
++--(prefix & postfix) - Conditional (Ternary):
condition ? expr1 : expr2
/* Demonstrating different operators with clear comments */
#include <stdio.h>
int main(void) {
int a = 10, b = 3;
int result;
/* Arithmetic operators */
result = a + b; /* addition → 13 */
result = a - b; /* subtraction → 7 */
result = a * b; /* multiplication → 30 */
result = a / b; /* integer division→ 3 (fractional part discarded) */
result = a % b; /* modulus → 1 (remainder of 10/3) */
/* Increment / Decrement */
a++; /* postfix: use current value, THEN increment a */
++a; /* prefix : increment a FIRST, then use new value */
b--; /* postfix decrement */
--b; /* prefix decrement */
/* Relational & Logical (often used inside if / while) */
if (a > b && a != 0) { /* true only if BOTH conditions are true */
printf("a is positive and greater than b\n");
}
/* Ternary operator – compact if-else */
int max = (a > b) ? a : b; /* if a > b then max = a else max = b */
/* Compound assignment */
a += 5; /* same as: a = a + 5; */
b *= 2; /* same as: b = b * 2; */
return 0;
}
Operator Precedence (High → Low)
(a + b) * c is clearer than relying on precedence.
Type Conversion
- Implicit (Automatic): Smaller type is promoted to larger type in mixed expressions.
- Explicit (Casting): You force a conversion using
(type)expression.
int x = 5, y = 2;
float result;
result = x / y; /* Integer division → 2.0 (truncated) */
result = (float)x / y; /* Cast x to float first → 2.5 (correct) */
/* Another example */
double d = 3.7;
int i = (int)d; /* Explicit cast: fractional part is discarded → i becomes 3 */
3. Conditional Statements, Branching & Looping
Decision Making
/* if – else if – else ladder */
#include <stdio.h>
int main(void) {
int marks;
printf("Enter marks (0-100): ");
scanf("%d", &marks); /* &marks = address of variable marks */
if (marks >= 90) {
printf("Grade: A+\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else if (marks >= 40) {
printf("Grade: D\n");
} else {
printf("Grade: F (Fail)\n");
}
return 0;
}
/* switch – useful when you have many discrete choices */
#include <stdio.h>
int main(void) {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break; /* break is REQUIRED, otherwise fall-through occurs */
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default: /* executed if none of the cases match */
printf("Invalid day number!\n");
}
return 0;
}
Loops
| Loop | When to Use | Syntax Sketch |
|---|---|---|
for |
Known number of iterations | for(init; cond; update) |
while |
Condition checked before body | while(cond) { ... } |
do-while |
Body executes at least once | do { ... } while(cond); |
/* for loop – print numbers 1 to 5 */
#include <stdio.h>
int main(void) {
int i;
/* for (initialization; condition; update) */
for (i = 1; i <= 5; i++) {
printf("%d ", i); /* prints: 1 2 3 4 5 */
}
printf("\n");
return 0;
}
/* while loop – sum of digits of a number */
#include <stdio.h>
int main(void) {
int num, sum = 0, digit;
printf("Enter a positive integer: ");
scanf("%d", &num);
while (num > 0) { /* continue as long as digits remain */
digit = num % 10; /* extract last digit */
sum = sum + digit; /* add it to sum */
num = num / 10; /* remove the last digit */
}
printf("Sum of digits = %d\n", sum);
return 0;
}
/* do-while – menu that runs at least once */
#include <stdio.h>
int main(void) {
int choice;
do {
printf("\n--- Menu ---\n");
printf("1. Option A\n");
printf("2. Option B\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
/* process choice here ... */
} while (choice != 3); /* loop continues until user chooses 3 */
printf("Goodbye!\n");
return 0;
}
4. Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations. Indexing starts from 0.
/* 1-D array example – storing and processing marks */
#include <stdio.h>
int main(void) {
/* Declaration + initialization */
int marks[5] = {85, 90, 78, 92, 88}; /* size 5, indices 0 to 4 */
int i;
int sum = 0;
float average;
/* Access and print each element */
printf("Marks: ");
for (i = 0; i < 5; i++) {
printf("%d ", marks[i]); /* marks[0], marks[1], ... */
sum += marks[i]; /* accumulate sum */
}
printf("\n");
average = (float)sum / 5; /* cast to float for accurate division */
printf("Average = %.2f\n", average);
return 0;
}
/* 2-D array (matrix) example */
#include <stdio.h>
int main(void) {
/* 3 rows × 3 columns matrix */
int matrix[3][3] = {
{1, 2, 3}, /* row 0 */
{4, 5, 6}, /* row 1 */
{7, 8, 9} /* row 2 */
};
int i, j;
printf("Matrix:\n");
for (i = 0; i < 3; i++) { /* outer loop = rows */
for (j = 0; j < 3; j++) { /* inner loop = columns */
printf("%d ", matrix[i][j]);
}
printf("\n"); /* new line after each row */
}
return 0;
}
- Array name represents the base address (address of the first element).
- Accessing an index outside 0 … size−1 causes undefined behaviour.
- When you pass an array to a function, only the address is passed (call by reference).
5. Functions & Recursion
Functions enable modular programming and hierarchical decomposition. They improve readability and reusability.
/*
* Function demonstration:
* - Function prototype (declaration)
* - Function definition
* - Function call
* - Return value
*/
#include <stdio.h>
/* Function prototype – tells the compiler about the function before it is used */
int add(int a, int b); /* takes two ints, returns an int */
void printMessage(void); /* takes nothing, returns nothing */
int main(void) {
int x = 5, y = 7;
int sum;
printMessage(); /* call a void function */
sum = add(x, y); /* call add() and store the returned value */
printf("Sum of %d and %d is %d\n", x, y, sum);
return 0;
}
/* Function definition of add */
int add(int a, int b) {
/* a and b are local copies of the arguments (call by value) */
return a + b; /* return the result to the caller */
}
/* Function definition of printMessage */
void printMessage(void) {
printf("Welcome to functions in C!\n");
/* no return statement needed for void functions */
}
Argument Passing
- Call by Value: A copy of the argument is passed. Changes inside the function do not affect the original variable.
- Call by Reference (using pointers): The address is passed; the function can modify the original variable.
/* Call by value vs Call by reference (using pointers) */
#include <stdio.h>
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
/* Only local copies are swapped – originals remain unchanged */
}
void swapByReference(int *a, int *b) { /* *a means "value at address a" */
int temp = *a;
*a = *b;
*b = temp;
/* Original variables are modified because we work with their addresses */
}
int main(void) {
int x = 10, y = 20;
printf("Before any swap: x = %d, y = %d\n", x, y);
swapByValue(x, y);
printf("After swapByValue: x = %d, y = %d (unchanged)\n", x, y);
swapByReference(&x, &y); /* pass addresses using & operator */
printf("After swapByReference: x = %d, y = %d (swapped!)\n", x, y);
return 0;
}
Recursion
A function that calls itself (directly or indirectly). It must have a base case that stops the recursion.
/* Factorial using recursion */
#include <stdio.h>
long factorial(int n) {
/* Base case – stops the recursion */
if (n <= 1) {
return 1;
}
/* Recursive case – function calls itself with a smaller argument */
return n * factorial(n - 1);
}
int main(void) {
int num = 5;
printf("Factorial of %d = %ld\n", num, factorial(num));
/* Calculation: 5 * 4 * 3 * 2 * 1 = 120 */
return 0;
}
6. String Handling
In C, a string is a null-terminated (\0) character array. The null character marks the end of the string.
/* Common string operations */
#include <stdio.h>
#include <string.h> /* required for strlen, strcpy, strcat, strcmp, etc. */
int main(void) {
char name[50] = "Alice"; /* automatically adds '\0' at the end */
char city[30];
char full[80];
/* Copy a string */
strcpy(city, "Mumbai"); /* city now contains "Mumbai\0" */
/* Concatenate (join) two strings */
strcpy(full, name); /* full = "Alice" */
strcat(full, " from "); /* full = "Alice from " */
strcat(full, city); /* full = "Alice from Mumbai" */
/* Length (does NOT count the '\0') */
printf("Length of name = %zu\n", strlen(name)); /* 5 */
/* Compare two strings (returns 0 if equal) */
if (strcmp(name, "Alice") == 0) {
printf("Names match!\n");
}
printf("Full string: %s\n", full);
return 0;
}
Common Library Functions (string.h)
strlen(s)– returns length of stringsstrcpy(dest, src)– copiessrcintodeststrcat(dest, src)– appendssrcto the end ofdeststrcmp(s1, s2)– comparess1ands2(0 = equal)strchr(s, ch)– finds first occurrence of characterchstrstr(s, sub)– finds first occurrence of substringsub
7. Structures, Unions & Enumerated Types
Structure
A user-defined type that groups variables of different types under one name.
/* Defining and using a structure */
#include <stdio.h>
#include <string.h>
/* Define a new data type called "struct Student" */
struct Student {
int roll; /* member 1 */
char name[50]; /* member 2 */
float marks; /* member 3 */
};
int main(void) {
/* Declare a variable of type struct Student */
struct Student s1;
/* Assign values to members using the dot operator */
s1.roll = 101;
strcpy(s1.name, "Riya Sharma");
s1.marks = 92.5f;
/* Access and print members */
printf("Roll : %d\n", s1.roll);
printf("Name : %s\n", s1.name);
printf("Marks : %.1f\n", s1.marks);
/* Initialization at declaration time */
struct Student s2 = {102, "Amit Patel", 88.0f};
return 0;
}
Array of Structures & Nested Structures
/* Array of structures + structure inside structure */
#include <stdio.h>
struct Date {
int day;
int month;
int year;
};
struct Employee {
int id;
char name[40];
struct Date joining; /* nested structure */
};
int main(void) {
/* Array of 3 employees */
struct Employee staff[3] = {
{1001, "Neha", {15, 6, 2022}},
{1002, "Raj", {1, 1, 2023}},
{1003, "Sara", {20, 3, 2021}}
};
int i;
for (i = 0; i < 3; i++) {
printf("%s joined on %02d-%02d-%d\n",
staff[i].name,
staff[i].joining.day,
staff[i].joining.month,
staff[i].joining.year);
}
return 0;
}
Union
Similar syntax to a structure, but all members share the same memory location. Only one member is valid at a time. Useful for saving memory.
/* Union example – only one member is active at a time */
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main(void) {
union Data d;
d.i = 42;
printf("d.i = %d\n", d.i); /* valid */
d.f = 3.14f; /* overwrites the previous value */
printf("d.f = %.2f\n", d.f); /* valid now */
/* d.i is no longer reliable */
return 0;
}
Enumerated Data Type
/* enum – gives meaningful names to integer constants */
#include <stdio.h>
enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
/* By default: MON=0, TUE=1, WED=2, ... SUN=6 */
int main(void) {
enum Weekday today = WED;
if (today == WED) {
printf("It is Wednesday!\n");
}
/* You can also assign explicit values */
enum Status { FAIL = 0, PASS = 1, DISTINCTION = 2 };
return 0;
}
8. File Handling 5 Hours
Files allow permanent storage of data beyond the lifetime of a program.
fopen] --> B{Success?} B -->|Yes| C[Read / Write
fscanf / fprintf
fgetc / fputc ...] C --> D[Close File
fclose] B -->|No| E[Error Handling] style A fill:#2b6cb0,color:#fff style D fill:#38a169,color:#fff
/* Basic file writing and reading */
#include <stdio.h>
#include <stdlib.h> /* for exit() */
int main(void) {
FILE *fp; /* FILE is a special type defined in stdio.h */
int num;
/* ---------- Writing to a file ---------- */
fp = fopen("data.txt", "w"); /* "w" = write mode (creates/overwrites) */
if (fp == NULL) { /* Always check if fopen succeeded */
printf("Error: Cannot open file for writing\n");
exit(1); /* terminate program with error code */
}
fprintf(fp, "Hello File Handling!\n");
fprintf(fp, "Number: %d\n", 42);
fclose(fp); /* Always close the file when done */
printf("Data written successfully.\n");
/* ---------- Reading from a file ---------- */
fp = fopen("data.txt", "r"); /* "r" = read mode */
if (fp == NULL) {
printf("Error: Cannot open file for reading\n");
exit(1);
}
char line[100];
while (fgets(line, sizeof(line), fp) != NULL) { /* read line by line */
printf("Read: %s", line);
}
fclose(fp);
return 0;
}
Common File Modes
"r"– open for reading (file must exist)"w"– open for writing (creates new / truncates existing)"a"– open for appending (writes at the end)"r+","w+","a+"– update modes (read + write)
fopen(). Always call fclose() when you finish with a file.
C Language Practical — Complete Solutions 30 Hours
Credit: 01 | Fully solved programs with detailed comments for every practical.
.c file, compile with gcc filename.c -o out and run ./out.
Read the comments carefully — they explain the logic step by step.
1. Sum and Product of Digits of an Integer
/* Practical 1: Sum and Product of digits of an integer */
#include <stdio.h>
int main(void) {
int num, digit;
int sum = 0; /* running sum of digits */
int product = 1; /* running product of digits */
int original; /* keep original number for display */
printf("Enter an integer: ");
scanf("%d", &num);
original = num;
/* Handle negative numbers by taking absolute value */
if (num < 0) num = -num;
/* Special case: number is 0 */
if (num == 0) {
sum = 0;
product = 0;
} else {
while (num > 0) {
digit = num % 10; /* extract last digit */
sum += digit; /* add to sum */
product *= digit; /* multiply to product */
num = num / 10; /* remove last digit */
}
}
printf("Number : %d\n", original);
printf("Sum : %d\n", sum);
printf("Product : %d\n", product);
return 0;
}
2. Reverse a Number
/* Practical 2: Reverse the digits of a number */
#include <stdio.h>
int main(void) {
int num, reversed = 0, digit;
printf("Enter an integer: ");
scanf("%d", &num);
int original = num;
int isNegative = 0;
if (num < 0) { /* remember sign */
isNegative = 1;
num = -num;
}
while (num > 0) {
digit = num % 10; /* take last digit */
reversed = reversed * 10 + digit; /* append it to reversed */
num = num / 10;
}
if (isNegative) reversed = -reversed;
printf("Original : %d\n", original);
printf("Reversed : %d\n", reversed);
return 0;
}
3. Sum of Series S = 1 + 1/2 + 1/3 + … + 1/n
/* Practical 3: Harmonic series sum */
#include <stdio.h>
int main(void) {
int n, i;
double sum = 0.0; /* use double for fractional accuracy */
printf("Enter n (number of terms): ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
sum += 1.0 / i; /* 1.0 forces floating-point division */
}
printf("Sum of first %d terms = %.6f\n", n, sum);
return 0;
}
4. Sum of Series S = 1 − 2 + 3 − 4 + 5 − …
/* Practical 4: Alternating sum series */
#include <stdio.h>
int main(void) {
int n, i;
int sum = 0;
printf("Enter n (number of terms): ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
if (i % 2 == 0)
sum -= i; /* even terms are subtracted */
else
sum += i; /* odd terms are added */
}
printf("Sum of first %d terms = %d\n", n, sum);
return 0;
}
5. Check whether a String is Palindrome
/* Practical 5: Palindrome check using a function */
#include <stdio.h>
#include <string.h>
#include <ctype.h> /* for tolower – optional case-insensitive check */
/* Returns 1 if s is palindrome, 0 otherwise */
int isPalindrome(char s[]) {
int left = 0;
int right = strlen(s) - 1;
while (left < right) {
if (s[left] != s[right])
return 0; /* mismatch found */
left++;
right--;
}
return 1; /* all characters matched */
}
int main(void) {
char str[100];
printf("Enter a string: ");
scanf("%s", str); /* reads until first space */
if (isPalindrome(str))
printf("\"%s\" is a Palindrome.\n", str);
else
printf("\"%s\" is NOT a Palindrome.\n", str);
return 0;
}
6. Prime Check + Generate Primes < 100
/* Practical 6: isPrime function + list primes less than 100 */
#include <stdio.h>
/* Returns 1 if n is prime, 0 otherwise */
int isPrime(int n) {
int i;
if (n <= 1) return 0;
if (n <= 3) return 1;
if (n % 2 == 0 || n % 3 == 0) return 0;
/* Check from 5 to sqrt(n) in steps of 6 */
for (i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return 0;
}
return 1;
}
int main(void) {
int num, i;
printf("Enter a number to check prime: ");
scanf("%d", &num);
if (isPrime(num))
printf("%d is Prime.\n", num);
else
printf("%d is NOT Prime.\n", num);
printf("\nPrime numbers less than 100:\n");
for (i = 2; i < 100; i++) {
if (isPrime(i))
printf("%d ", i);
}
printf("\n");
return 0;
}
7. Factors of a Given Number
/* Practical 7: Print all factors of a number */
#include <stdio.h>
int main(void) {
int num, i;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num <= 0) {
printf("Please enter a positive integer.\n");
return 1;
}
printf("Factors of %d are: ", num);
for (i = 1; i <= num; i++) {
if (num % i == 0)
printf("%d ", i);
}
printf("\n");
return 0;
}
8. Macro that Swaps Two Numbers
/* Practical 8: Swap using a macro */
#include <stdio.h>
/* Macro to swap two variables of the same type.
Uses a temporary variable of the same type as x. */
#define SWAP(x, y) do { \
typeof(x) temp = (x); \
(x) = (y); \
(y) = temp; \
} while (0)
/* Portable version without typeof (works in any C compiler) */
#define SWAP_INT(a, b) do { \
int temp = (a); \
(a) = (b); \
(b) = temp; \
} while (0)
int main(void) {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
SWAP_INT(x, y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
9. Triangle of Stars
/* Practical 9: Print a triangle of stars
*
***
*****
******* (odd number of stars per row) */
#include <stdio.h>
int main(void) {
int lines, i, j;
printf("Enter number of lines: ");
scanf("%d", &lines);
for (i = 1; i <= lines; i++) {
/* print (2*i - 1) stars */
for (j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
printf("\n");
}
return 0;
}
10. Menu-Driven Array Operations
/* Practical 10: Full menu-driven array program */
#include <stdio.h>
#define MAX 100
void printEven(int a[], int n) {
int i, found = 0;
printf("Even elements: ");
for (i = 0; i < n; i++)
if (a[i] % 2 == 0) { printf("%d ", a[i]); found = 1; }
if (!found) printf("None");
printf("\n");
}
void printOdd(int a[], int n) {
int i, found = 0;
printf("Odd elements: ");
for (i = 0; i < n; i++)
if (a[i] % 2 != 0) { printf("%d ", a[i]); found = 1; }
if (!found) printf("None");
printf("\n");
}
void sumAvg(int a[], int n) {
int i, sum = 0;
for (i = 0; i < n; i++) sum += a[i];
printf("Sum = %d, Average = %.2f\n", sum, (float)sum / n);
}
void maxMin(int a[], int n) {
int i, mx = a[0], mn = a[0];
for (i = 1; i < n; i++) {
if (a[i] > mx) mx = a[i];
if (a[i] < mn) mn = a[i];
}
printf("Maximum = %d, Minimum = %d\n", mx, mn);
}
int removeDuplicates(int a[], int n) {
int i, j, k;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; ) {
if (a[i] == a[j]) {
for (k = j; k < n - 1; k++) a[k] = a[k + 1];
n--;
} else {
j++;
}
}
}
return n; /* new size */
}
void reverseArray(int a[], int n) {
int i, temp;
for (i = 0; i < n / 2; i++) {
temp = a[i];
a[i] = a[n - 1 - i];
a[n - 1 - i] = temp;
}
}
void printArray(int a[], int n) {
int i;
printf("Array: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
}
int main(void) {
int a[MAX], n = 0, choice, i;
do {
printf("\n===== ARRAY MENU =====\n");
printf("1. Enter / Re-enter array\n");
printf("2. Print even elements\n");
printf("3. Print odd elements\n");
printf("4. Sum and Average\n");
printf("5. Maximum and Minimum\n");
printf("6. Remove duplicates\n");
printf("7. Reverse array\n");
printf("8. Print array\n");
printf("9. Quit\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter size (1-%d): ", MAX);
scanf("%d", &n);
if (n < 1 || n > MAX) { printf("Invalid size\n"); n = 0; break; }
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
break;
case 2: if (n) printEven(a, n); else printf("Array empty\n"); break;
case 3: if (n) printOdd(a, n); else printf("Array empty\n"); break;
case 4: if (n) sumAvg(a, n); else printf("Array empty\n"); break;
case 5: if (n) maxMin(a, n); else printf("Array empty\n"); break;
case 6:
if (n) {
n = removeDuplicates(a, n);
printf("Duplicates removed. New size = %d\n", n);
printArray(a, n);
} else printf("Array empty\n");
break;
case 7:
if (n) { reverseArray(a, n); printArray(a, n); }
else printf("Array empty\n");
break;
case 8: if (n) printArray(a, n); else printf("Array empty\n"); break;
case 9: printf("Goodbye!\n"); break;
default: printf("Invalid choice\n");
}
} while (choice != 9);
return 0;
}
11. Alphabet Occurrence Table (Command-line Arguments)
/* Practical 11: Count frequency of each alphabet in command-line text
Compile: gcc prog.c -o prog
Run : ./prog Hello World → counts letters in "HelloWorld" */
#include <stdio.h>
#include <ctype.h> /* isalpha, tolower */
int main(int argc, char *argv[]) {
int freq[26] = {0}; /* index 0 = 'a', 1 = 'b', ... */
int i, j;
char c;
if (argc < 2) {
printf("Usage: %s <text...>\n", argv[0]);
return 1;
}
/* Process every argument */
for (i = 1; i < argc; i++) {
for (j = 0; argv[i][j] != '\0'; j++) {
c = tolower(argv[i][j]);
if (isalpha(c))
freq[c - 'a']++;
}
}
printf("Alphabet Count\n");
printf("---------------\n");
for (i = 0; i < 26; i++) {
if (freq[i] > 0)
printf(" %c %d\n", 'a' + i, freq[i]);
}
return 0;
}
12. Swap Two Numbers Using Pointers
/* Practical 12: Swap using pointers */
#include <stdio.h>
void swap(int *p, int *q) {
int temp = *p; /* *p means "value pointed to by p" */
*p = *q;
*q = temp;
}
int main(void) {
int a = 5, b = 9;
printf("Before: a = %d, b = %d\n", a, b);
swap(&a, &b); /* pass addresses */
printf("After : a = %d, b = %d\n", a, b);
return 0;
}
13. Function that Alters Variables via Addresses
/* Practical 13: Modify two variables through their addresses */
#include <stdio.h>
void alter(int *x, int *y) {
*x = *x + 10; /* increase first variable by 10 */
*y = *y * 2; /* double the second variable */
}
int main(void) {
int a = 5, b = 7;
printf("Before: a = %d, b = %d\n", a, b);
alter(&a, &b);
printf("After : a = %d, b = %d\n", a, b);
/* Expected: a = 15, b = 14 */
return 0;
}
14. Area & Circumference of Circle (pass radius to function)
/* Practical 14: Compute area & circumference, display from main */
#include <stdio.h>
#define PI 3.1415926535
void compute(float radius, float *area, float *circum) {
*area = PI * radius * radius;
*circum = 2 * PI * radius;
}
int main(void) {
float r, area, circum;
printf("Enter radius: ");
scanf("%f", &r);
compute(r, &area, &circum); /* pass addresses so function can fill them */
printf("Area = %.4f\n", area);
printf("Circumference = %.4f\n", circum);
return 0;
}
15. Menu-Driven String Operations
/* Practical 15: Comprehensive string menu */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void showAddresses(char *s) {
int i;
for (i = 0; s[i] != '\0'; i++)
printf("s[%d] = '%c' address = %p\n", i, s[i], (void*)&s[i]);
}
void concatManual(char *dest, char *src) {
while (*dest) dest++; /* move to end of dest */
while (*src) *dest++ = *src++; /* copy src */
*dest = '\0';
}
int lengthPtr(char *s) {
char *p = s;
while (*p) p++;
return p - s;
}
void toUpperStr(char *s) {
while (*s) { *s = toupper(*s); s++; }
}
void toLowerStr(char *s) {
while (*s) { *s = tolower(*s); s++; }
}
int countVowels(char *s) {
int c = 0;
while (*s) {
char ch = tolower(*s);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') c++;
s++;
}
return c;
}
void reverseStr(char *s) {
int i, n = strlen(s);
for (i = 0; i < n/2; i++) {
char t = s[i];
s[i] = s[n-1-i];
s[n-1-i] = t;
}
}
int main(void) {
char s1[200] = "", s2[100] = "";
int choice;
do {
printf("\n===== STRING MENU =====\n");
printf("1. Enter string(s)\n");
printf("2. Show address of each character\n");
printf("3. Concatenate (without strcat)\n");
printf("4. Concatenate (with strcat)\n");
printf("5. Compare two strings\n");
printf("6. Length (using pointers)\n");
printf("7. Convert to UPPERCASE\n");
printf("8. Convert to lowercase\n");
printf("9. Count vowels\n");
printf("10. Reverse string\n");
printf("11. Quit\n");
printf("Choice: ");
scanf("%d", &choice);
getchar(); /* consume leftover newline */
switch (choice) {
case 1:
printf("Enter first string: ");
fgets(s1, sizeof(s1), stdin);
s1[strcspn(s1, "\n")] = 0; /* remove newline */
printf("Enter second string (for concat/compare): ");
fgets(s2, sizeof(s2), stdin);
s2[strcspn(s2, "\n")] = 0;
break;
case 2: showAddresses(s1); break;
case 3: {
char temp[300];
strcpy(temp, s1);
concatManual(temp, s2);
printf("Result: %s\n", temp);
break;
}
case 4: {
char temp[300];
strcpy(temp, s1);
strcat(temp, s2);
printf("Result: %s\n", temp);
break;
}
case 5: {
int cmp = strcmp(s1, s2);
if (cmp == 0) printf("Strings are equal\n");
else if (cmp < 0) printf("\"%s\" < \"%s\"\n", s1, s2);
else printf("\"%s\" > \"%s\"\n", s1, s2);
break;
}
case 6: printf("Length = %d\n", lengthPtr(s1)); break;
case 7: toUpperStr(s1); printf("Now: %s\n", s1); break;
case 8: toLowerStr(s1); printf("Now: %s\n", s1); break;
case 9: printf("Vowels = %d\n", countVowels(s1)); break;
case 10: reverseStr(s1); printf("Reversed: %s\n", s1); break;
case 11: printf("Bye!\n"); break;
default: printf("Invalid\n");
}
} while (choice != 11);
return 0;
}
16. Merge Two Ordered Arrays
/* Practical 16: Merge two sorted arrays into one sorted array */
#include <stdio.h>
void merge(int a[], int n1, int b[], int n2, int result[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (a[i] <= b[j])
result[k++] = a[i++];
else
result[k++] = b[j++];
}
/* copy remaining elements */
while (i < n1) result[k++] = a[i++];
while (j < n2) result[k++] = b[j++];
}
int main(void) {
int a[] = {1, 3, 5, 7, 9};
int b[] = {2, 4, 6, 8, 10, 12};
int n1 = 5, n2 = 6;
int result[20];
int i;
merge(a, n1, b, n2, result);
printf("Merged array: ");
for (i = 0; i < n1 + n2; i++)
printf("%d ", result[i]);
printf("\n");
return 0;
}
17. Fibonacci Series (Recursion + Iteration)
/* Practical 17: Fibonacci – recursive and iterative */
#include <stdio.h>
/* Recursive version – returns nth Fibonacci number (0-indexed: 0,1,1,2,3,5,...) */
int fibRec(int n) {
if (n <= 1) return n;
return fibRec(n - 1) + fibRec(n - 2);
}
/* Iterative version – prints first n terms */
void fibIter(int n) {
int a = 0, b = 1, next, i;
if (n >= 1) printf("%d ", a);
if (n >= 2) printf("%d ", b);
for (i = 3; i <= n; i++) {
next = a + b;
printf("%d ", next);
a = b;
b = next;
}
printf("\n");
}
int main(void) {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci (Iteration): ");
fibIter(n);
printf("Fibonacci (Recursion): ");
for (i = 0; i < n; i++)
printf("%d ", fibRec(i));
printf("\n");
return 0;
}
18. Factorial (Recursion + Iteration)
/* Practical 18: Factorial – both methods */
#include <stdio.h>
long factRec(int n) {
if (n <= 1) return 1;
return n * factRec(n - 1);
}
long factIter(int n) {
long f = 1;
int i;
for (i = 2; i <= n; i++)
f *= i;
return f;
}
int main(void) {
int n;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial not defined for negative numbers.\n");
return 1;
}
printf("Factorial (Recursion) = %ld\n", factRec(n));
printf("Factorial (Iteration) = %ld\n", factIter(n));
return 0;
}
19. GCD (Recursion + Iteration)
/* Practical 19: GCD – Euclidean algorithm both ways */
#include <stdio.h>
int gcdRec(int a, int b) {
if (b == 0) return a;
return gcdRec(b, a % b);
}
int gcdIter(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int main(void) {
int x, y;
printf("Enter two positive integers: ");
scanf("%d %d", &x, &y);
printf("GCD (Recursion) = %d\n", gcdRec(x, y));
printf("GCD (Iteration) = %d\n", gcdIter(x, y));
return 0;
}
20. Matrix Operations (Sum, Difference, Product, Transpose)
/* Practical 20: Menu-driven matrix operations (2-D arrays) */
#include <stdio.h>
#define N 10 /* maximum dimension */
void readMatrix(int m[][N], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
scanf("%d", &m[i][j]);
}
void printMatrix(int m[][N], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%5d", m[i][j]);
printf("\n");
}
}
void add(int a[][N], int b[][N], int r[][N], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
r[i][j] = a[i][j] + b[i][j];
}
void subtract(int a[][N], int b[][N], int r[][N], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
r[i][j] = a[i][j] - b[i][j];
}
void multiply(int a[][N], int b[][N], int r[][N],
int r1, int c1, int c2) {
int i, j, k;
for (i = 0; i < r1; i++)
for (j = 0; j < c2; j++) {
r[i][j] = 0;
for (k = 0; k < c1; k++)
r[i][j] += a[i][k] * b[k][j];
}
}
void transpose(int a[][N], int t[][N], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
t[j][i] = a[i][j];
}
int main(void) {
int a[N][N], b[N][N], r[N][N];
int r1, c1, r2, c2, choice;
printf("Enter rows and columns of Matrix A: ");
scanf("%d %d", &r1, &c1);
printf("Enter elements of A:\n");
readMatrix(a, r1, c1);
printf("Enter rows and columns of Matrix B: ");
scanf("%d %d", &r2, &c2);
printf("Enter elements of B:\n");
readMatrix(b, r2, c2);
do {
printf("\n1.Sum 2.Difference 3.Product 4.Transpose(A) 5.Quit\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (r1==r2 && c1==c2) {
add(a, b, r, r1, c1);
printf("A + B =\n"); printMatrix(r, r1, c1);
} else printf("Order mismatch\n");
break;
case 2:
if (r1==r2 && c1==c2) {
subtract(a, b, r, r1, c1);
printf("A - B =\n"); printMatrix(r, r1, c1);
} else printf("Order mismatch\n");
break;
case 3:
if (c1 == r2) {
multiply(a, b, r, r1, c1, c2);
printf("A * B =\n"); printMatrix(r, r1, c2);
} else printf("Cannot multiply (c1 != r2)\n");
break;
case 4:
transpose(a, r, r1, c1);
printf("Transpose of A =\n"); printMatrix(r, c1, r1);
break;
case 5: printf("Bye\n"); break;
default: printf("Invalid\n");
}
} while (choice != 5);
return 0;
}
21. Area of Rectangle, Square, Circle & Triangle (Menu)
/* Practical 21: Menu-driven area calculator */
#include <stdio.h>
#define PI 3.14159
float areaRect(float l, float b) { return l * b; }
float areaSquare(float s) { return s * s; }
float areaCircle(float r) { return PI * r * r; }
float areaTriangle(float b, float h){ return 0.5f * b * h; }
int main(void) {
int choice;
float a, b, result;
do {
printf("\n1.Rectangle 2.Square 3.Circle 4.Triangle 5.Exit\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Length & Breadth: ");
scanf("%f %f", &a, &b);
result = areaRect(a, b);
printf("Area = %.2f\n", result);
break;
case 2:
printf("Side: ");
scanf("%f", &a);
result = areaSquare(a);
printf("Area = %.2f\n", result);
break;
case 3:
printf("Radius: ");
scanf("%f", &a);
result = areaCircle(a);
printf("Area = %.2f\n", result);
break;
case 4:
printf("Base & Height: ");
scanf("%f %f", &a, &b);
result = areaTriangle(a, b);
printf("Area = %.2f\n", result);
break;
case 5: printf("Exit\n"); break;
default: printf("Invalid\n");
}
} while (choice != 5);
return 0;
}
22–24. Simple Fibonacci / Factorial (already covered above)
These are simplified versions of Practicals 17 and 18. Use the same code.
25. Sum of Series 1 − 2/2! + 3/3! − 4/4! + … ± n/n!
/* Practical 25: Series 1 - 2/2! + 3/3! - 4/4! + ... */
#include <stdio.h>
/* Compute n! */
double factorial(int n) {
double f = 1.0;
int i;
for (i = 2; i <= n; i++) f *= i;
return f;
}
int main(void) {
int n, i;
double sum = 0.0, term;
printf("Enter number of terms: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
term = i / factorial(i);
if (i % 2 == 0)
sum -= term; /* even position → subtract */
else
sum += term; /* odd position → add */
}
printf("Sum of series = %.8f\n", sum);
return 0;
}
26. Sum and Product of Two Compatible Matrices
/* Practical 26: Matrix sum and product (compatible check) */
#include <stdio.h>
#define N 10
void readMat(int m[][N], int r, int c) {
int i, j;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &m[i][j]);
}
void printMat(int m[][N], int r, int c) {
int i, j;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) printf("%5d", m[i][j]);
printf("\n");
}
}
int main(void) {
int a[N][N], b[N][N], sum[N][N], prod[N][N];
int r1, c1, r2, c2, i, j, k;
printf("Order of Matrix A (rows cols): ");
scanf("%d %d", &r1, &c1);
printf("Elements of A:\n");
readMat(a, r1, c1);
printf("Order of Matrix B (rows cols): ");
scanf("%d %d", &r2, &c2);
printf("Elements of B:\n");
readMat(b, r2, c2);
/* Sum – same order required */
if (r1 == r2 && c1 == c2) {
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("\nSum of matrices:\n");
printMat(sum, r1, c1);
} else {
printf("\nCannot add – different orders.\n");
}
/* Product – c1 must equal r2 */
if (c1 == r2) {
for (i = 0; i < r1; i++)
for (j = 0; j < c2; j++) {
prod[i][j] = 0;
for (k = 0; k < c1; k++)
prod[i][j] += a[i][k] * b[k][j];
}
printf("\nProduct of matrices:\n");
printMat(prod, r1, c2);
} else {
printf("\nCannot multiply – incompatible orders (c1 != r2).\n");
}
return 0;
}
Course Hours Distribution
Visual breakdown of the 45-hour theory component:
Topic Coverage Weight
Quick Reference – Common Patterns
Reading input & printing
int n;
float f;
char str[50];
scanf("%d", &n); /* read integer – note the & */
scanf("%f", &f); /* read float */
scanf("%s", str); /* read string (no spaces) – no & needed for arrays */
fgets(str, 50, stdin); /* safer way to read a whole line (including spaces) */
printf("Integer: %d\n", n);
printf("Float : %.2f\n", f);
printf("String : %s\n", str);
Looping over an array
int arr[5] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
Simple function with return value
/* Returns the larger of two integers */
int max(int a, int b) {
return (a > b) ? a : b; /* ternary operator used for brevity */
}
/* Usage */
int bigger = max(15, 27); /* bigger becomes 27 */
Checking a prime number (useful for practicals)
int isPrime(int n) {
int i;
if (n <= 1) return 0; /* 0 and 1 are not prime */
if (n <= 3) return 1; /* 2 and 3 are prime */
/* Check divisibility from 2 up to sqrt(n) */
for (i = 2; i * i <= n; i++) {
if (n % i == 0)
return 0; /* divisible → not prime */
}
return 1; /* no divisors found → prime */
}