C#: Display the sum of first 10 natural numbers
C# Sharp For Loop: Exercise-2 with Solution
Write a C# Sharp program to find the sum of the first 10 natural numbers.
Visual Presentation:
Sample Solution:
C# Sharp Code:
using System; // Importing necessary namespace
public class Exercise2 // Declaration of the Exercise2 class
{
public static void Main() // Main method, entry point of the program
{
int j, sum = 0; // Declaration of variables 'j' for iteration and 'sum' to store the total sum
Console.Write("\n\n"); // Displaying new lines
Console.Write("Find the sum of the first 10 natural numbers:\n"); // Displaying the purpose of the program
Console.Write("----------------------------------------------"); // Displaying a separator
Console.Write("\n\n");
Console.Write("The first 10 natural numbers are:\n");
for (j = 1; j <= 10; j++) // Loop to calculate the sum of the first 10 natural numbers
{
sum = sum + j; // Adding each number to the sum
Console.Write("{0} ", j); // Printing each natural number
}
Console.Write("\nThe Sum is : {0}\n", sum); // Displaying the total sum of the first 10 natural numbers
}
}
Sample Output:
Find the sum of first 10 natural numbers: ---------------------------------------------- The first 10 natural number are : 1 2 3 4 5 6 7 8 9 10 The Sum is : 55
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to display the first 10 natural numbers.
Next: Write a program in C# Sharp to display n terms of natural number and their sum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/for-loop/csharp-for-loop-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics