Loop
• In programming, a loop allows you to execute a block of code repeatedly until a certain
condition is met.
• This avoids writing the same code multiple times.
Types of Loops in C
1. for Loop
2. while Loop
3. do…. while loop
Special Statements in Loops
4. break → exits the loop immediately.
5. continue → skips the current iteration and goes to the next.
‘for’ Loop
• Used when the number of iterations is known.
Syntax
for (initialization; condition; update)
{
// code to be executed
}
Example:
#include <stdio.h>
int main ()
{
for (int i = 1; i <= 5; i++) {
printf ("Hello %d \n", i);
}
return 0;
}
‘while’ Loop
• Used when the number of iterations is not known beforehand.
• Condition is checked before entering the loop.
Syntax
while (condition)
{
// code to execute
}
Example:
#include <stdio.h>
int main ()
{
int i = 1;
while (i <= 5) {
printf ("Count: %d \n", i);
i++;
}
return 0;
}
‘do…while’ Loop
• Similar to while, but condition is checked after executing the loop body.
• Ensures the loop runs at least once, even if the condition is false.
Example:
#include <stdio.h>
int main ()
{
int i = 1;
do {
printf ("Number: %d\n", i);
i++;
}
while(i <= 5);
return 0;
}
Arithmetic Operators
Operator Meaning Example (a=10, b=3) Result
+ Addition a+b 13
- Subtraction a-b 7
* Multiplication a*b 30
/ Division (quotient) a/b 3
% Modulus (remainder) a%b 1
Relational Operators
Operator Meaning Example (a=10, b=5) Result
== Equal to a==b 0 (false)
!= Not equal to a != b 1 (true)
> Greater than a>b 1 (true)
< Less than a<b 0 (false)
>= Greater than or equal to a >= b 1 (true)
<= Less than or equal to a <= b 0 (false)
Compound Assignment Operators
Operator Equivalent to Example (x=10, y=3) Result (x)
+= x=x+y x += y → 10+3 13
-= x=x-y x -= y → 10-3 7
*= x=x*y x *= y → 10*3 30
/= x=x/y x /= y → 10/3 3
%= x=x%y x %= y → 10%3 1