CSC115 ยท 2075 ยท 10 marks
What is looping statement?Discuss different looping statements with suitable example of each.[2+8]
What is looping statement?Discuss different looping statements with suitable example of each.[2+8]
Quick answer
A looping statement (also called an iterative statement) is a control structure that allows a block of statements to be executed repeatedly as long as a given condition remains true. Looping avoids writing the same code multiple times and is used when a task needs to be performed a fixed or variable number of times.
Looping Statements in C
Definition of Looping Statement [2 marks]
As per the notes, iterative statements in C include:
forwhiledo...while
Types of Looping Statements [8 marks]
1. while Loop
Syntax:
while (condition)
{
// body of loop
}
How it works:
- The condition is checked before executing the body.
- If the condition is
true, the body executes. - If the condition is
falseat the start, the body is never executed. - It is called an entry-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h>
void main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i++;
}
}
Output:
1
2
3
4
5
2. do...while Loop
Syntax:
do
{
// body of loop
} while (condition);
How it works:
- The body is executed first, then the condition is checked.
- The body executes at least once even if the condition is false.
- It is called an exit-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h>
void main()
{
int i = 1;
do
{
printf("%d\n", i);
i++;
} while (i <= 5);
}
Output:
1
2
3
4
5
Key difference from while: Even if i starts at 6, the body runs once before checking the condition.
3. for Loop
Syntax:
for (initialization; condition; increment/decrement)
{
// body of loop
}
How it works:
- Initialization: Executed once at the beginning (e.g.,
i = 1). - Condition: Checked before each iteration; if false, loop ends.
- Increment/Decrement: Executed after each iteration.
- It is also an entry-controlled loop and is preferred when the number of iterations is known in advance.
Example: Find the sum of first 10 natural numbers
#include<stdio.h>
void main()
{
int i, sum = 0;
for (i = 1; i <= 10; i++)
{
sum = sum + i;
}
printf("Sum = %d", sum);
}
Output:
Sum = 55
Comparison Table
| Feature | while | do...while | for |
|---|---|---|---|
| Type | Entry-controlled | Exit-controlled | Entry-controlled |
| Condition checked | Before body | After body | Before body |
| Minimum executions | 0 | 1 | 0 |
| Best used when | Iterations unknown | Must run at least once | Iterations known |
Summary
Looping statements are essential in C programming to perform repetitive tasks efficiently. The for loop is used when the number of iterations is known; the while loop is used when the condition is checked before execution; and the do...while loop guarantees at least one execution of the loop body.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.