Skip to content
Related Articles

Related Articles

Improve Article

C Program to Print all digits of a given number

  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2020

Given a number N, the task is to write a C program to print all digits of the number N in their original order.

Examples:

Input: N = 12
Output: 1, 2

Input: N = 1032
Output: 1, 0, 3, 2

Method 1: The simplest way to do is to extract the digits one by one and print it.



  1. Extract the last digit of the number N by N%10, and store that digit in an array(say arr[]).
  2. Update the value of N by N/10 and repeat the above step till N is not equals to 0.
  3. When all the digits have been extracted and stored, traverse the array from the end and print the digits stored in it.

Below is the implementation of the above approach:




// C program of the above approach
  
#include <stdio.h>
#define MAX 100
  
// Function to print the digit of
// number N
void printDigit(int N)
{
    // To store the digit
    // of the number N
    int arr[MAX];
    int i = 0;
    int j, r;
  
    // Till N becomes 0
    while (N != 0) {
  
        // Extract the last digit of N
        r = N % 10;
  
        // Put the digit in arr[]
        arr[i] = r;
        i++;
  
        // Update N to N/10 to extract
        // next last digit
        N = N / 10;
    }
  
    // Print the digit of N by traversing
    // arr[] reverse
    for (j = i - 1; j > -1; j--) {
        printf("%d ", arr[j]);
    }
}
  
// Driver Code
int main()
{
    int N = 3452897;
  
    printDigit(N);
    return 0;
}
Output:
3 4 5 2 8 9 7

Time Complexity: O(log10 N)
Auxiliary Space: O(log10 N)

Method 2: Using Recursion

  1. Recursively iterate till N become 0:
    • Base Case: If the value of N is 0, exit from the function.
      if(N==0) 
        return ;
      
    • Recursive Call: If the base case is not met, recursively call for next iteration by updating N to N/10 and print the value of last digit extracted(say r) from the number N, after recursive call.
      recursive_function(N/10);
      print(r);
      

Below is the implementation of the above approach:




// C program of the above approach
  
#include <stdio.h>
  
// Function to print the digit of
// number N
void printDigit(int N)
{
    int r;
  
    // Base Case
    if (N == 0) {
        return;
    }
  
    // Extract the last digit
    r = N % 10;
  
    // Recursive call to next
    // iteration
    printDigit(N / 10);
  
    // Print r
    printf("%d ", r);
}
  
// Driver Code
int main()
{
    int N = 3452897;
  
    printDigit(N);
    return 0;
}
Output:
3 4 5 2 8 9 7

Time Complexity: O(log10 N)
Auxiliary Space: O(1)

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.




My Personal Notes arrow_drop_up
Recommended Articles
Page :