Advertisement
dmilicev

extracting_digits_from_a_number.c

Dec 15th, 2019
275
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     extracting_digits_from_a_number.c
  4.  
  5.  
  6.  
  7.     You can find all my C programs at Dragan Milicev's pastebin:
  8.  
  9.     https://pastebin.com/u/dmilicev
  10.  
  11. */
  12.  
  13. #include <stdio.h>
  14.  
  15. // extract digits from number into array digits[]
  16. // returns the number of extracted digits
  17. int extract_digits_from_number( int number, int digits[20] )
  18. {
  19.     int i, j, number_of_digits = 0, mem;
  20.  
  21.     while( number != 0 )
  22.     {
  23.         digits[number_of_digits++] = number % 10;   // fill array digits[]
  24.         number = number / 10;
  25.     }
  26.  
  27.     // reverse first number_of_digits elements of array digits[]
  28.     for ( i=0, j=number_of_digits-1; i<number_of_digits/2; i++, j-- )
  29.     {
  30.         mem = digits[i];
  31.         digits[i] = digits[j];
  32.         digits[j] = mem;
  33.     }
  34.  
  35.     return( number_of_digits );
  36.  
  37. } // extract_digits_from_number
  38.  
  39.  
  40. int main(void)
  41. {
  42.     int number;             // our number
  43.     int digits[10];         // array to store digits of number
  44.     int number_of_digits;
  45.     int i;
  46.  
  47.     printf("\n Enter number = ");
  48.     scanf("%d",&number);
  49.  
  50.     number_of_digits = extract_digits_from_number( number, digits );
  51.  
  52.     printf("\n Digits of number %d are: \n", number );
  53.  
  54.     for( i=0; i<number_of_digits; i++ )
  55.         printf("\n %d \n", digits[i] );
  56.  
  57.  
  58.     return 0;
  59.  
  60. } // main()
Advertisement
RAW Paste Data Copied
Advertisement