Nearby lessons
124 of 124C - 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:
The four parts inside main() are not compulsory, but they are the natural order of thinking.
| Part | What 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. |
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.
How a C Program Runs — Three Stages
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.
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.
Program: the four constant types
Program: declare, assign, change, print
The naming rules (with valid and invalid examples)
| Rule | Valid | Invalid |
|---|---|---|
| Start with a letter or underscore | _total, sum | 9marks (starts with digit) |
| No spaces or special symbols inside | total_marks | total marks, a#b |
| Cannot be a keyword | student | int, if, for |
| C is case sensitive | sum, Sum, SUM all different | — |
Program 1: int (whole numbers)
Program 2: float (decimal numbers)
Program 3: double (more precision)
Program 4: char (one character)
Declaration and Initialization
Declaration tells C the type and name. Initialization gives a value at the time of declaration.
Program: declaration styles in action
Program: size of every basic type
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.
Program: all five arithmetic operators
Program: all six relational operators
Program: AND, OR and NOT
Program: every shortcut operator
Program 1: pre-increment vs post-increment
Program 2: pre-decrement vs post-decrement
Conditional (Ternary) Operator (?:)
This is a one-line shortcut for a simple if-else. It picks one of two values based on a condition.
Program: check pass or fail
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:
Operator Precedence — What Runs First
printf() — Printing Output
printf("text", values...) prints text, and any % format specifiers inside the text are replaced by the values.
The most important format specifiers
| Specifier | Prints |
|---|---|
| %d | Integer (int) |
| %f | Float with decimal places |
| %.2f | Float with exactly 2 decimal places |
| %c | One character |
| %s | String (text) |
| %ld | Long integer |
| %lf | Double (in scanf) |
| %x | Integer in hexadecimal |
printf() — Printing Output
Program: escape sequences in action
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.
Reading and Writing Single Characters
- getchar() — reads one character from the keyboard.
- putchar(c) — prints one character.
A Complete Example — Calculate Simple Interest
The if Statement
The if Statement
If the condition is true, the block runs; if false, it is skipped entirely.
The if-else Statement
The if-else Statement
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.
The if-else-if Ladder
Program: check result and attendance together
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.
The switch Statement
Program: ternary in action
The while Loop
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.
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.
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.
The for Loop
The for loop gathers three things in one line: where to start, when to stop, and how to move forward.
The for Loop
The for Loop
Program: The classic textbook examples: print even numbers, print a multiplication table, sum of first n numbers.
break and continue
- break — immediately stops the loop completely.
- continue — skips the rest of the current round and jumps to the next round.
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:
Program A: print even numbers up to 20
Program B: sum of first n numbers
Program C: reverse a number
Program D: factorial with a for loop
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.
Without arrays, storing 100 students' marks means 100 separate variables. With an array, it is just marks[100].
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].
Initializing an Array
If you give fewer values than the size, the remaining elements are filled with 0.
Program 1: Read and Print an Array
Program 2: Sum and Average
Program 3: Find the Maximum
Program 4: Find the Minimum
Program 5: Linear Search
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.
Program 7: Matrix Addition
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.
Declaring and Initializing Strings
Reading Strings — scanf, gets, fgets
| Function | Reads | Limitation |
|---|---|---|
| scanf("%s", name) | One word (no spaces) | Stops at the first space |
| gets(name) | A whole line including spaces | Unsafe (no size check) — avoid |
| fgets(name, size, stdin) | A whole line, safely | The modern safe choice |
The String Functions (string.h)
Include #include <string.h> and use these ready-made functions:
| Function | What it does | Example |
|---|---|---|
| strlen(s) | Length (number of characters before \0) | strlen("Rahul") → 5 |
| strcpy(dest, src) | Copy src into dest | strcpy(b, a) |
| strcat(dest, src) | Join src at the end of dest | strcat(b, a) |
| strcmp(a, b) | Compare two strings (0 = equal) | strcmp(a, b) |
| strlwr(s) | Convert to lowercase | strlwr(s) |
| strupr(s) | Convert to uppercase | strupr(s) |
| strrev(s) | Reverse the string | strrev(s) |
String Basics Without Functions
Understand how it works underneath by doing it with loops (the classic exam approach):
Program A: count vowels in a string
Program B: reverse a string (without strrev)
Program C: palindrome check
The Three Parts of a Function
| Part | What it is | Example |
|---|---|---|
| Function declaration | Tells C the function exists (before main) | int add(int, int); |
| Function definition | The actual body of the function | int add(int a, int b) { return a + b; } |
| Function call | Using the function in main | result = add(5, 3); |
Arguments and Return Values
A function can receive values (arguments) and/or return a value back. This gives four combinations:
| Type | Arguments | Return value | Example |
|---|---|---|---|
| 1 | Yes | Yes | int add(int a, int b) — returns a + b |
| 2 | Yes | No | void show(int n) — just prints |
| 3 | No | Yes | int getNum() — just returns a value |
| 4 | No | No | void welcome() — just does something |
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.
Return Statement
The return statement does two things: it gives a value back, and it immediately ends the function.
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).
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.
Fibonacci with Recursion
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.
Program 1: Declare Variables and Access Members
The dot operator (.) is how you reach a member. It is also called the member access operator.
Program 2: Initializing in One Line
Program 3: Take a Student's Data from the User
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.
Program 5: Nested Structures
A structure can contain another structure. For example, a Student can contain an Address:
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.
| Point | Structure | Union |
|---|---|---|
| Memory | Sum of all members (each has its own space) | Only the largest member (all share one space) |
| When | All members can be used together | Only one member is used at a time |
| Keyword | struct | union |
| Access | Dot operator (same) | Dot operator (same) |
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.
Program 1: see & and * working
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.
Complete Program 2 — Change a Value Through a Pointer
Using *p you can read or change the value at that address:
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:
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.
| Point | Call by value | Call by reference |
|---|---|---|
| What is passed | A copy of the value | The address of the variable |
| Function can change original? | No | Yes |
| Symbol | Normal variable | & when calling, * in the function |
| Use for | Simple calculations | Swapping, changing variables, big data (no copy) |
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.
Opening and Closing a File
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.
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.
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:
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.
- Every example is complete and compiles as-is
- Programs are grouped by chapter
- Typing programs is the fastest way to learn C