In C programming, a loop is a way to repeat a block of code multiple times. This is helpful when you want to do something again and again without writing the same code many times.
Types of Loops in C
There are three main types of loops in C:
- for loop – Best when you know how many times you want to repeat something.
- while loop – Good for repeating something as long as a condition is true.
- do-while loop – Similar to
while, but it runs the code at least once before checking the condition.
How Each Loop Works
for loop
- Syntax:
- Example:
- for (int i = 0; i < 5; i++) {printf("Hello\n");}
- This loop prints "Hello" 5 times.
int i = 0;sets the starting value.i < 5;is the condition, meaning the loop stops wheniis 5.i++increasesiby 1 each time.
- This loop prints "Hello" 5 times.
while loop
- Syntax:
- while (condition) {
- // Code to repeat
- }
Example:- int i = 0;
- while (i < 5) {
- printf("Hello\n");
- i++;
- }
- This loop also prints "Hello" 5 times. Here, the loop continues as long as
i < 5. do-while loop
- Syntax:
- Example:int i = 0;do {printf("Hello\n");i++;} while (i < 5);
- Syntax:
- Syntax:
- Syntax:
.png)
انا بكتب احلي
ReplyDeleteAmazing
ReplyDeleteperfect
ReplyDelete