+ 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

1st Jun 2018, 8:14 PM
Haseeb Shah
Haseeb Shah - avatar
10 Answers
+ 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.
1st Jun 2018, 9:40 PM
John Wells
John Wells - avatar
+ 1
You can, but must know a valid exit condition. This works: for(;x!=0;)
1st Jun 2018, 10:21 PM
John Wells
John Wells - avatar
+ 1
Another way: for(;x>0;x=x/10) { y=x%10; sum=sum+y; }
1st Jun 2018, 10:24 PM
John Wells
John Wells - avatar
+ 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
1st Jun 2018, 10:27 PM
John Wells
John Wells - avatar
+ 1
yes
1st Jun 2018, 10:44 PM
John Wells
John Wells - avatar
+ 1
Thank you Sir for the answer
1st Jun 2018, 10:45 PM
Haseeb Shah
Haseeb Shah - avatar
0
Why can't we use for loop while making this program
1st Jun 2018, 10:11 PM
Haseeb Shah
Haseeb Shah - avatar
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
1st Jun 2018, 10:24 PM
Haseeb Shah
Haseeb Shah - avatar
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
1st Jun 2018, 10:37 PM
Haseeb Shah
Haseeb Shah - avatar
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 ?
2nd Jun 2018, 10:35 AM
Haseeb Shah
Haseeb Shah - avatar