Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Breaking down a number into digits – C

I’m trying to create a program that breaks down a number into its component digits.

The code I’ve written so far is as follows:

#include <stdio.h>

int main() {

int num;
int digits;
int count = 1;

printf("Insert a positive number: ");

do {

    scanf("%d", &num);

} while (num <= 0);

printf("In digits... \n");

// Number in digits
while (num != 0) {
    digits = num % 10;
    printf("Digit %d --> %d \n", count, digits);
    num /= 10;
    count++;
}

}

The digits of the number are printed correctly, but in reverse order!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Insert a positive number: 345
In digits...
Digit 1 --> 5
Digit 2 --> 4 
Digit 3 --> 3 

I can’t figure out how to fix this, can anyone help me?

>Solution :

Using your code plus code available on https://www.geeksforgeeks.org/c-program-to-print-all-digits-of-a-given-number/ (google is your friend!)

#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;
    printf("Insert a positive number: ");

do {

    scanf("%d", &N);

} while (N <= 0);

printf("In digits... \n");
  
    printDigit(N);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading