Nearby lessons

124 of 124

C - Program Examples

A collection of complete C programs from every chapter — copy any program, compile it with GCC, and watch it run. Each example shows its output.

The Structure of a C Program

Every C program follows a simple structure. Learn this skeleton and every program fits into it:

In simple words: every C program has the same skeleton — #include <stdio.h> brings in ready-made tools, main() is where the program starts, and the real instructions live inside { }.

The four parts inside main() are not compulsory, but they are the natural order of thinking.

PartWhat it does
#include <stdio.h>Brings in ready-made functions (printf, scanf) from the stdio header file.
void main()The starting point of the program. Execution always begins here.
{ }The body of main() — all the actual instructions live here.
;Every statement in C ends with a semicolon.
Example01
CCode Cell
1#include <stdio.h> // header file - gives us printf, scanf
2 
3void main() // main() - every program starts here
4{
5 // 1. declaration part - tell C what variables you need
6 // 2. input part - take data from the user
7 // 3. processing part - do the calculations
8 // 4. output part - show the result
9}

How a C Program Runs — Three Stages

A C program does not run directly. It passes through these stages:

  • Write the program in a file called program.c.
  • Compile it — the compiler (like GCC) checks for errors and converts your code into object code.
  • Link it — the linker joins your object code with the ready-made library functions (like printf).
  • Execute — the resulting .exe file runs and shows the output.
Example02
CCode Cell
1Program.c (source code you write)
2 |
3 COMPILER (cc / gcc)
4 |
5Program.obj / Program.o (object code)
6 |
7 LINKER (adds library code)
8 |
9 Program.exe (executable - runs)

How a C Program Runs — Three Stages

Trainer's Note: Memory trick: W-C-L-R — Write, Compile, Link, Run. Or remember "We Compile Like Runners". You only type the Write step; the compiler and linker silently do the middle two for you.
Example03
CCode Cell
1C:\> gcc program.c -o program // compile + link
2C:\> program // run
3Hello World

Your First C Program

printf(...) is the function that prints text on the screen. The \n inside the quotes means move to a new line.

Trainer's Note: Some modern compilers prefer int main() with a return 0; at the end. Both void main() and int main() are accepted in exams and college work — int main() is the modern standard. We show the classic form because this material follows the classic textbook.
Example04
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 printf("Hello, welcome to C!\n");
6}
Output
Hello, welcome to C!

A Slightly Bigger Example — Adding Two Numbers

Notice %d — it is a format specifier that tells printf where to print the integer sum. We study format specifiers properly in Chapter 4.

In simple words: %d is a placeholder. printf sees %d, goes to the value sum, and prints it exactly in that place. Change the value, and the same printf line prints the new number.
Example05
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10; // declaration + initialization
6 int b = 20;
7 int sum;
8 
9 sum = a + b; // processing
10 printf("Sum = %d\n", sum); // output
11}
Output
Sum = 30

Program: the four constant types

Example06
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age = 20; // integer constant
6 float pi = 3.14; // real (floating) constant
7 char grade = 'A'; // character constant
8 char msg[] = "Hello, C"; // string constant
9 
10 printf("Integer constant : %d\n", age);
11 printf("Real constant : %.2f\n", pi);
12 printf("Character constant : %c\n", grade);
13 printf("String constant : %s\n", msg);
14}
Output
Integer constant : 20 Real constant : 3.14 Character constant : A String constant : Hello, C

Program: declare, assign, change, print

The naming rules (with valid and invalid examples)

RuleValidInvalid
Start with a letter or underscore_total, sum9marks (starts with digit)
No spaces or special symbols insidetotal_markstotal marks, a#b
Cannot be a keywordstudentint, if, for
C is case sensitivesum, Sum, SUM all different
Example07
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age; // declaration - make a box named age
6 age = 20; // assignment - put 20 inside
7 printf("Age is %d\n", age); // 20
8 
9 age = 25; // change the value
10 printf("Now age is %d\n", age); // 25
11}
Output

Age is 20
Now age is 25
      

Program 1: int (whole numbers)

Example08
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age = 20;
6 int year = 2026;
7 
8 printf("Age : %d\n", age);
9 printf("Year : %d\n", year);
10 printf("Sum : %d\n", age + year); // 2046
11}
Output

Age  : 20
Year : 2026
Sum  : 2046
      

Program 2: float (decimal numbers)

Example09
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 float marks = 87.5;
6 float percent = marks / 100;
7 
8 printf("Marks : %.2f\n", marks);
9 printf("Percent : %.2f\n", percent);
10}
Output

Marks     : 87.50
Percent   : 0.88
      

Program 3: double (more precision)

Example10
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 double price = 99.991234567;
6 double total = price * 2;
7 
8 printf("Price : %.6lf\n", price);
9 printf("Total : %.6lf\n", total);
10}
Output

Price : 99.991235
Total : 199.982469
      

Program 4: char (one character)

Trainer's Note: Size trick: char is always 1 byte (holds one character). int is the standard whole number. Use float for simple decimals and double when you need very accurate decimals (like scientific calculations).
Example11
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 char grade = 'A';
6 char symbol = '5';
7 
8 printf("Grade : %c\n", grade);
9 printf("Symbol : %c\n", symbol);
10}
Output

Grade  : A
Symbol : 5
      

Declaration and Initialization

Declaration tells C the type and name. Initialization gives a value at the time of declaration.

Example12
CCode Cell
1int a, b, c; // declare three integers
2int total = 0; // declare and initialize
3float salary = 5000.50;
4char ch = 'A';

Program: declaration styles in action

Example13
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a, b, c; // declaration only
6 int total = 0; // declaration + initialization
7 float salary = 5000.50;
8 char ch = 'A';
9 
10 a = 10; b = 20; c = 30; // assign later
11 total = a + b + c;
12 
13 printf("Total : %d\n", total);
14 printf("Salary : %.2f\n", salary);
15 printf("Char : %c\n", ch);
16}
Output

Total  : 60
Salary : 5000.50
Char   : A
      

Program: size of every basic type

Trainer's Note: Sizes can change with the compiler and operating system. On 64-bit Linux, long is usually 8 bytes; on Windows it is 4 bytes (as shown above). That is exactly why sizeof exists — it prints the truth for your machine. char is the one type the C language fixes: it is always 1 byte.
Example14
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 printf("int : %d bytes\n", sizeof(int));
6 printf("float : %d bytes\n", sizeof(float));
7 printf("double : %d bytes\n", sizeof(double));
8 printf("char : %d byte\n", sizeof(char)); // char is always 1 byte
9 printf("short : %d bytes\n", sizeof(short));
10 printf("long : %d bytes\n", sizeof(long));
11}
Output

int    : 4 bytes
float  : 4 bytes
double : 8 bytes
char   : 1 byte
short  : 2 bytes
long   : 4 bytes
      

What is an Operator?

An operator is a symbol that performs an operation on values (called operands). An expression is a combination of operators and operands that gives a value.

In simple words: an operator is the verb (it does the action) and the operands are the nouns (the values it acts on). a + b means a and b are the operands, + is the operator.
Example15
CCode Cell
1sum = a + b; // + and = are operators; a, b are operands
2x = a + b * c; // an expression

Program: all five arithmetic operators

Example16
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 7, b = 2;
6 
7 printf("a = %d, b = %d\n", a, b);
8 printf("Addition : %d\n", a + b); // 9
9 printf("Subtraction : %d\n", a - b); // 5
10 printf("Multiplication : %d\n", a * b); // 14
11 printf("Division (int) : %d\n", a / b); // 3 (decimal dropped)
12 printf("Remainder (%%): %d\n", a % b); // 1
13 printf("Division (float): %.2f\n", 7.0 / 2); // 3.50
14}
Output

a = 7, b = 2
Addition       : 9
Subtraction    : 5
Multiplication : 14
Division (int) : 3
Remainder (%): 1
Division (float): 3.50
      

Program: all six relational operators

Example17
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10, b = 20;
6 
7 printf("%d == %d : %d\n", a, b, a == b); // 0
8 printf("%d != %d : %d\n", a, b, a != b); // 1
9 printf("%d < %d : %d\n", a, b, a < b); // 1
10 printf("%d > %d : %d\n", a, b, a > b); // 0
11 printf("%d <= %d : %d\n", a, b, a <= b); // 1
12 printf("%d >= %d : %d\n", a, b, a >= b); // 0
13}
Output

10 == 20 : 0
10 != 20 : 1
10 <  20 : 1
10 >  20 : 0
10 <= 20 : 1
10 >= 20 : 0
      

Program: AND, OR and NOT

Example18
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age = 25, marks = 80;
6 
7 printf("AND: age>18 && marks>70 : %d\n", age > 18 && marks > 70); // 1
8 printf("AND: age<18 && marks>70 : %d\n", age < 18 && marks > 70); // 0
9 printf("OR : age<18 || marks>70 : %d\n", age < 18 || marks > 70); // 1
10 printf("OR : age<18 || marks<40 : %d\n", age < 18 || marks < 40); // 0
11 printf("NOT: !(age > 18) : %d\n", !(age > 18)); // 0
12 printf("NOT: !(age > 30) : %d\n", !(age > 30)); // 1
13}
Output

AND: age>18 && marks>70  : 1
AND: age<18 && marks>70  : 0
OR : age<18 || marks>70  : 1
OR : age<18 || marks<40  : 0
NOT: !(age > 18)         : 0
NOT: !(age > 30)         : 1
      

Program: every shortcut operator

Example19
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 
7 a += 5; printf("after a += 5 : %d\n", a); // 15
8 a -= 3; printf("after a -= 3 : %d\n", a); // 12
9 a *= 2; printf("after a *= 2 : %d\n", a); // 24
10 a /= 4; printf("after a /= 4 : %d\n", a); // 6
11 a %= 4; printf("after a %%= 4 : %d\n", a); // 2
12}
Output

after a += 5 : 15
after a -= 3 : 12
after a *= 2 : 24
after a /= 4 : 6
after a %= 4 : 2
      

Program 1: pre-increment vs post-increment

Example20
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 
7 printf("a is %d\n", a); // 10
8 printf("a++ prints %d\n", a++); // 10 (print first, then add)
9 printf("now a is %d\n", a); // 11
10 printf("++a prints %d\n", ++a); // 12 (add first, then print)
11}
Output
a is 10 a++ prints 10 now a is 11 ++a prints 12

Program 2: pre-decrement vs post-decrement

Example21
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 
7 printf("a-- prints %d\n", a--); // 10 (print first, then subtract)
8 printf("now a is %d\n", a); // 9
9 printf("--a prints %d\n", --a); // 8 (subtract first, then print)
10}
Output
a-- prints 10 now a is 9 --a prints 8

Conditional (Ternary) Operator (?:)

This is a one-line shortcut for a simple if-else. It picks one of two values based on a condition.

In simple words: the ternary operator asks one yes/no question and hands you one of two answers. Read ? as "then" and : as "otherwise": marks >= 40 ? 'P' : 'F' → "if marks ≥ 40 then 'P', otherwise 'F'".
Example22
CCode Cell
1condition ? value_if_true : value_if_false

Program: check pass or fail

Example23
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks = 60;
6 char result;
7 
8 result = (marks >= 40) ? 'P' : 'F';
9 printf("Result: %c\n", result); // P
10 
11 int a = 10, b = 20;
12 int bigger = (a > b) ? a : b;
13 printf("Bigger of %d and %d is %d\n", a, b, bigger); // 20
14}
Output

Result: P
Bigger of 10 and 20 is 20
      

Operator Precedence — What Runs First

When an expression has many operators, C follows a fixed priority order. The higher-precedence operator runs first. See it live in one program:

Example24
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int x, y;
6 
7 x = 2 + 3 * 4; // 3*4 first = 12, then 2+12
8 printf("2 + 3 * 4 = %d\n", x); // 14
9 
10 y = (2 + 3) * 4; // brackets first: 5*4
11 printf("(2 + 3) * 4 = %d\n", y); // 20
12 
13 int z = 10 + 5 > 12; // 10+5 = 15, then 15 > 12
14 printf("10 + 5 > 12 = %d\n", z); // 1
15}
Output

2 + 3 * 4  = 14
(2 + 3) * 4 = 20
10 + 5 > 12 = 1
      

Operator Precedence — What Runs First

Trainer's Note: Trainer tip: never rely on memory for precedence. When in doubt, use brackets `( )` — they make your intention clear and avoid bugs. a + (b * c) is easier to read than hoping C does the right thing.
Example25
CCode Cell
1Priority (high to low):
21. ( ) brackets
32. * / %
43. + -
54. < <= > >=
65. == !=
76. &&
87. ||
98. = (assignment) - lowest

printf() — Printing Output

printf("text", values...) prints text, and any % format specifiers inside the text are replaced by the values.

In simple words: printf is a fill-in-the-blanks printer. It prints the text, and wherever it sees a %d or %f, it fills that blank with your value — in the same order you give them.

The most important format specifiers

SpecifierPrints
%dInteger (int)
%fFloat with decimal places
%.2fFloat with exactly 2 decimal places
%cOne character
%sString (text)
%ldLong integer
%lfDouble (in scanf)
%xInteger in hexadecimal
Example26
CCode Cell
1printf("My age is %d and my marks are %f", age, marks);

printf() — Printing Output

Example27
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age = 20;
6 float marks = 87.5;
7 char grade = 'A';
8 char name[] = "Rahul";
9 
10 printf("Name : %s\n", name);
11 printf("Age : %d\n", age);
12 printf("Marks : %.2f\n", marks);
13 printf("Grade : %c\n", grade);
14}
Output
Name : Rahul Age : 20 Marks : 87.50 Grade : A

Program: escape sequences in action

Example28
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 printf("Name\tMarks\n"); // tab between columns
6 printf("Rahul\t87\n");
7 printf("Priya\t95\n");
8 printf("I said \"Hello\" \\ done\n"); // quotes and backslash
9 printf("Percent sign: %%\n"); // prints %
10}
Output

Name	Marks
Rahul	87
Priya	95
I said "Hello" \ done
Percent sign: %
      

scanf() — Taking Input

scanf("specifiers", &variables...) reads input from the keyboard. Important: you must put & before a variable (except for strings) so scanf knows where to store the value.

In simple words: scanf is the mirror image of `printf` — printf sends values to the screen, scanf receives them from the keyboard. Same specifiers, same order — but scanf needs a & before every variable (except strings).
Trainer's Note: The & (address of) operator is essential in scanf: scanf("%d", &age) stores the input at age's memory location. Beginners often forget & — the program then compiles but crashes or gives a garbage value. For strings (%s), you do not use &.
Example29
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age;
6 float salary;
7 
8 printf("Enter your age: ");
9 scanf("%d", &age);
10 
11 printf("Enter your salary: ");
12 scanf("%f", &salary);
13 
14 printf("Age = %d, Salary = %.2f\n", age, salary);
15}
Output

Enter your age: 20
Enter your salary: 5000.50
Age = 20, Salary = 5000.50
      

Reading and Writing Single Characters

  • getchar() — reads one character from the keyboard.
  • putchar(c) — prints one character.
Trainer's Note: The classic textbook also uses getch() and getche() (from conio.h) — but those are Windows-only functions and not part of standard C. Modern practice is to use getchar() (standard) or the safer fgets() for strings, which we see in Chapter 8.
Example30
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 char ch;
6 printf("Enter one character: ");
7 ch = getchar();
8 printf("You typed: ");
9 putchar(ch);
10 printf("\n");
11}
Output
Enter one character: A You typed: A

A Complete Example — Calculate Simple Interest

Example31
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 float p, r, t, si;
6 
7 printf("Enter principal, rate, time: ");
8 scanf("%f %f %f", &p, &r, &t);
9 
10 si = (p * r * t) / 100;
11 
12 printf("Simple Interest = %.2f\n", si);
13}
Output

Enter principal, rate, time: 10000 8 2
Simple Interest = 1600.00
      

The if Statement

Example32
CCode Cell
1if (condition) {
2 // statements that run when condition is true
3}

The if Statement

If the condition is true, the block runs; if false, it is skipped entirely.

Example33
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks = 55;
6 if (marks >= 40) {
7 printf("Pass\n");
8 }
9}
Output
Pass

The if-else Statement

Example34
CCode Cell
1if (condition) {
2 // runs when true
3} else {
4 // runs when false
5}

The if-else Statement

In simple words: if-else is a fork in the road — exactly two paths. The if path runs when the condition is true, the else path runs when it is false. One of the two always runs, never both.
Example35
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int age;
6 printf("Enter age: ");
7 scanf("%d", &age);
8 
9 if (age >= 18) {
10 printf("Eligible to vote\n");
11 } else {
12 printf("Not eligible to vote\n");
13 }
14}
Output
Enter age: 20 Eligible to vote

The if-else-if Ladder

When there are more than two choices, chain else if blocks. Only the first true condition's block runs; the rest are skipped.

In simple words: the ladder checks from top to bottom and stops at the first true condition — the rest of the ladder is ignored. The final else catches the case where nothing above was true.
Example36
CCode Cell
1if (condition1) {
2 // block 1
3} else if (condition2) {
4 // block 2
5} else if (condition3) {
6 // block 3
7} else {
8 // default - when none are true
9}

The if-else-if Ladder

Example37
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks;
6 printf("Enter marks: ");
7 scanf("%d", &marks);
8 
9 if (marks >= 90) printf("Grade A\n");
10 else if (marks >= 75) printf("Grade B\n");
11 else if (marks >= 60) printf("Grade C\n");
12 else if (marks >= 40) printf("Grade D\n");
13 else printf("Fail\n");
14}
Output
Enter marks: 80 Grade B

Program: check result and attendance together

Example38
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks = 55, attendance = 80;
6 
7 if (marks >= 40) {
8 if (attendance >= 75) {
9 printf("Pass with good attendance\n");
10 } else {
11 printf("Pass but short attendance\n");
12 }
13 } else {
14 printf("Fail\n");
15 }
16}
Output
Pass with good attendance

The switch Statement

switch is perfect when one value is compared against many fixed constants (like a menu). It jumps straight to the matching case.

In simple words: switch is a menu — the expression is the order, each case is one dish, and break means "that's all, I'm done". It jumps straight to the matching dish instead of checking every option in order.
Example39
CCode Cell
1switch (expression) {
2 case value1: statements; break;
3 case value2: statements; break;
4 ...
5 default: statements;
6}

The switch Statement

Trainer's Note: The break is essential in switch — without it, execution falls through to the next case. The default case is optional and runs when nothing matches. Also remember: switch works with integer and character expressions, not floats or strings.
Example40
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int day;
6 printf("Enter day number (1-3): ");
7 scanf("%d", &day);
8 
9 switch (day) {
10 case 1: printf("Monday\n"); break;
11 case 2: printf("Tuesday\n"); break;
12 case 3: printf("Wednesday\n"); break;
13 default: printf("Other day\n");
14 }
15}
Output

Enter day number (1-3): 2
Tuesday
      

Program: ternary in action

Example41
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks = 60;
6 char result;
7 
8 result = (marks >= 40) ? 'P' : 'F'; // same as if-else
9 printf("Result: %c\n", result); // P
10}
Output
Result: P

The while Loop

Example42
CCode Cell
1while (condition) {
2 // body repeats while the condition is true
3}

The while Loop

The while loop checks the condition first, then runs the body. If the condition is false from the start, the body runs zero times.

In simple words: while is "check the door, then enter" — if the door is locked from the start, you never enter. The body may run zero times.
Example43
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i = 1;
6 while (i <= 5) {
7 printf("%d ", i);
8 i++; // important - otherwise the loop never ends
9 }
10}
Output

1 2 3 4 5 
      

The do-while Loop

The do-while loop runs the body first, then checks the condition. So its body runs at least once even if the condition is false.

In simple words: do-while is "enter first, then check the door" — you get inside at least once, then the condition decides whether you come back in.
Example44
CCode Cell
1do {
2 // body
3} while (condition);

The do-while Loop

Here the user is asked again and again until a positive number comes — the do-while is perfect for ask-at-least-once situations.

Example45
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int n;
6 do {
7 printf("Enter a positive number: ");
8 scanf("%d", &n);
9 } while (n <= 0); // repeat until positive
10 
11 printf("You entered %d\n", n);
12}

The for Loop

The for loop gathers three things in one line: where to start, when to stop, and how to move forward.

In simple words: for puts the whole plan in one line — start, stop, step. Read for (i = 1; i <= 5; i++) as "i starts at 1, keep going while i ≤ 5, add 1 each round".
Example46
CCode Cell
1for (start; condition; update) {
2 // body
3}

The for Loop

Example47
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i;
6 for (i = 1; i <= 5; i++) {
7 printf("%d ", i);
8 }
9}
Output

1 2 3 4 5 
      

The for Loop

Example48
CCode Cell
1for (i = 1; i <= 5; i++) // start=1, condition i<=5, update i++
2 | | |
3 start stop step

Program: The classic textbook examples: print even numbers, print a multiplication table, sum of first n numbers.

Example49
CCode Cell
1// Table of 5
2for (int i = 1; i <= 10; i++) {
3 printf("5 x %d = %d\n", i, 5 * i);
4}
Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
      

break and continue

  • break — immediately stops the loop completely.
  • continue — skips the rest of the current round and jumps to the next round.
Trainer's Note: Memory trick: break = the emergency exit — it leaves the building. continue = skipping a turn in a game — the game keeps going, you just miss one round.
Example50
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i;
6 for (i = 1; i <= 5; i++) {
7 if (i == 3) break; // stop at 3
8 printf("%d ", i);
9 }
10 printf("\n---\n");
11 for (i = 1; i <= 5; i++) {
12 if (i == 3) continue; // skip 3
13 printf("%d ", i);
14 }
15}
Output

1 2 
---
1 2 4 5 
      

Nested Loops

A loop inside a loop is a nested loop. For each round of the outer loop, the inner loop runs completely. Nested loops build patterns:

Trainer's Note: The secret of pattern programs: outer loop = number of rows, inner loop = what is printed in each row. Change the inner condition and you change the whole pattern.
Example51
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i, j;
6 for (i = 1; i <= 3; i++) { // outer loop - rows
7 for (j = 1; j <= i; j++) { // inner loop - stars in a row
8 printf("* ");
9 }
10 printf("\n");
11 }
12}
Output

* 
* * 
* * * 
      

Program A: print even numbers up to 20

Example52
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i;
6 for (i = 2; i <= 20; i = i + 2) {
7 printf("%d ", i);
8 }
9 printf("\n");
10}
Output

2 4 6 8 10 12 14 16 18 20 
      

Program B: sum of first n numbers

Example53
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int n, i, sum = 0;
6 
7 printf("Enter n: ");
8 scanf("%d", &n);
9 
10 for (i = 1; i <= n; i++) {
11 sum = sum + i;
12 }
13 printf("Sum = %d\n", sum);
14}
Output

Enter n: 5
Sum = 15
      

Program C: reverse a number

Example54
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int n, rev = 0;
6 
7 printf("Enter a number: ");
8 scanf("%d", &n);
9 
10 while (n > 0) {
11 rev = rev * 10 + (n % 10); // take last digit
12 n = n / 10; // remove last digit
13 }
14 printf("Reversed: %d\n", rev);
15}
Output

Enter a number: 12345
Reversed: 54321
      

Program D: factorial with a for loop

Trainer's Note: These four are the most-asked loop programs in exams. The reverse-number program (C) is a favourite — understand how rev = rev * 10 + digit builds the reversed number.
Example55
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int n = 5, i;
6 long fact = 1;
7 
8 for (i = 1; i <= n; i++) {
9 fact = fact * i;
10 }
11 printf("5! = %ld\n", fact);
12}
Output
5! = 120

What is an Array?

An array is a group of variables of the same type, stored one after another in memory, under one name. Each element is reached by its index (position), starting from 0.

In simple words: an array is one row of lockers — the array name is the locker row, and the index is the locker number. In C the lockers are numbered from 0, not 1.
Trainer's Note: Memory trick: index = position − 1. The first element is at index 0, so a 5-element array uses indexes 0 to 4. Forgetting this and using marks[5] goes past the last locker — silent garbage.

Without arrays, storing 100 students' marks means 100 separate variables. With an array, it is just marks[100].

Example56
CCode Cell
1int marks[5]; // an array of 5 integers
2 
3marks[0] = 80; // first element
4marks[1] = 90;
5marks[4] = 75; // last element

Declaring an Array

The size tells C how many elements to reserve. Remember: indexes go from 0 to size-1. So marks[5] has indexes marks[0] to marks[4].

Example57
CCode Cell
1dataType arrayName[size];
2 
3int marks[5]; // 5 integers: marks[0]..marks[4]
4float salaries[10]; // 10 floats
5char name[20]; // 20 characters (a string)

Initializing an Array

If you give fewer values than the size, the remaining elements are filled with 0.

Example58
CCode Cell
1int marks[5] = {80, 90, 75, 60, 88}; // give all values at once
2int a[] = {1, 2, 3, 4}; // size is automatic (4)
3int b[5] = {1, 2}; // rest become 0: {1,2,0,0,0}

Program 1: Read and Print an Array

Example59
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks[5], i;
6 
7 printf("Enter 5 marks: ");
8 for (i = 0; i < 5; i++) {
9 scanf("%d", &marks[i]);
10 }
11 
12 printf("Marks are: ");
13 for (i = 0; i < 5; i++) {
14 printf("%d ", marks[i]);
15 }
16 printf("\n");
17}
Output
Enter 5 marks: 80 90 75 60 88 Marks are: 80 90 75 60 88

Program 2: Sum and Average

Example60
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks[5] = {80, 90, 75, 60, 88};
6 int i, total = 0;
7 
8 for (i = 0; i < 5; i++) {
9 total = total + marks[i];
10 }
11 
12 printf("Sum = %d\n", total);
13 printf("Average = %.2f\n", total / 5.0);
14}
Output

Sum     = 393
Average = 78.60
      

Program 3: Find the Maximum

In simple words: the max program uses a running champion — start with the first element as the champion, then challenge each next element. Whoever is bigger becomes the new champion.
Example61
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks[5] = {80, 90, 75, 60, 88};
6 int i, max = marks[0]; // start with the first element
7 
8 for (i = 1; i < 5; i++) {
9 if (marks[i] > max) max = marks[i];
10 }
11 
12 printf("Maximum = %d\n", max);
13}
Output
Maximum = 90

Program 4: Find the Minimum

Example62
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks[5] = {80, 90, 75, 60, 88};
6 int i, min = marks[0]; // start with the first element
7 
8 for (i = 1; i < 5; i++) {
9 if (marks[i] < min) min = marks[i];
10 }
11 
12 printf("Minimum = %d\n", min);
13}
Output
Minimum = 60

Program 5: Linear Search

Trainer's Note: The search pattern above is called linear search — it checks every element one by one. The trick found = -1 (a value that can never be a valid index) tells us 'not found' at the end.
Example63
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int marks[5] = {80, 90, 75, 60, 88};
6 int key, i, found = -1; // -1 means 'not found'
7 
8 printf("Enter value to search: ");
9 scanf("%d", &key);
10 
11 for (i = 0; i < 5; i++) {
12 if (marks[i] == key) {
13 found = i;
14 break;
15 }
16 }
17 
18 if (found == -1)
19 printf("Not found\n");
20 else
21 printf("Found at index %d\n", found);
22}
Output
Enter value to search: 75 Found at index 2

Program 6: Two-Dimensional Arrays (Read and Print)

A 2D array is like a table of rows and columns. Use nested loops — the outer loop for rows, the inner loop for columns.

In simple words: a 2D array is a table. The first index picks the row, the second picks the column — like a train seat: m[1][2] means row 1, column 2.
Example64
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int m[2][3], i, j;
6 
7 printf("Enter 6 values: \n");
8 for (i = 0; i < 2; i++) {
9 for (j = 0; j < 3; j++) {
10 scanf("%d", &m[i][j]);
11 }
12 }
13 
14 printf("Matrix:\n");
15 for (i = 0; i < 2; i++) {
16 for (j = 0; j < 3; j++) {
17 printf("%d ", m[i][j]);
18 }
19 printf("\n"); // new line after each row
20 }
21}
Output
Enter 6 values: 1 2 3 4 5 6 Matrix: 1 2 3 4 5 6

Program 7: Matrix Addition

Example65
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a[2][2] = {{1, 2}, {3, 4}};
6 int b[2][2] = {{10, 20}, {30, 40}};
7 int c[2][2], i, j;
8 
9 for (i = 0; i < 2; i++) {
10 for (j = 0; j < 2; j++) {
11 c[i][j] = a[i][j] + b[i][j];
12 }
13 }
14 
15 printf("Result matrix:\n");
16 for (i = 0; i < 2; i++) {
17 for (j = 0; j < 2; j++) {
18 printf("%d ", c[i][j]);
19 }
20 printf("\n");
21 }
22}
Output
Result matrix: 11 22 33 44

What is a String in C?

In C, a string is simply an array of characters ending with a special character '\0' (called the null character). This \0 tells C where the string ends.

So a string "Rahul" needs an array of size at least 6 (5 characters + the \0). This is a common beginner mistake — forgetting space for the null character.

In simple words: a string is just a row of characters with a full-stop marker — \0 — at the end. The \0 is invisible; it only tells C "the text ends here".
Trainer's Note: Memory trick: `\0` is not the digit 0 and not the letter O — it is one character that means "end of text". Count it whenever you size a char array: text length + 1.
Example66
CCode Cell
1char name[10] = "Rahul";
2 
3R a h u l \0
4^-----------^-----^
55 real chars null marks the end

Declaring and Initializing Strings

Trainer's Note: "Rahul" (double quotes) is a string — it ends with \0. 'A' (single quotes) is a single character — it has no \0. Do not mix them.
Example67
CCode Cell
1char name[20]; // empty string variable (capacity 20)
2char name[20] = "Rahul"; // initialize with a string
3char name[] = "Rahul"; // size is automatic (6)
4char name[] = {'R','a','h','u','l','\0'}; // as an array of chars

Reading Strings — scanf, gets, fgets

FunctionReadsLimitation
scanf("%s", name)One word (no spaces)Stops at the first space
gets(name)A whole line including spacesUnsafe (no size check) — avoid
fgets(name, size, stdin)A whole line, safelyThe modern safe choice
Trainer's Note: scanf with %s reads only one word — "Rahul Kumar" would store only "Rahul". To read a full line with spaces, use fgets() (modern and safe). The old textbook's gets() is dangerous because it does not check the size — it can overflow memory. Prefer fgets.
Example68
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 char name[30];
6 
7 printf("Enter your name: ");
8 fgets(name, 30, stdin); // safe - reads spaces too
9 
10 printf("Hello %s", name);
11}
Output
Enter your name: Rahul Kumar Hello Rahul Kumar

The String Functions (string.h)

Include #include <string.h> and use these ready-made functions:

FunctionWhat it doesExample
strlen(s)Length (number of characters before \0)strlen("Rahul") → 5
strcpy(dest, src)Copy src into deststrcpy(b, a)
strcat(dest, src)Join src at the end of deststrcat(b, a)
strcmp(a, b)Compare two strings (0 = equal)strcmp(a, b)
strlwr(s)Convert to lowercasestrlwr(s)
strupr(s)Convert to uppercasestrupr(s)
strrev(s)Reverse the stringstrrev(s)
In simple words: <string.h> is a ready-made toolkit for text — strlen measures, strcpy copies, strcat joins, strcmp compares. You write the plan; the toolkit does the heavy work.
Trainer's Note: You cannot compare or copy strings with = and ==. b = a and if (a == b) are WRONG for strings — they compare addresses, not the text. Always use strcpy and strcmp.
Example69
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4void main()
5{
6 char a[20] = "Hello";
7 char b[20];
8 
9 strcpy(b, a); // b becomes "Hello"
10 strcat(b, " World"); // b becomes "Hello World"
11 
12 printf("%s\n", b);
13 printf("Length: %d\n", strlen(b));
14 printf("Compare: %d\n", strcmp(a, "Hello")); // 0 = equal
15}
Output

Hello World
Length: 11
Compare: 0
      

String Basics Without Functions

Understand how it works underneath by doing it with loops (the classic exam approach):

Example70
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 char s[30];
6 int len = 0, i;
7 
8 printf("Enter a string: ");
9 gets(s); // or fgets
10 
11 for (i = 0; s[i] != '\0'; i++) {
12 len++; // count until the null character
13 }
14 printf("Length = %d\n", len);
15 
16 // print it in reverse
17 for (i = len - 1; i >= 0; i--) {
18 printf("%c", s[i]);
19 }
20 printf("\n");
21}

Program A: count vowels in a string

Example71
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 char s[50];
6 int i, vowels = 0;
7 
8 printf("Enter a string: ");
9 gets(s);
10 
11 for (i = 0; s[i] != '\0'; i++) {
12 char c = s[i];
13 if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
14 || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
15 vowels++;
16 }
17 }
18 printf("Vowels = %d\n", vowels);
19}
Output
Enter a string: Balagurusamy Vowels = 5

Program B: reverse a string (without strrev)

Example72
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4void main()
5{
6 char s[50];
7 int i, len;
8 
9 printf("Enter a string: ");
10 gets(s);
11 len = strlen(s);
12 
13 printf("Reversed: ");
14 for (i = len - 1; i >= 0; i--) {
15 printf("%c", s[i]);
16 }
17 printf("\n");
18}
Output
Enter a string: hello Reversed: olleh

Program C: palindrome check

Trainer's Note: These three — count vowels, reverse, palindrome — are the most-asked string programs in exams. Palindrome compares the first character with the last, then the second with the second-last, and so on, moving inward.
Example73
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4void main()
5{
6 char s[50];
7 int start = 0, end, isPal = 1;
8 
9 printf("Enter a string: ");
10 gets(s);
11 end = strlen(s) - 1;
12 
13 while (start < end) {
14 if (s[start] != s[end]) { isPal = 0; break; }
15 start++;
16 end--;
17 }
18 
19 if (isPal) printf("Palindrome\n");
20 else printf("Not a palindrome\n");
21}
Output
Enter a string: madam Palindrome

The Three Parts of a Function

PartWhat it isExample
Function declarationTells C the function exists (before main)int add(int, int);
Function definitionThe actual body of the functionint add(int a, int b) { return a + b; }
Function callUsing the function in mainresult = add(5, 3);
Example74
CCode Cell
1#include <stdio.h>
2 
3int add(int, int); // 1. declaration
4 
5void main()
6{
7 int s = add(5, 3); // 3. call
8 printf("Sum = %d\n", s);
9}
10 
11int add(int a, int b) // 2. definition
12{
13 return a + b;
14}
Output
Sum = 8

Arguments and Return Values

A function can receive values (arguments) and/or return a value back. This gives four combinations:

TypeArgumentsReturn valueExample
1YesYesint add(int a, int b) — returns a + b
2YesNovoid show(int n) — just prints
3NoYesint getNum() — just returns a value
4NoNovoid welcome() — just does something
In simple words: arguments are the message you send to the function; the return value is the reply it sends back. No message (no args) and no reply (void) are both perfectly fine.
Example75
CCode Cell
1#include <stdio.h>
2 
3void welcome(); // no args, no return
4int getNumber(); // no args, returns int
5void showSum(int a, int b); // args, no return
6int add(int a, int b); // args, returns int
7 
8void main()
9{
10 int x = getNumber();
11 showSum(x, 10);
12 printf("add returns: %d\n", add(x, 5));
13}
14 
15void welcome() { printf("Welcome\n"); }
16int getNumber() { return 42; }
17void showSum(int a, int b) { printf("Sum = %d\n", a + b); }
18int add(int a, int b) { return a + b; }

Call by Value

C passes arguments by value — it gives the function a copy of the value. The function can change its copy, but the original in main() is not affected.

In simple words: call by value is like giving someone a photocopy of your exam answer sheet — they can scribble all over the copy, but your original stays untouched.
Trainer's Note: This surprises every beginner: the function changes x, but main's num stays 10, because num's value (a copy) was passed. To let a function change a variable, we pass its address with pointers — that is Chapter 11's topic (call by reference).
Example76
CCode Cell
1#include <stdio.h>
2 
3void change(int x)
4{
5 x = 100; // changes only the copy
6}
7 
8void main()
9{
10 int num = 10;
11 change(num);
12 printf("%d\n", num); // still 10 - original unchanged
13}
Output
10

Return Statement

The return statement does two things: it gives a value back, and it immediately ends the function.

Example77
CCode Cell
1return value; // send a value back and end the function
2return; // just end the function (for void)

Recursion — A Function Calling Itself

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs two parts: a base case (when to stop) and the recursive call (calling itself).

In simple words: recursion is like Russian dolls — a function opens a smaller copy of itself, which opens a smaller one, until the tiniest doll (the base case) is reached, and then the answer passes back up, growing at every step.

How it works: factorial(5) asks factorial(4), which asks factorial(3)... down to factorial(1) = 1, then the answers come back up: 1, 2, 6, 24, 120.

Trainer's Note: Recursion vs loop: anything you do with recursion can be done with a loop too. Recursion makes the code shorter and more elegant for problems like factorial, Fibonacci, and tree structures — but it uses more memory. For beginners, master factorial and Fibonacci with recursion.
Example78
CCode Cell
1#include <stdio.h>
2 
3int factorial(int n) // n! = n * (n-1)!
4{
5 if (n <= 1) return 1; // base case - stop here
6 return n * factorial(n - 1); // recursive call
7}
8 
9void main()
10{
11 printf("%d\n", factorial(5)); // 5*4*3*2*1 = 120
12}
Output
120

Fibonacci with Recursion

Example79
CCode Cell
1#include <stdio.h>
2 
3int fib(int n) // nth Fibonacci number
4{
5 if (n <= 1) return n; // base case: fib(0)=0, fib(1)=1
6 return fib(n - 1) + fib(n - 2);
7}
8 
9void main()
10{
11 int i;
12 for (i = 0; i < 8; i++) {
13 printf("%d ", fib(i));
14 }
15}
Output

0 1 1 2 3 5 8 13 
      

Defining a Structure

This only creates a template (a design). It does not reserve memory. Memory is reserved when we declare variables of this type.

Example80
CCode Cell
1struct student {
2 int rollNo; // member 1
3 char name[30]; // member 2
4 float marks; // member 3
5}; // note the semicolon

Program 1: Declare Variables and Access Members

The dot operator (.) is how you reach a member. It is also called the member access operator.

In simple words: the dot is the "reach into the box" operator. s1.rollNo means open box s1 and pull out the rollNo slot.
Example81
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4struct student {
5 int rollNo;
6 char name[30];
7 float marks;
8};
9 
10void main()
11{
12 struct student s1; // variable of type struct student
13 
14 s1.rollNo = 101; // member access with the dot (.)
15 strcpy(s1.name, "Rahul");
16 s1.marks = 88.5;
17 
18 printf("%d %s %.2f\n", s1.rollNo, s1.name, s1.marks);
19}
Output
101 Rahul 88.50

Program 2: Initializing in One Line

Example82
CCode Cell
1#include <stdio.h>
2 
3struct student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9void main()
10{
11 struct student s1 = {101, "Rahul", 88.5}; // values in order
12 struct student s2 = {102, "Priya", 95.0};
13 
14 printf("%d %s %.2f\n", s1.rollNo, s1.name, s1.marks);
15 printf("%d %s %.2f\n", s2.rollNo, s2.name, s2.marks);
16}
Output

101 Rahul 88.50
102 Priya 95.00
      

Program 3: Take a Student's Data from the User

Example83
CCode Cell
1#include <stdio.h>
2 
3struct student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9void main()
10{
11 struct student s;
12 
13 printf("Enter roll number: ");
14 scanf("%d", &s.rollNo);
15 printf("Enter name: ");
16 scanf("%s", s.name); // note: no & for strings
17 printf("Enter marks: ");
18 scanf("%f", &s.marks);
19 
20 printf("%d %s %.2f\n", s.rollNo, s.name, s.marks);
21}
Output

Enter roll number: 101
Enter name: Rahul
Enter marks: 88.5
101 Rahul 88.50
      

Program 4: Array of Structures (Many Students)

Just like an array of ints, you can have an array of structures — for many students:

Notice the pattern s[i].rollNo — first the index, then the member.

In simple words: an array of structures is a class register — the index picks the student, the member picks the detail. s[2].marks means the marks of student number 2.
Example84
CCode Cell
1#include <stdio.h>
2 
3struct student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9void main()
10{
11 struct student s[3]; // 3 students
12 int i;
13 
14 for (i = 0; i < 3; i++) {
15 printf("Enter roll, name, marks: ");
16 scanf("%d %s %f", &s[i].rollNo, s[i].name, &s[i].marks);
17 }
18 
19 printf("\nStudent details:\n");
20 for (i = 0; i < 3; i++) {
21 printf("%d %s %.2f\n", s[i].rollNo, s[i].name, s[i].marks);
22 }
23}
Output
Enter roll, name, marks: 101 Rahul 88 Enter roll, name, marks: 102 Priya 95 Enter roll, name, marks: 103 Anil 76 Student details: 101 Rahul 88.00 102 Priya 95.00 103 Anil 76.00

Program 5: Nested Structures

A structure can contain another structure. For example, a Student can contain an Address:

Example85
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4struct address {
5 char city[30];
6 int pin;
7};
8 
9struct student {
10 int rollNo;
11 struct address addr; // structure inside a structure
12};
13 
14void main()
15{
16 struct student s;
17 
18 s.rollNo = 101;
19 strcpy(s.addr.city, "Hyderabad"); // reach through both levels
20 s.addr.pin = 500038;
21 
22 printf("Roll: %d\n", s.rollNo);
23 printf("City: %s\n", s.addr.city);
24 printf("Pin : %d\n", s.addr.pin);
25}
Output
Roll: 101 City: Hyderabad Pin : 500038

Program 6: Unions

A union looks like a structure but all its members share the same memory. A union uses only enough memory for its largest member.

PointStructureUnion
MemorySum of all members (each has its own space)Only the largest member (all share one space)
WhenAll members can be used togetherOnly one member is used at a time
Keywordstructunion
AccessDot operator (same)Dot operator (same)
Trainer's Note: Simple memory trick: structure gives every member its own room; union gives one room shared by all members. That is why sizeof(struct) is big but sizeof(union) is just the biggest member. Use unions when you store only one of several types at a time.
Example86
CCode Cell
1#include <stdio.h>
2 
3union value {
4 int i;
5 float f;
6 char c;
7}; // memory = size of the largest member
8 
9void main()
10{
11 union value v;
12 
13 v.i = 10; // uses the space as an int
14 printf("int : %d\n", v.i);
15 
16 v.f = 3.14; // same space now used as a float
17 printf("float : %.2f\n", v.f);
18 
19 printf("Size of union : %d bytes\n", sizeof(v));
20}
Output
int : 10 float : 3.14 Size of union : 4 bytes

What is a Pointer?

Every variable in C lives at some memory address. A pointer is a special variable that stores the address of another variable — it 'points to' that variable.

Think of it like a map that tells you where a house is: p is the map, and &a is the house's location.

In simple words: a normal variable stores a value; a pointer stores a house address. With the address you can go to the house (*p) and read or change what is inside.
Example87
CCode Cell
1int a = 10; // a is stored somewhere in memory
2int *p; // p is a pointer - it will store an address
3p = &a; // p now holds the address of a (points to a)

Program 1: see & and * working

Trainer's Note: Memory trick: `&` reads 'address of', `*` reads 'value at'. So p = &a puts a's address in p, and *p gives back a's value. Beginners often mix them — practise this one program until it is clear.
Example88
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 int *p = &a; // p stores a's address
7 
8 printf("Value of a : %d\n", a); // 10
9 printf("Address of a : %p\n", &a); // some memory address
10 printf("Value of p : %p\n", p); // same address
11 printf("Value at *p : %d\n", *p); // 10 - the value a holds
12}
Output
Value of a : 10 Address of a : 0x7ffe... Value of p : 0x7ffe... Value at *p : 10

Declaring Pointers

The * in the declaration says: this variable is a pointer. The type (int, float, char) tells C what kind of value the pointer points to.

Example89
CCode Cell
1int *ip; // pointer to an integer
2float *fp; // pointer to a float
3char *cp; // pointer to a character

Complete Program 2 — Change a Value Through a Pointer

Using *p you can read or change the value at that address:

Example90
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 int *p = &a;
7 
8 printf("Before: a = %d\n", a); // 10
9 
10 *p = 50; // change the value AT a's address
11 
12 printf("After : a = %d\n", a); // 50 - a changed through the pointer!
13}
Output
Before: a = 10 After : a = 50

Complete Program 3 — Pointers and Arrays

The name of an array is actually the address of its first element. So pointers and arrays are very close friends:

In simple words: the array name is the address of the first locker. So p = a makes p point to locker 0, and *(p + 1) reaches locker 1 — exactly like a[1].
Trainer's Note: Pointer arithmetic follows the type size: p + 1 on an int pointer moves forward by sizeof(int) bytes, not 1 byte. That is why *(p + 1) reaches the next array element correctly.
Example91
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a[5] = {10, 20, 30, 40, 50};
6 int *p = a; // p points to a[0]
7 int i;
8 
9 printf("a[0] via *p : %d\n", *p); // 10
10 printf("a[1] via *(p+1) : %d\n", *(p + 1)); // 20
11 
12 printf("Whole array via pointer: ");
13 for (i = 0; i < 5; i++) {
14 printf("%d ", *(p + i)); // same as a[i]
15 }
16 printf("\n");
17}
Output
a[0] via *p : 10 a[1] via *(p+1) : 20 Whole array via pointer: 10 20 30 40 50

Complete Program 4 — Call by Reference (Swap)

In Chapter 9 we saw call by value (a function gets a copy). With pointers we get call by reference: the function receives the address, so it can change the original variable in main().

The classic swap program is THE exam question for call by reference: without pointers, swap cannot change the original values; with pointers, it can.

PointCall by valueCall by reference
What is passedA copy of the valueThe address of the variable
Function can change original?NoYes
SymbolNormal variable& when calling, * in the function
Use forSimple calculationsSwapping, changing variables, big data (no copy)
In simple words: call by reference sends the house address instead of a photocopy — so the function can walk in and change the original. Call by value could never do that.
Example92
CCode Cell
1#include <stdio.h>
2 
3void swap(int *x, int *y) // receives addresses
4{
5 int temp = *x;
6 *x = *y; // change what x points to
7 *y = temp;
8}
9 
10void main()
11{
12 int a = 10, b = 20;
13 
14 printf("Before swap: a=%d b=%d\n", a, b);
15 swap(&a, &b); // pass addresses
16 printf("After swap : a=%d b=%d\n", a, b); // a=20 b=10
17}
Output

Before swap: a=10 b=20
After swap : a=20 b=10
      

Complete Program 5 — Safe Use with NULL

Always check that a pointer is not NULL before using *p — this avoids the famous segmentation fault (crash) that happens when you dereference a pointer holding an invalid address.

Example93
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 int *p = NULL; // points to nothing - safe starting state
7 
8 if (p != NULL) {
9 printf("%d\n", *p);
10 } else {
11 printf("p is NULL - nothing to print\n");
12 }
13 
14 p = &a; // now p really points to a
15 if (p != NULL) {
16 printf("Now *p = %d\n", *p);
17 }
18}
Output
p is NULL - nothing to print Now *p = 10

Opening and Closing a File

In simple words: fopen is booking a room — "r" means I will read only, "w" means give me a fresh empty room (old stuff thrown out), "a" means let me add to the room, keep what is inside. fclose locks the room when you leave.
Example94
CCode Cell
1FILE *fp; // file pointer
2fp = fopen("data.txt", "w"); // open for writing
3if (fp == NULL) { // always check!
4 printf("Cannot open file\n");
5 return;
6}
7// ... work with the file ...
8fclose(fp); // always close

Writing to a File

Use fprintf (like printf, but writes to the file) and fputs (like puts, for strings):

After running, a file named marks.txt is created with three lines.

Example95
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 FILE *fp = fopen("marks.txt", "w");
6 if (fp == NULL) { printf("Cannot open\n"); return; }
7 
8 fprintf(fp, "Rahul 88\n"); // write formatted data
9 fprintf(fp, "Priya 95\n");
10 fputs("Anil 76\n", fp); // write a string
11 
12 fclose(fp);
13 printf("File written\n");
14}
Output
File written

Reading from a File

Use fscanf (like scanf, reads formatted data) and fgets (reads a whole line). fgets returns NULL when the file ends — that is how we know when to stop.

fscanf returns the number of values it read. When it returns 2, a record was read successfully. When the file ends, it returns EOF (-1), so the loop stops.

Trainer's Note: Reading a whole line (with spaces) uses fgets(line, size, fp) — the same safe line reader we met for keyboard input in Chapter 8. fscanf %s reads only one word per field, which suits records with separate name and marks columns.
Example96
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 FILE *fp = fopen("marks.txt", "r");
6 if (fp == NULL) { printf("Cannot open\n"); return; }
7 
8 char name[30];
9 int marks;
10 
11 // read records one by one until the end of file
12 while (fscanf(fp, "%s %d", name, &marks) == 2) {
13 printf("%s got %d\n", name, marks);
14 }
15 fclose(fp);
16}
Output
Rahul got 88 Priya got 95 Anil got 76

End of File — EOF

EOF (End Of File) is a special constant (value -1) that tells you the file has ended. You can also write the reading loop like this:

Example97
CCode Cell
1while (!feof(fp)) { // while NOT end of file
2 if (fscanf(fp, "%s %d", name, &marks) == 2)
3 printf("%s %d\n", name, marks);
4}

A Complete Example — Copy One File to Another

Here fgetc reads one character, fputc writes one character — together they copy any file (even text) character by character until EOF.

Example98
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 FILE *in = fopen("source.txt", "r");
6 FILE *out = fopen("copy.txt", "w");
7 
8 if (in == NULL || out == NULL) {
9 printf("Cannot open files\n");
10 return;
11 }
12 
13 char ch;
14 while ((ch = fgetc(in)) != EOF) { // read one character at a time
15 fputc(ch, out); // write it to the other file
16 }
17 
18 fclose(in);
19 fclose(out);
20 printf("File copied\n");
21}
Output
File copied
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Programs are grouped by chapter
  • Typing programs is the fastest way to learn C