Home > Blockchain >  C program fails to execute more than one statement at the same time
C program fails to execute more than one statement at the same time

Time:10-21

I am trying to make a c program that converts the decimal the user entered into a binary and octal number.

Given the user entered 24, my output should look like this:

24 in Decimal is 11000 in Binary.
24 in Decimal is 30 in Octal.

But the terminal only executes the decimal to binary conversion. Hence my current output look like this:

24 in Decimal is 11000 in Binary.
0 in Decimal is 0 in Octal.

Here is the code in question. For context, the two conversions were written by two separate people:

#include <stdlib.h>

int main()
{
            int a[10], input, i;  //variables for binary and the user input
            int oct = 0, rem = 0, place = 1; //variables for octal
            printf("Enter a number in decimal: ");
            scanf("%d", &input);

//decimal to binary conversion            
            printf("\n%d in Decimal is ", input);
            for(i=0; input>0;i  )
                {
                    a[i]=input%2;
                    input=input/2;
                }
            for(i=i-1;i>=0;i--)    
            {printf("%d",a[i]);}

//decimal to octal conversion
            printf("\n%d in Decimal is ", input);
            while (input)
            {rem = input % 8;
            oct = oct   rem * place;
            input = input / 8;
            place = place * 10;}
            printf("%d in Octal.", oct);

        }

The octal conversion only executes when I remove the decimal to binary portion. But I want both of them to execute at the same time.

CodePudding user response:

Your first for loop manipulates the input variable, therefore its value is always 0 after the binary conversion. Change your code to something like this, using an additional variable to do the computation on:

printf("\n%d in Decimal is ", input);
int temp = input;
for(i=0; temp>0;i  )
{
     a[i]=temp%2;
     temp=temp/2;
}
for(i=i-1;i>=0;i--)    
{
    printf("%d",a[i]);
}

//decimal to octal conversion
printf("\n%d in Decimal is ", input);
temp = input;
while (temp)
{
    rem = temp% 8;
    oct = oct   rem * place;
    temp = temp / 8;
    place = place * 10;
}
printf("%d in Octal.", oct);
  • Related