Loops not executing in functions C++

Viewed 458

Here's my code. Whenever I run the program, I expect that the cout statement in the for loop in the function Binary() to execute. But whenever I input something, it gives me 0

#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
    int temp=0,res=0;
    for(int i=x;i<0;i--){
        temp++;
        res=res+ pow(10,temp)*(i%2);
        i=i/2;
        cout<<i<<"  "<<res<<endl;
    }
    return res;
} 
int main(){
    int x; cin>>x;
    cout<<endl<<Binary(x);
    return 0;
}
2 Answers

I think the condition in your for loop is the opposite way round than your expect it. You seem to want it to continue looping until i<0. But it will actually loop while i<0. The condition is already not true when you enter the loop, so it will finish immediately without doing any iterations.

You just have to change the loop i check.

#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
    int temp=0,res=0;
    for(int i=x;i>0;i--){
        temp++;
        res=res+ pow(10,temp)*(i%2);
        i=i/2;
        cout<<i<<"  "<<res<<endl;
    }
    return res;
} 
int main(){
    int x; cin>>x;
    cout<<endl<<Binary(x);
    return 0;
}

Check the live version here http://cpp.sh/95z74

Related