dr 21
dr 21

Reputation: 21

Variable shows while in loop but not out of it

So I'm trying to print the first even number of "n". Somehow, when I try to print the number it would keep reading numbers on console to infinite, but when I print inside the loop it prints "66666666 etc..". This is my code:

#include <iostream>
using namespace std;
int main()
{
    int n,i,x=1;
    cin>>n;
    while(n){
        while(x){
            i=n%10;
            if(n%2==0){
                x--;
            }
            n/=10;
        }
    }
    cout<<i;
    return 0;
}

Upvotes: 1

Views: 68

Answers (1)

user10957435
user10957435

Reputation:

The problem is your 2 while loops:

while(n) {
    while(x) {
        //...
    }
}

Once x goes to 0, you end up in the outer loop.

However, this outer loop doesn't modify n at all. So if n is ever not 0, it will sit there continually.

The simplest fix is probably just combine them into a single loop:

while(n && x) {
    //...
}

Or, you can just use 1 loop and not use x at all.

int main()
{
    int n,i;
    cin>>n;
    while(n){
        i=n%10;
        if(n%2==0){
            break;
        }
        n/=10;
    }
    cout<<i;
    return 0;
}

That should also work as well.

Upvotes: 3

Related Questions