CSC115 C Programming

C ProgrammingTU Board 2075Unit 5

What is looping statement? Discuss different looping statements with suitable example of each.

10

Answer

A looping statement repeats a block of code while a condition is true. It saves writing the same statements again and again, for example to print numbers 1 to 100 or to read many inputs.

Every loop has three parts: initialisation of a counter, a condition that is tested, and an update that eventually makes the condition false.

C has three looping statements.

1. while loop (entry-controlled)

The condition is tested before each pass, so the body may not run at all.

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
/* Output: 1 2 3 4 5 */

2. do...while loop (exit-controlled)

The condition is tested after each pass, so the body always runs at least once. Useful for menus.

int n;
do {
    printf("Enter a positive number: ");
    scanf("%d", &n);
} while (n <= 0);

3. for loop

Initialisation, condition and update are written together in one line. It is best when the number of repetitions is known.

int i, fact = 1;
for (i = 1; i <= 5; i++)
    fact = fact * i;
printf("5! = %d", fact);   /* 5! = 120 */

Comparison

while do...while for
Entry-controlled Exit-controlled Entry-controlled
Body may run 0 times Body runs at least once Body may run 0 times
Used when the count is unknown Used for menus and input checks Used when the count is known

break ends a loop immediately, and continue skips the rest of the current pass and moves to the next one.

Discussion

Loading…

All C Programming old questions