Question Using loop to sum numbers

Rabi

Member
Joined
Mar 22, 2022
Messages
17
Programming Experience
Beginner
This code to sum numbers, but it is only show the numbers. mean instead of sum : 1 2 3 4 = 10 . its only show the numbers. how to sum the numbers?

C#:
  for (int x = 0; x < 5; x++)
            {
                    int sum = 0;
                    Console.WriteLine(sum += x);
            }

            /*print  on screen:
             * 1
             * 2
             * 3
             * 4
             */
 
Last edited by a moderator:
Solution
Declare and initialize sum before the for loop.
Inside the loop add x to sum.
If you wish you can print the running sum.
If you decide not to print the running sum you can just print the final value after the for loop.
Declare and initialize sum before the for loop.
Inside the loop add x to sum.
If you wish you can print the running sum.
If you decide not to print the running sum you can just print the final value after the for loop.
 
Solution

Latest posts

Back
Top Bottom