Positive integers 1, 2, 3, 4… are known as natural numbers.
This program takes a positive integer from user( suppose user entered n ) then, this program displays the value of 1+2+3+….+n.
The program was created with “for” loop statement on C# Console.
First Step, the user enter a number.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void Main(string[] args) { int n, sum=0; Console.Write("Enter a positive integer: "); n = Int32.Parse(Console.ReadLine()); for(int i=1;i<=n;i++) { sum += i; } Console.WriteLine("Sum = "+sum); Console.ReadKey(); } |
Output:
The Sum Of The First 10 Natural Numbers
1 2 3 4 5 6 7 8 9 10 11 12 | static void Main(string[] args) { int sum=0; for(int i=1;i<=50;i++) { sum += i; } Console.WriteLine("Sum of 1 to 10 = "+sum); Console.ReadKey(); } |
The Sum Of The First n Natural Numbers
1 2 3 4 5 6 7 8 9 10 11 12 | static void Main(string[] args) { int sum=0; for(int i=1;i<=50;i++) { sum += i; } Console.WriteLine("Sum of 1 to 50 = "+sum); Console.ReadKey(); } |
The Sum Of The First 100 Natural Numbers
1 2 3 4 5 6 7 8 9 10 11 12 | static void Main(string[] args) { int sum=0; for(int i=1;i<=100;i++) { sum += i; } Console.WriteLine("Sum of 1 to 100 = "+sum); Console.ReadKey(); } |
The Sum Of The First 500 Natural Numbers
1 2 3 4 5 6 7 8 9 10 11 12 | static void Main(string[] args) { int sum=0; for(int i=1;i<=500;i++) { sum += i; } Console.WriteLine("Sum of 1 to 500 = "+sum); Console.ReadKey(); } |