Algorithm to Find the Sum of Natural Numbers
Step 1: Start
Step 2: Input: Read a positive integer n from the user.
Step 3: Process:
- Initialize variables sum to store the sum and i for iteration.
- Initialize sum to 0.
- Use a loop to iterate from 1 to n:
(i) Add the current value of i to sum.
- After the loop, sum will contain the sum of natural numbers
from 1 to n.
Step 4: Output: Display the sum of natural numbers up to n.
Step 5: End
C Program to Find the Sum of Natural Numbers
#include <stdio.h>
int main() {
int n, sum = 0, i;
// Step 2: Read a positive integer from the user
printf("Enter a positive integer: ");
scanf("%d", &n);
// Step 3: Calculate the sum of natural numbers up to n
for (i = 1; i <= n; i++) {
sum += i; // Add i to sum
}
// Step 4: Output the sum of natural numbers
printf("The sum of natural numbers up to %d is %d.\n", n, sum);
// Step 5: End
return 0;
}
Explanation of Each Step
Include Header:
#include <stdio.h>
- This line includes the standard input-output library.
Main Function:
int main() {
- The main function is the entry point of the C program.
Variable Declaration:
int n, sum = 0, i;
- Three integer variables are declared: n to store the user input, sum to store the sum of natural numbers, and i for iteration in the loop.
Reading Input:
printf("Enter a positive integer: ");
scanf("%d", &n);
- printf prompts the user to enter a positive integer.
- scanf reads the integer and stores it in the variable n.
Calculating the Sum of Natural Numbers:
for (i = 1; i <= n; i++) {
sum += i; // Add i to sum
}
- The for loop initializes i to 1 and iterates as long as i is less than or equal to n.
- In each iteration:
- i is added to sum using the compound assignment operator (+=).
Output:
printf("The sum of natural numbers up to %d is %d.\n", n, sum);
- printf prints the sum of natural numbers up to n using the format specifier %d for integers.
End:
return 0;
- This line indicates successful completion of the program.
This program effectively calculates and displays the sum of natural numbers up to a given positive integer n using a simple for loop. The algorithm ensures that each natural number from 1 to n is added to the sum, providing the cumulative total.
Discover more from lounge coder
Subscribe to get the latest posts sent to your email.