Home > OS >  Digit output in C
Digit output in C

Time:11-09

Hello everyone I'm a beginner in coding and I try to figure out how to output all the digits. Example in the number 158 the number 1,5,8,15,58,158. Sorry for the bad English.

I have tried something but it doesnt work for all numbers plus i believe there must be a better way to code it without all the while loops.

    #include <stdio.h>

int main(){
    long num = 5025;
    int num1=num ,num2= num, num3=num;
   
    while(num1 !=0)
    {
        int digit = num1 % 10;
        num1 = num1/10;
        printf("%d\n", digit);
    } 
    while(num2 >10)
    {
        
        int digit = num2 % 100;
        
        num2 = num2 / 10;
                
        printf("%.2d\n", digit);
    }
    while(num3 >100)
    {
        
        int digit = num3 % 1000;
        
        num3 = num3 / 10;
                
        printf("%.3d\n", digit);
    }
    
    return 0;
}

CodePudding user response:

One could print to a string and then post its various combinations

  long num = 158;
  char buf[25];
  snprintf(buf, sizeof buf, "%ld", num);

  for (int first = 0; buf[first]; first  ) {
    for (int last = first; buf[last]; last  ) {
      int width = last - first   1;
      printf("%.*s\n", width, buf   first);
    }
  }

Output

1
15
158
5
58
8

Depending on the value, you may get repeats. OP has not yet defined what to do in that case.


For a math only approach, I'd use recursion, yet I expect that is beyond OP's ken at this time.

CodePudding user response:

Without fancy printf formats:

void print(unsigned num)
{
    char nums[20];
    size_t len;

    len = sprintf(nums, "%u", num);

    for(size_t seql = 1; seql <= len; seql  )
    {
        for(size_t ndig = 0; ndig < len - seql   1; ndig   )
        {
            for(size_t dig = 0; dig < seql; dig  )
            {
                printf("%c", nums[dig   ndig]);
            }
            printf("%c", seql == len ? '\n' : ',');
        }
    }
}

int main(void)
{
    print(15895678);
}
  •  Tags:  
  • c
  • Related