Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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--).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading