Question Sum many numbers with condition

Rabi

Member
Joined
Mar 22, 2022
Messages
17
Programming Experience
Beginner
this code will enter numbers and print sum them between 1 to 10 // the problem is : it sum all the nummbers except the first number i entered
example : if I enter 5 3 2 1 will print sum(3+2+1) = 6. will not sum 5 with numbers
C#:
int a = int.Parse(Console.ReadLine());
int sum = 0;

while (a < 10 && a > 0)
{
  a = int.Parse(Console.ReadLine());
  if (a < 10 && a > 0)
  {
    sum = sum + a;
    Console.WriteLine(sum);
  }
  else
  {
    Console.WriteLine("No");
    Console.WriteLine(sum);
  }
}
 
Last edited by a moderator:
The bug is pretty obvious. You have a logic bug.

We can tell you what it is like we have done in your past two threads, but it is time for you to increase your skill level. Step through the code line by line with the debugger. Don't just press F5. Instead press F11 and go line by line. Add a debug pane to view the values of the variables. Or hover your mouse over each of variables to see the values as you go from line to line.

Alternatively, you can do what people used to do when they didn't have access to the computer. Simulate the running of the code with pencil and paper.
 
Last edited:
the variable a must be int a =1. because it will not print the variable, only will take it as a value in the loop in the first.
 
Look at your code. You have this:
C#:
int a = int.Parse(Console.ReadLine());

...
    
  a = int.Parse(Console.ReadLine());

...
    
    sum = sum + a;
Why would you be surprised that the first value was not added to the sum when you're not adding the first number to the sum? Think about the logic first. Only when you have logic that works, which you can test using a pen and paper, should you write any code and then only to explicitly implement the logic you have already got.
 

Latest posts

Back
Top Bottom