Hi Guys,

I have written the below program to convert binary to octal, it is giving me erroneous results. On entering 1111 as the input number I should get 17 as the output, whereas I am getting 16707000337 as the output. Kindly help me out, below is my program:

/*program to convert binary to octal*/
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int bin,dec[100]={0},i=0,j=0,k=0,num=0,output[100]={0},number=0,rem1,rem,output1;
    printf("enter the binary number to be converted into octal");
    scanf("%d",&bin);
    rem1=bin;
/*counts the number of digits in the input binary number*/
    while(rem1!=0)
    {
            rem1=rem1/10;    
            num+=1;
    }
/*converts binary number to decimal */
    for(i=0;i<num;i++)
    {
            number=bin%10;
            bin=bin/10;
            dec[i]=pow(2,j)*number;
            j++;
    }
/*converts binary number to decimal */
    for(;i>=0;i--)
    {
            output1+=dec[i];
    }
/*converts decimal to octal*/
    while(output1!=0)
    {               
            rem=output1%8;        
            output1=output1/8;
            output[k]=rem;
            k+=1;
    }
/*prints the value of octal*/
    printf("the octal representation is");
    for(;k>0;k--)
    {
            printf("%d",output[k-1]);
    }
    system("pause");
    return 0;
}

On entering 1111 as the input number I should get 17

I think you mean 15?

Your error is in the loop at lines 26 - 29.

For a 4 digit binary number the loop at lines 18 - 24 will c=increment i to 5, the loop in lines 26 - 29 will then run 5 times adding the values for 5 binary digits to output1, but there were only 4 binary digits. The first value you add to output1 dec[i] where i = 5 has not been set to anything and so you get a random value.

Change the loop in lines 26 - 29 to run the correct number of times (rather than the correct number of times +1) and access the correct indeces of dec. You have already solved a similar problem in the 2 loops at lines 31 and 40.

Solved...the problem was uninitialized value of output1 variable...thank you for your reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.