while beginner

Hey, how should I make this program to count how many even numbers are in given number. For ex., if you are given 15623, the answer should be 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
using namespace std;
int main (){
int b=1,a,n=1; // n-number(that will be given)
cin>>n;
while( n != 0){

a=n%10; //by this i take the last number and store it in 'a'
if(a%2==0){ //checking if a is an even number
    b++;
    cout<<b;}
    else{

        cout<<"not even";
    }

    n=n/10; // i get rid of the number that i checked
}

return 0;
}
Last edited on
That code will do the job but you need to initialize b to 0, not to 1.
Also, you might want to move cout << b; from line 11 to line 19, and to remove lines 12 - 16.
I've corrected it but it gives me infinite zero's.
That's weird, with naaissus' correction it should work. Would you mind posting the code you have after correcting it?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <iostream>
using namespace std;
int main (){
int b=0,a,n=1; // n-number(that will be given)
cin>>n;
while( n != 0){

a=n%10; 
if(a%2==0){ 
    b++;
    n=n/10; 
}
cout<<b;}
return 0;
}
n = n /10; should be outside if statement
cout << b; should be outside while statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main (){
    int b = 0, a, n = 1; // n-number(that will be given)
    cin >> n;
    while (n != 0) {
        a = n % 10;
        if (a % 2 == 0) b++;
        n = n / 10;
    }
    cout << b;
    return 0;
}
Thank you, that was a dumb mistake.
Ah yes, you mustn't recalculate n inside the if statement, because this might result in an infinite loop just as you experienced.
See, first a is 3, right? It won't do the code inside the if statement because 3%2 isn't 0, but now that it won't execute everything inside the if, it won't recalculate n. So the next time it checks, n is still 15623 which is != 0 , a will still be 15623%10 = 3 and it results in an infinite loop.

Now you just have to move n=n/10; to line 13 and it should work.

Edit: And put the closing bracket for the while-loop before cout<< b; because else it will still print b everytime.
Last edited on
Topic archived. No new replies allowed.