Topic 1: Loops in C
Loops allow you to repeat a block of code multiple times.
🧠 Types of Loops:
Loop Type
Use Case
for
Known number of iterations
while
Unknown number of iterations
do-while
Runs at least once, checks condition later
1. for Loop
for (initialization; condition; update) {
// code block
}
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
2. while Loop
while (condition) {
// code block
}
EXAMPLE
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
3. do-while Loop
do {
// code block
} while (condition);
Example: Print 1 to 5
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
✂️ break and continue
•
break → exits the loop
•
continue → skips to next iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skips 3
printf("%d\n", i);
}
✨ Bonus: ++i vs i++
Both increment i by 1, but:
•
i++ → Post-increment: Use the value first, then increment
•
++i → Pre-increment: Increment first, then use the value
In loops, both work the same in most cases.
🔹 Topic 2: Arithmetic Operators in C
✅ What are Arithmetic Operators?
Arithmetic operators are used to perform mathematical calculations on variables and
values.
Operator
Description
Example
Resu
+
Addition
5 + 3
8
-
Subtraction
5 - 3
2
*
Multiplication
5 * 3
15
/
Division
10 / 2
5
%
Modulus (remainder)
10 % 3
1
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %d\n", a / b);
printf("Modulus: %d\n", a % b);
return 0;
}
Out put for those operations
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
🧠 Note:
•
If you're dividing integers, the result is also an integer (decimal part is cut off).
For decimal results, use float or double.
•
float a = 10, b = 3; printf("Division: %.2f\n", a / b); // Output: 3.33
•
******************
Created by : the Department of Computer and Electrical Engineering 2025,
Kandy Regional Center.