+ 1
Loop Issue
for(i=0;i<x;i++) { y=x%10; sum=sum+y; x=x/10; } cout"<<sum"; return 0; } in this program when i type a no 1234 only 432gets add plz help .. where x is inputed number
10 Réponses
+ 1
when i becomes 3 with x of 1 you exit the loop failing to process the 1. Replace:
for(i=0;i<x;i++)
with:
while(x>0)
and it will do what you're looking for.
+ 1
You can, but must know a valid exit condition. This works:
for(;x!=0;)
+ 1
Another way:
for(;x>0;x=x/10)
{
y=x%10;
sum=sum+y;
}
+ 1
first loop test: i=0;x=1234
second: i=1;x=123
third: i=2;x=12
fourth: i=3;x=1 condition met so exit
+ 1
yes
+ 1
Thank you Sir for the answer
0
Why can't we use for loop while making this program
0
Yes i have tried this and that worked perfectly but I am not able to understand that why for(i=0;i<n;i++) is not working. Can you please explain me in brief
0
So when i=3;x=1 condition is reached the loop will exit out and that no is not being added . Am i right ? .. and if the no is 2345 at i=3;x=2 the loop exits and 2 is not added
0
john wells sir when we not initialize and increment the value in for loop as u have shown (;x!=0;) earlier it means that the loop became infinite am i right na ?