Search code examples
ccodeblocks

Why does the array print zero in the beginning with the last digit missing?


I am trying to separate digits of a number and print those individual digits. When I do this -:

#include <stdio.h>
#define size 100

int main()
{
    int num, remainder, arr[size], i=0;

    printf("Enter a number : ");
    scanf("%d", &num);

    while(num != 0)
    {
        remainder = num%10;
        arr[i]=remainder;
        i++;
        num /= 10;
    }

    for(int j=i; j>0; j--)
        printf("%d\t", arr[j]);

    printf("\n");

    return 0;
}

It shows -:

Output

I don't know the reason as to why it's happening. Please help me.

Thank You.


Solution

  • This should work:

    #include <stdio.h>
    #define size 100
    
    int main()
    {
        int num, remainder, arr[size], i=0;
    
        printf("Enter a number : ");
        scanf("%d", &num);
    
        while(num != 0)
        {
            remainder = num%10;
            arr[i]=remainder;
            i++;
            num /= 10;
        }
    
        for(int j=i-1; j>=0; j--)
            printf("%d\t", arr[j]);
    
        printf("\n");
    
        return 0;
    }
    

    I have changed for(int j=i; j>0; j--) with for(int j=i-1; j>=0; j--).

    Or use this code, it is faster can also accepted 0 and any int value

    #include <stdio.h>
    
    int main()
    {
        int num;
        int i = 1000000000;
        int first_index = 0;
    
        printf("Enter a number : ");
        scanf("%d", &num);
    
        while (i>1){
       
           if((num%i*10)/i == 0 && first_index == 0){
               i = i/10;
               if(i==1){
                   printf("0");
               }
               continue;
           }
           first_index = 1;
           printf("%d ", (num%i*10)/i);
           i = i/10;
        }
    }