Reputation: 49
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
Reputation: 726479
a
being evaluated and its value discarded in the initialization section of the first for
loopa
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