## c++ - for is not working properly or something wrong with switch?

• %Artur (58/58) Dec 01 2008 /*This prog supposed to convert from binary number system to decimal but
• Artur (56/56) Dec 01 2008 /*This prog supposed to convert from binary number system to decimal but...
```/*This prog supposed to convert from binary number system to decimal but
something is not

#include <iostream>
using namespace std;

int main()
{
int a[8],sum=0;
cout << endl;
cout << "Input Binary number(with spaces between digits): ";
for(int i=0;i<=7;i++)
{

cin >> a[i];

if((a[i]!=1)&&(a[i]!=0))//Strange indeed!!! I tried || but my message
showed up.
{
cout << "You entered wrong digit!!!" << endl;
i--;
}

}

for(int i=7;i>-0;i++) // I also tried for(int i=7;i>=0;i--) but get same
results
{                    // results of 000000001 is 128 and of 10000000 is 1?!
if(a[i])
{
switch(i)  // ofcourse I can just change cases but it is not the way
"for" must work...
{
case 0:
sum+=1;
break;
case 1:
sum += 2;
break;
case 2:
sum += 4;
break;
case 3:
sum += 8;
break;
case 4:
sum += 16;
break;
case 5:
sum += 32;
break;
case 6:
sum += 64;
break;
case 7:
sum += 128;
break;

default: cout << "This shall not happen!" << endl;
}
}
}

cout << sum;
}
```
Dec 01 2008
```/*This prog supposed to convert from binary number system to decimal but
something
is not

#include <iostream>
using namespace std;

int main()
{
int a[8],sum=0;
cout << endl;
cout << "Input Binary number(with spaces between digits): ";
for(int i=0;i<=7;i++)
{

cin >> a[i];

if((a[i]!=1)&&(a[i]!=0))//Strange indeed!!! I tried || but my message
showed up.
{
cout << "You entered wrong digit!!!" << endl;
i--;
}

}

for(int i=0;i<8;i++) // I also tried for(int i=7;i>=0;i--) but get same
results
{                    // results of 000000001 is 128 and of 10000000 is 1?!
if(a[i])
{
switch(i)  // ofcourse I can just change cases but it is not the way
"for"
must work...
{
case 0:
sum+=128;
break;
case 1:
sum += 64;
break;
case 2:
sum += 32;
break;
case 3:
sum += 16;
break;
case 4:
sum += 8;
break;
case 5:
sum += 4;
break;
case 6:
sum += 2;
break;
case 7:
sum += 1;
break;

default: cout << "This shall not happen!" << endl;
}
}
}

cout << sum;
}
```
Dec 01 2008