This C# program calculates the sum of the first 50 natural numbers. Natural numbers are the positive integers starting from 1.
Problem Statement
Write a C# program that calculates and displays the sum of the first 50 natural numbers. Natural numbers are positive integers starting from 1 and continuing indefinitely. Your program should use a for loop to iterate through the first 50 natural numbers, accumulate their sum, and then output the result.
C# Program to Find the Sum of First 50 Natural Numbers using For Loop
using System;
namespace SumOfFirst50NaturalNumbers
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
// Using a for loop to iterate through the first 50 natural numbers
for (int i = 1; i <= 50; i++)
{
sum += i;
}
Console.WriteLine("The sum of the first 50 natural numbers is: " + sum);
}
}
}
How it Works
- Initialization:
- We start by declaring an integer variable called
sumand initialize it to 0. This variable will be used to store the cumulative sum of the natural numbers.
- We start by declaring an integer variable called
- For Loop:
- We use a
forloop to perform a series of actions repeatedly. In this case, the loop will execute 50 times, starting fromi = 1and ending whenibecomes greater than 50. int i = 1;initializes a loop variableito 1, which is the first natural number.i <= 50is the loop condition. The loop will continue as long asiis less than or equal to 50.i++is the increment statement, which increasesiby 1 after each iteration.
- We use a
- Loop Body:
- Inside the loop, we have a single statement:
sum += i;. This statement adds the current value ofito thesumvariable.- In the first iteration,
iis 1, so we add 1 tosum. - In the second iteration,
iis 2, so we add 2 tosum. - This process continues until the loop completes all 50 iterations.
- In the first iteration,
- Inside the loop, we have a single statement:
- Accumulation of Sum:
- As the loop iterates, the
sumvariable accumulates the sum of the first 50 natural numbers.
- As the loop iterates, the
- Printing the Result:
- After the
forloop finishes executing, we useConsole.WriteLineto display the result. - We print a message, “The sum of the first 50 natural numbers is: “, followed by the value of the
sumvariable, which contains the sum we calculated in the loop.
- After the
- Program Execution:
- When you run the program, it initializes
sumto 0, enters theforloop, adds the numbers from 1 to 50 tosum, and then displays the final sum in the console.
- When you run the program, it initializes
Input/ Output
