6

Getting digits from a number beginning from the least significant in C is pretty easy:

#include <stdio.h>

int main()
{
    int num = 1024;

    while(num != 0)
    {
        int digit = num % 10;
        num = num / 10;
        printf("%d\n", digit);
    }


    return 0;
}

But how to extract digits beginning from the first digit (here 1), that the solution could be applied to any number?

It would be trivial with arrays, but I don't want to use array, and I don't want to use logical operators.

6
  • Divide by 1000, 100, 10, 1. Nov 1, 2014 at 10:45
  • Say your number is 12, what will 12 & F0 will give? What if you shift it (FO) right by 4 and do bitwise and again?
    – SMA
    Nov 1, 2014 at 10:45
  • 1
    OR fill an array with the digits, then reverse that array. Nov 1, 2014 at 10:45
  • @BasileStarynkevitch: it would be trivial with array, but I dont want to use array, as I dont want to use logical operators. Nov 1, 2014 at 10:46
  • Why don't you want to use an array? Nov 1, 2014 at 10:48

6 Answers 6

5

The following program does what you want:

#include <stdio.h>

int main()
{

    int num =0;
    int power=1;

    printf("Enter any number:");
    scanf("%d",&num);

    while(num>power)
      power*=10;

    power/=10;

    while(num != 0)
    {
        int digit = num /power;
        printf("%d\n", digit);
        if(digit!=0)
          num=num-digit*power;
        if(power!=1)
          power/=10;
    }



    return 0;
}
4
  • ... right up until the point that num is greater than the largest power of ten that can be contained in an int, or when num is 1. Then it will fall in a screaming heap.
    – paxdiablo
    Nov 24, 2014 at 7:38
  • The first problem arises because you're trying to find the first power of ten above the number but, at some point, multiplication will wrap around. You can detect this by checking if power * 10 is actually less than power, which it will be on wraparound. The second problem is divide by zero for an input of one. That may be fixable by looping based on power rather than num.
    – paxdiablo
    Nov 24, 2014 at 7:44
  • @paxdiablo ,First of all,Thanks for looking at my answer. Will adding if(power>power*10){printf("The number is too large");return -1;} inside the body of the first while loop before power*=10; solve the first problem?
    – Spikatrix
    Nov 24, 2014 at 9:03
  • @paxdiablo , And will putting the first power/=10 inside this condition if(num>1) solve the second issue?
    – Spikatrix
    Nov 24, 2014 at 9:04
2

Assuming a 32 bit signed number that is positive, then as a simple example:

#include <stdio.h>

int main()
{
int rmdr;
int dvsr;
int quot;
    scanf("%d", &rmdr);               // read in number
    dvsr = 1000000000;
    while(0 >= (quot = rmdr / dvsr)){ // skip leading zeroes
        rmdr %= dvsr;
        dvsr /= 10;
        if(dvsr == 1)
            break;
    }
    while(dvsr){                      // display number
        quot = rmdr / dvsr;
        printf("%1d", quot);
        rmdr %= dvsr;
        dvsr /= 10;
    }
    printf("\n");
    return(0);
}

or a slight optimization:

int main()
{
int rmdr;
int rm10;
int dvsr;
int quot;
    scanf("%d", &rmdr);               // read in number
    rm10 = rmdr/10;
    dvsr = 1;
    while(dvsr <= rm10)               // skip to 1st digit
        dvsr *= 10;
    while(dvsr){                      // display number
        quot = rmdr / dvsr;
        printf("%1d", quot);
        rmdr %= dvsr;
        dvsr /= 10;
    }
    printf("\n");
    return(0);
}
4
  • and what if I use scanf to read the number? the solution is great but will fail, because I dont know what number user will give - anyway - thank you Nov 1, 2014 at 10:57
  • @BrianBrown - added a second more optimized example.
    – rcgldr
    Nov 1, 2014 at 18:44
  • @Z1zw4r - thanks for the suggested edit. The edit to the second example was approved and the answer updated.
    – rcgldr
    Dec 10, 2017 at 21:04
  • @BrianBrown - A correction to the second example was made by Z1zw4r, changing while(dvsr < rm10) to while(dvsr <= rm10) . Before this fix, if the input was a power of 10, the first instance of quot would be 10, a 2 digit number, when the goal is a single digit number. This was masked by the printf("%1d", quot); since it would print a 2 digit number despite the %1d format string.
    – rcgldr
    Dec 10, 2017 at 21:06
1

If you don't want to use array, a simple solution will be..

  • Take Input from the user.

  • Reverse the number.

  • And then print the digits.

    #include<stdio.h>
    #include <math.h>
    
    int reversDigits(int num)
    {
    int rev_num = 0;
    while(num > 0)
    {
    rev_num = rev_num*10 + num%10;
    num = num/10;
    }
    return rev_num;
    }
    
    int main() {
    int i = 1024;
    int number = reversDigits(i);
    while(number != 0)
    {
        int digit = number % 10;
        number = number/ 10;
        printf("%d\n", digit);
    }
    return 0;
    }
    
1
  • OP said "I don't want to use arrays"
    – Spikatrix
    Nov 1, 2014 at 10:55
0

Try to store the return value in integer or character array.

So I can print the value as we required.

If we use character array we can easily find the length and get the result easily.

#include <stdio.h>
#include<string.h>
int main()
{
    int num = 1024;
char a[10];
        int i=0;
    while(num != 0)
    {
        a[i++] = (num % 10)+'0';
        num = num / 10;

    }
    a[i]='\0';
    printf("%s",a);
    return 0;

}

1
  • 1
    He asked without using arrays.
    – Vynylyn
    Sep 19, 2022 at 11:26
0

I know the question has been answered, but I shall post this answer in case anyone finds it useful.

#include<stdio.h>

//get_int_first gets each digit and multiplies it by it's placeholder value.
// the number is reconstructed and returned to main

int get_int_first(int num){
    int power = 1,len = 0,first = 0,i = 0;
    int number = 0;

    while (num>power){                                          
        power=power*10;                                 //calculating number of zeroes in number. for 789, power = 10 -> 100 -> 1000
    }
    power = power/10;                                   // to multiply with power directly and get highest placeholder, we divide by 10. now power = 100

    while (power>1){                                    
        first = (num/power);                            //get digits from the leftmost(100th placeholder/nth placeholder)  f = 7                    f = 8
        number = number + first*power;                  //first*power = gives number as                                    nb = 0 +7*100 = 700      nb = 700 + 80
        num = num - (power*(first));                    //change number to get next significant digit from left            n = 789 - (100*7) = 89   n = 89-10*8=9
        power = power/10;                               //change power to divide number by appropriate power.              p = 100/10 = 10          p = 1
    }
    number = number + num;                              //number is missing the unit's digit and it is stored in num. thus, it is added to number
    return number;
}


int main() {

    printf("digits are %d\n",get_int_first(789));
    return 0;
}
0

Here is my try. Works for positive numbers only. Max range 2^64 (unsigned long long)

#include <iostream>
#include <cmath>

using namespace std;
using bignum = unsigned long long;

inline
bignum Power(unsigned x, unsigned y) {
    return y>0 ? x*Power(x,y-1) : 1;
}

// return digits count in a number
inline
int Numlen(bignum num) {
    return num<10 ? 1 : floor(log10(num))+1;
}

// get the starting divisor for our calculation
inline
bignum Getdivisor(unsigned factor) {
    return Power(10, factor);
}


int main()
{
    bignum num{3252198};
    //cin >> num;

    unsigned numdigits = Numlen(num);    
    auto divisor = Getdivisor(numdigits-1);

    while(num > 0) {

        cout << "digit = " << (num/divisor) << "\n";

        num %= divisor;
        divisor /= 10;
    }
}

/*
output:
digit = 3
digit = 2
digit = 5
digit = 2
digit = 1
digit = 9
digit = 8
*/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.