hacaoideas
hacaoideas

Reputation: 115

for loop of c++ initializes wrong iterator

I tried to write a simple program to check some numbers. It just refuses to work. Below code sample:

#include <iostream>
using namespace std;

void checknumber(int i)
{
if(i>9)
{
    if(i%2==0) {cout<<"even"<<endl;}
    else {cout<< "odd" << endl;}
}
else
{
    switch(i)
    {
        case 1:
            cout<<"one"<<endl;
            break;
        case 2:
            cout<<"two"<<endl;
            break;
        case 3:
            cout<<"three"<<endl;
            break;
        case 4:
            cout<<"four"<<endl;
            break;
        case 5:
            cout<<"five"<<endl;
            break;
        case 6:
            cout<< "six"<<endl;
            break;
        case 7:
            cout<<"seven"<<endl;
            break;
        case 8:
            cout<<"eight"<<endl;
            break;
        case 9:
            cout<<"nine"<<endl;
            break;
        default:
            break;

    }
    }
}


int main() {

int a,b;
cin >> a >> b;
for (int i=a; i==b; i++)
{
    checknumber(i);
}

return 0;
}

Function works fine. But, main program refuses to work as I expected.

input: 3 10, output: nothing. I debugged it and found that I have to initialize to a very negative number around -27k.

Upvotes: 0

Views: 90

Answers (3)

Muhammad Abbas
Muhammad Abbas

Reputation: 496

for (int i = a; i == b; i++)
{
    checknumber(i);
}

You cannot solve this problem like this. Do

for (int i = a; i <= b; i++)
    {
        checknumber(i);
    }

Then your problem will solve correctly.

Upvotes: 0

Manwal
Manwal

Reputation: 23836

Loop's condition part is not correct. Try:

for (int i=a; i<=b; i++)
              ^^^^

If I understand the problem correctly you want to run it from 3 to 10.

In your case for (int i=a; i==b; i++) condition i==b will be checked only once, so loop will break at first condition where (3 == 10) is false. In example of 3 to 10 it will break in first condition.

Upvotes: 4

Employed Russian
Employed Russian

Reputation: 213957

I debug it and find I to be initialized to a very large negative number instead of 'a'.

It's likely that you didn't debug correctly. In any case, this loop:

for (int i=a; i==b; i++)

will only execute once if a == b, and zero times otherwise. You probably want:

for (int i=a; i!=b; i++)

Upvotes: 1

Related Questions