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]
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 Type | Description |
|---|---|
for loop | Used when the number of iterations is known |
while loop | Entry-controlled; checks condition before executing |
do-while loop | Exit-controlled; executes at least once |
Difference Between break and continue Statement
| Feature | break | continue |
|---|---|---|
| Function | Terminates the entire loop immediately | Skips the current iteration only |
| Control Transfer | Transfers control outside the loop | Transfers control to the loop's condition check |
| Effect on Loop | Loop stops completely | Loop continues with next iteration |
| Use Case | Exit loop when a condition is met | Skip 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:
breakexits the loop entirely, whilecontinueonly 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):
| Iteration | i | sum = sum + i |
|---|---|---|
| 1 | 1 | 0 + 1 = 1 |
| 2 | 2 | 1 + 2 = 3 |
| 3 | 3 | 3 + 3 = 6 |
| 4 | 4 | 6 + 4 = 10 |
| 5 | 5 | 10 + 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.