Define the numbers in the given number.

I am new to programming and I have a problem. I want my program to identify individual digits in a given number, for example, if I entered 4692, it should identify the numbers and print 4 6 9 2. And yes, without using arrays.

+3
source share
6 answers

An ideal recursion problem to solve if you are new to programming ...

4692/1000 = 4

4692% 1000 = 692

692/100 = 6

692% 100 = 92

92/10 = 9

92% 10 = 2

You should get the idea of ​​a loop that you should use now so that it works for any number. :)

+26

C , .

int i = 12345;

while( i > 0 ){
   int nextVal = i % 10;
   printf( "%d", nextVal );
   i = i / 10;
}
+1

Simple and nice

void PrintDigits(const long n)
{
    int m = -1;
    int i = 1;

    while(true)
    {
        m = (n%(10*i))/i;
        i*= 10;
        cout << m << endl;

        if (0 == n/i)
            break;
    }
}
+1
source

Here is a simple solution if you just want to print numbers from a number.


#include 
/**
 printdigits
*/
void printDigits(int num) {

  char buff[128] = "";
  sprintf(buff, "%d ", num);
  int i = 0;
  while (buff[i] != '\0') {
     printf("%c ", buff[i]);
     i++;
   }
  printf("\n");
}
/*
 main function
*/
int main(int argc, char** argv) {
   int digits = 4321;
   printDigits(digits);
   return 0;
}

0
source

I think the idea is to print unarmed numbers (otherwise it would be too easy) ... well, you can track already printed integers without having an array encoding them in another whole.

some pseudo C to give you the key:

int encoding = 0;
int d;

while (keep_looking()) {
  d = get_digit();
  if (encoding/(2**d)%2 == 0) {
    print(d);
    encoding += 2**d;
  }
}
0
source

Is it right

int main()

    {

        int number;

        cin>>number;

        int nod=0;

        int same=number;

        while(same)

        {

            same/=10;

            nod++;

        }

        while(nod--)

        cout<<(int)number/(int)pow10(nod)%10<<"\t";


        return 0;
    }
-1
source

Source: https://habr.com/ru/post/1710249/


All Articles