c++ - Code explanation for a While Loop within a For Loop -
can explain me why output program below, if input values: 5, 222, 2043, 29, 2, 20035 22222? i'm trying solve on paper , can't result.
#include <iostream> using namespace std;  int n=0; int x=0; int s=0; int i=1;   int main() {     cin >> n;     for(i=1; i<=n; i++) {         cin >> x;         int nr=1;         while(x>9) {             nr=nr*10;             x=x/10;         }         s=s+x*nr;     }     cout << s;     return 0; } 
your while loop divides x 10 every time. , since you're dealing integers, shifts decimal number 1 right: 7234 -> 723.  untill smaller 10, or in other words, there 1 (the first) digit left: 7. multiplies again 10^(times divided 10): 7000.
 means code whitin for-loop makes first digits 0 in each x. in end you'll have: 200 + 2000 + 20 + 2 + 20000
Comments
Post a Comment