Hello my currenct code is doing sum on numbers after including 10 I need it only after, now is doing like 10 10 = 20 then 20 11 = 31 and etc which is wrong, when I change my i with 11 it adds 1 more interaction to the correct and makes the number more than 1000.
`` `
int i = 10;
int a = 10;
while (a < 1000)
{
a = i ;
}
Console.WriteLine(a);
Console.WriteLine(i);
Tried to change the numbers to 11 which is correct but gives me 1 more interaction which I want to remove!
CodePudding user response:
sorry, do you mean to increment only by 10 ?, you can change a = i ;
to a = i;
CodePudding user response:
Solution:
int i = 11;
int a = 10;
while (a < 1000)
{
a = i ;
}
i -= 1;
a -= i;
Console.WriteLine(a);
Console.WriteLine(i);
CodePudding user response:
So you want to termionate the loop before a
gets > 1000.
The easiest way is to calculate the new value but not yet assign it to a
:
int i = 10;
int a = 10;
while (a < 1000)
{
int newValue = a i;
if (newValue > 1000) break;
i ;
a = newValue;
}
Console.WriteLine(a);
Console.WriteLine(i);
Alternative: you could also modify the while condition. As you know you are going to add i
, check if the result would be still <= 1000:
while (a i <= 1000)
{
a = i ;
}
Alternative 2: Another strategy proposed in @Slepcho's comment is to undo the last addition after the loop:
while (a <= 1000)
{
a = i ;
}
a -= --i;