Usman Qamar
Usman Qamar

Reputation: 49

Why for loop behave differently in following different situations

I am new in programming I am studying about for loop I tried it in various ways and output every time was different. Code when I wrote only "a" to initialize for loop:

input was "Enter binary number:11011"

Output was "Decimal Number=27"

 #include <iostream>
    using namespace std;
    int main(){
        int a,b,c=1,d=0;
        cout<<"Enter binary number:";
        cin>>a;
        for (a;a!=0;a=a/10) {
            b=a%10;
            d=d+b*c;
            c=c*2;
        }
        cout<<"Decimal Number="<<d<<endl;

    } 

Code when I wrote "int a" to initialize for loop:

input was "Enter binary number:11011"

Output was "Decimal Number=0"

#include <iostream>
using namespace std;

    int main(){
        int a,b,c=1,d=0;
        cout<<"Enter binary number:";
        cin>>a;
        for (int a;a!=0;a=a/10) {
            b=a%10;
            d=d+b*c;
            c=c*2;
        }
        cout<<"Decimal Number="<<d<<endl;

    }

Code when I wrote nothing to initialize for loop:

input was "Enter binary number:11011"

Output was "Decimal Number=27"

#include <iostream>
using namespace std;
int main(){
    int a,b,c=1,d=0;
    cout<<"Enter binary number:";
    cin>>a;
    for (;a!=0;a=a/10) {
        b=a%10;
        d=d+b*c;
        c=c*2;
    }
    cout<<"Decimal Number="<<d<<endl;

}

Upvotes: 1

Views: 66

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

  • Your first and last code snippets do not differ from each other, apart from a being evaluated and its value discarded in the initialization section of the first for loop
  • Your second loop re-declares a without initializing it. Variable a inside the for loop is not the same as the variable a outside the loop, so reading its uninitialized value is undefined behavior.

Since you do not really need a separate loop variable, using a while loop is a more common choice:

while (a) {
    b = a%10;
    d += b*c;
    c *= 2;
    a /= 10;
}

Note the use of compound assignment expressions +=, *=, and /=. A compound assignment of the form x += y is equivalent to x = x + y

Upvotes: 1

Related Questions