#include <iostream>
usingnamespace 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;
}
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.
#include <iostream>
usingnamespace 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>
usingnamespace 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;
}
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.