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.
- Extract the last digit of the number N by N%10, and store that digit in an array(say arr[]).
- Update the value of N by N/10 and repeat the above step till N is not equals to 0.
- 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:
#include <stdio.h>
#define MAX 100
void printDigit( int N)
{
int arr[MAX];
int i = 0;
int j, r;
while (N != 0) {
r = N % 10;
arr[i] = r;
i++;
N = N / 10;
}
for (j = i - 1; j > -1; j--) {
printf ( "%d " , arr[j]);
}
}
int main()
{
int N = 3452897;
printDigit(N);
return 0;
}
|
Time Complexity: O(log10 N)
Auxiliary Space: O(log10 N)
Method 2: Using Recursion
- Recursively iterate till N become 0:
Below is the implementation of the above approach:
#include <stdio.h>
void printDigit( int N)
{
int r;
if (N == 0) {
return ;
}
r = N % 10;
printDigit(N / 10);
printf ( "%d " , r);
}
int main()
{
int N = 3452897;
printDigit(N);
return 0;
}
|
Time Complexity: O(log10 N)
Auxiliary Space: O(1)