Write a program to calculate the sum of the sequence no. from 1 to n. Thus if the input is 6, the output should be 21 because: (Apply the three looping statements in your solutions) 1 + 2 + 3 + 4 +5 + 6 = 21
1st Solution – using for loop
2nd Solution – using while loop
3rd Solution-‐ using do while loop
class Program
{
public static void Main()
{
Console.Write("Enter a number: ");
string input = Console.ReadLine();
if(!int.TryParse(input, out int value))
{
Console.WriteLine("Incorrect input. Press any key..");
return;
}
int output = CalcWithDoWhile(value);
Console.WriteLine($"Sum: {output}");
Console.ReadLine();
}
public static int CalcWithFor(int number)
{
int result = 0;
for (int i = 0; i < number; i++)
result += i + 1;
return result;
}
public static int CalcWithWhile(int number)
{
int result = 0,
i = 0;
while (i < number)
result += i++ + 1;
return result;
}
public static int CalcWithDoWhile(int number)
{
int result = 0,
i = 0;
do
{
result += i + 1;
} while (++i <number);
return result;
}
}
Comments
Leave a comment