Khacho
Khacho

Reputation: 301

Print integer from character array in c

int main(){
int n,i=0,c1,c2;
char a[1000];
scanf("%d",&n);

while(n!=0)
{
    a[i]=n%2;
    printf("%d",a[i]); // This prints Values Correctly
    n=n/2;
    i++;

}    
a[i]='\0';
for(i=0;a[i]!='\0';i++)
printf("%d",a[i]);    //This prints only the first element of the array
}

What am I missing here? Why can't I loop through and print the values of the char array although it works when I try to print it inside while loop?

Upvotes: 0

Views: 4049

Answers (3)

NeoR
NeoR

Reputation: 353

First thing you used a[i]=n%2 and n is an integer value so what happens is say n=65(for A) then 65%2=1 (now a[0]=1) 65/2=32 now, for the next iteration 32%2=0 so basically you stored a null value at the first or second iteration depending on the value of n.

I edited your code a little bit for better understanding and debugging.

#include<stdio.h>
int main(){
int n,i=0,c1,c2;
char a[1000];
scanf("%d",&n);

while(n!=0)
{    
a[i]=n%2;
printf("%d\t%d\t%c\n",a[i],i,a[i]); // This prints Values Correctly
n=n/2;
i++;
} 
printf("%d\n",i);   
a[i]='\0';
printf("%d\t%d\n",a[i],i);
for(i=0;a[i]!='\0';i++)
printf("%d\t%d\n",a[i],i);    //This prints only the first element of the         array
}

SAMPLE RUN:-

Untitled.png

I also recommend that before posting for such silly errors try debugging using printf within loops and perform dry runs before you come to any conclusions.

Upvotes: 1

User_Targaryen
User_Targaryen

Reputation: 4225

When your input is an even number like 12, then the first digit to be stored is 0 which actually means NULL as the array defined is a character array.

That is why nothing gets printed when the input is an even number.

Here is what you can do:

#include<stdio.h>
int main(){
int n,i=0,c1,c2;
char a[1000];
scanf("%d",&n);

while(n!=0)
{
    a[i]='0' + n%2; //note here
  //  printf("%d",a[i]); // This prints Values Correctly
    n=n/2;
    i++;

}    
a[i]='\0';
for(i=0;a[i]!='\0';i++)
printf("%c",a[i]);    
}

Upvotes: 1

2501
2501

Reputation: 25753

The array, which has the type char, is used to store integers, the array isn't a string. Because you store remained of division by 2, most elements will have the value 0.

Remove the line that null terminates the array. The variable i already counts the number of elements entered, so iterate and print until you print i elements.

Upvotes: 3

Related Questions