Animeartist
Animeartist

Reputation: 1187

How to display values of an array in C?

I have written the following code in C to find the binary of a number using functions.

//C program to find the binary equivalent of a number using functions

#include <stdio.h>
void bineq(int);
void main()
{    
    int a=5,b=3;           //Initialize two numbers        
    printf("The binary equivalent of a= \n");
    bineq(a);
    printf("The binary equivalent of b= \n");
    bineq(b);

}
void bineq(int x)         // Function Definition.
   {
       int p[50];
       int i=0,t,j;
       t=x;

       while(t>=0)
       {
           p[i]=t%2;
           i++;
           if(t==0){
             break;}
           t=t/2;   
       }  

       for(j=i-1;j>=0;j--)
       {
            printf("%d ",p[i]);

       }

   }

When I run the code, I get the following values:

 The binary equivalent of a= -1610823072 -1610823072 -1610823072 -1610823072 

 The binary equivalent of b= 32644 32644 32644                                                       

When I ran the code in C Tutor(online compiler),the following error occurred at the printf statement in the bineq function:

ERROR: Conditional jump or move depends on uninitialized value(s) (Stopped 
running after the first error. Please fix your code.)

The binary of 5 is correctly stored in integer array p,but I am not able to display each integer backwards.

I would like to solve the problem in the most simplest way possible. Have I missed any logic or any line in the code?

Upvotes: 0

Views: 257

Answers (1)

Deepesh Choudhary
Deepesh Choudhary

Reputation: 677

In the for loop of bineq, change

printf("%d ",p[i]);

to

printf("%d ",p[j]); 

Also you don't need to check if(t==0) break; your while will do the same thing just change while(t>=0) to while(t>0)

Upvotes: 4

Related Questions