+ 2
Problem with for loop
https://code.sololearn.com/c18PnHUpHo6R/?ref=app I want to return in this case //9 //8 If num = 25 it should return //9 //9 //7 If num <= 9 then return num Hope someone help me. Thanks
4 Respuestas
+ 6
First look at what's going on inside the for loop. When num = 25, it will write:
-> 0
-> 9
-> 18
... Continued unless it is equal or greater than num.
Modifying it a little, with Console.WriteLine(9) inside the for loop instead of Console.WriteLine(x) as we need to express the number as a sum of 9s and a positive integer less than 9. We have:
-> 9
-> 9
-> 9
At least it's not going above 9 now but that doesn't exactly solve the problem since we can't get the 7 at the end of the desired ouptut with this. If you know about the remainder operator %, then this is a piece of cake. (If not, then this would be a good time to check it out.)
Writing Console.WriteLine(num % 9); after the for loop, we now get:
-> 9
-> 9
-> 9
-> 7
That's some progress. The output is close to what was needed. There's an extra 9 here, which appears because the loop only cares whether the x is less than num, not x is less than (num-9). Correcting the condition, we have:
-> 9
-> 9
-> 7
Yay! That's the required output. Just in case that was a fluke, let's put num = 37 to see we weren't relying on luck:
-> 9
-> 9
-> 9
-> 9
-> 1
Problem solved.
+ 1
Thank you so much Stellar Fox. That's what I trying to do.
0
Hey Rey P. Wong , I don't understand your problem clearly please tell me ..
0
You are only printing x.
You do not assign or add something to num.
So the first iteration is 0.
Than the loop add's 9
Result
0 0<17
9 9<17
18 18<17 this returns false so Console.WriteLine is not printed.