2081 1

BIT102 · 2081 · 10 marks

What is loop? Differentiate between break and continue statement.Write a program to find sum of first N natural numbers.[6+4]

What is loop? Differentiate between break and continue statement.Write a program to find sum of first N natural numbers.[6+4]

C ProgrammingChapter 5: Loops and IterationLoop control statements

Quick answer

A loop is a control structure that allows repeated execution of a block of statements as long as a given condition remains true. Loops are used to avoid writing the same code multiple times.

Loop, Break vs Continue, and Sum of N Natural Numbers


What is a Loop?

Types of Loops in C:

Loop TypeDescription
for loopUsed when the number of iterations is known
while loopEntry-controlled; checks condition before executing
do-while loopExit-controlled; executes at least once

Difference Between break and continue Statement

Featurebreakcontinue
FunctionTerminates the entire loop immediatelySkips the current iteration only
Control TransferTransfers control outside the loopTransfers control to the loop's condition check
Effect on LoopLoop stops completelyLoop continues with next iteration
Use CaseExit loop when a condition is metSkip specific values during iteration

Example of break:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        break;       // loop ends when i reaches 5
    printf("%d ", i);
}
// Output: 1 2 3 4

Example of continue:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        continue;    // skips i=5, loop keeps running
    printf("%d ", i);
}
// Output: 1 2 3 4 6 7 8 9 10

Conclusion: break exits the loop entirely, while continue only skips the current iteration and the loop keeps running.


Program to Find Sum of First N Natural Numbers

The sum of first N natural numbers means adding all integers from 1 to N.

#include <stdio.h>

int main() {
    int n, i, sum = 0;

    printf("Enter the value of N: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++) {
        sum = sum + i;   // accumulate sum
    }

    printf("Sum of first %d natural numbers = %d\n", n, sum);

    return 0;
}

Sample Output:

Enter the value of N: 5
Sum of first 5 natural numbers = 15

Explanation (Dry Run for N = 5):

Iterationisum = sum + i
110 + 1 = 1
221 + 2 = 3
333 + 3 = 6
446 + 4 = 10
5510 + 5 = 15

The for loop runs from i = 1 to i = N, adding each value of i to the variable sum. After the loop ends, the final sum is displayed.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.