Introduction
Loops are a fundamental concept in programming that allow us to execute a block of code repeatedly. In this blog, we'll explore how to use loops in C with a simple example that calculates the sum of the first n natural numbers. This demonstration will help you understand the basics of for, while, and do-while loops.
Step-by-Step Guide
1. Understand the Problem:
The task is to calculate the sum of the first n natural numbers, where n is provided by the user.
2. Logic:
We will use loops to repeatedly add numbers from 1 to n and display the total sum.
C Program Code
#include <stdio.h>
int main() {
int n, sum = 0;
// Prompting user for input
printf("Enter a positive integer: ");
scanf("%d", &n);
// Using a for loop to calculate the sum
for (int i = 1; i <= n; i++) {
sum += i;
}
// Displaying the result
printf("The sum of the first %d natural numbers is: %d\n", n, sum);
return 0;
}Explanation of the Code
Input: The program prompts the user to enter a positive integer
n.Loop: A
forloop is used to iterate from 1 ton. In each iteration, the loop adds the current value ofito thesum.Output: After the loop completes, the program displays the total sum.
Example Output
Enter a positive integer: 5
The sum of the first 5 natural numbers is: 15Variations
Using a
whileLoop:int i = 1; while (i <= n) { sum += i; i++; }Using a
do-whileLoop:int i = 1; do { sum += i; i++; } while (i <= n);
Conclusion
Loops are incredibly versatile and widely used in programming. This example shows how to use them for a simple task, but the possibilities are endless. Mastering loops will make your programs more efficient and powerful.

0 Comments