1 x 20 +1 x 21 + 1 x 22 + 0 x 23 +1 x 24 = 1 + 2 x (1 + 2 x (1 + 2 x (0 + 2 x 1) ) )
Recall b[0] = 1, b[1] = 1, b[2] = 1,b[3] = 0, b[4] = 1
/* to convert a binary representation to a decimal one*/
int dec, b[5] = {1, 1, 1, 0, 1};
dec = b[4];
for (int i = 3; i >= 0; i--)
{
dec=2 * dec + b[i]; //horner's scheme
}
cout << dec << endl;
I tried to write this code again in C language, but it’s not working correctly:
#include<stdio.h>
int main()
{
int B[5];
int x, s, s1;
for(int i = 1;i <= 5; i++)
{
printf("Enter %d. digit of binary number", i);
scanf("%d", &B[i]);
}
s = B[5]; /*this part for reverse the array*/
B[5] = B[1];
B[1] = s;
s1 = B[4];
B[4] = B[2];
B[2] = s1;
x = B[4];
for (int i = 3; i >= 0; i--)
{
x = 2 * x + B[i];
}
printf("%d", x);
scanf("%d");
}
This is your initial loop where you initialise the array B
which is bad as you are accessing element
B[5]which is outside the bounds of your array anyway, but also you are never initialisingB[0]which you use in your second looptry changing your first loop to
and see if this gives the result you expect.
Also this code
has problems, because you declared B as an array of 5 integers and since arrays have zero based indices, the only values for an index that are valid are from 0 to 4. If you want to reverse the array correctly replace your code with
You must not access B[5] as this is outside the bounds of your array !!!!