0

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.

  • 3
    Please try to explain the code to your [rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). Especially what is the value of `i` once the first loop ends? Is that value of `i` an index of one of the digits in the number? Also, what is the first index of your array `arr`? Will the printing loop include that index? – Some programmer dude May 23 '22 at 11:05
  • Please don't post pictures of text. Post text as properly formatted text. Your output is text. You can copy/paste your output. – Jabberwocky May 23 '22 at 11:05
  • 1
    And generally, this is the perfect case to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs, and how to use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – Some programmer dude May 23 '22 at 11:08
  • Your initial value for `j` is wrong, since it should start at `i-1` and continue until `j>=0` – Itai Dagan May 23 '22 at 11:09
  • For small codes, use https://www.onlinegdb.com/ for debugging. It is really helpful. – Avinash May 23 '22 at 11:13
  • @Itai Dagan Thank You! But why should we initialise j to i-1 and not i? – Citizen Of Earth May 23 '22 at 11:19

1 Answers1

-1

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;
    }
}
Poder Psittacus
  • 94
  • 1
  • 10