Answer to Question #272281 in C# for chi

Question #272281

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


1
Expert's answer
2021-11-28T05:31:08-0500
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;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS