user14253580
user14253580

Reputation:

How to split an arbitrary long input integer into pair of digits?

Expected Input:

123456

Expected output:

 12
 34
 56

I have tried in this way

#include <stdio.h>
int main()
{
    // Put variables for further proceed
    int number, remainder, quotient = 1, numberUpdate, count = 0;
    int value = 10000;
   
  /*This for input validation. User can give exactly 6 digit as an input If 
   user breaks this condition then It 
   will redirect back to take input again */ 

    while (1)
    {
        int countUpdate = 0;
        int quotientUpdate = 1;
        printf("Enter a number: ");
        scanf("%d", &number);
        numberUpdate = number;
        while (quotientUpdate != 0)
        {
            quotientUpdate = numberUpdate / 10;
            numberUpdate = quotientUpdate;
            countUpdate++;
        }

        if (countUpdate > 6 || countUpdate < 6)
        {
            printf("It allows exactly 6 digits\n");
        }
        else
        {
            break;
        }
    }
   
   //This for finding the pair of two consecutive digits.

    while (quotient != 0)
    {
        count++;

        if (count == 4)
        {
            break;
        }
        quotient = number / value;
        remainder = number % value;
        if (count != 2)
            printf("%d\n", quotient);
        if (count == 1)
        {
            number = remainder;
        }
        else
        {
            number = quotient;
        }

        if (count == 1)
        {
            value = value / 1000;
        }

        if (count == 3)
        {
            remainder = remainder * 10 + 6;

            printf("%d\n", remainder);
        }
    }

    return 0;
}

My problem is: I have made this for the exact input 6 digits. From my code, I did not get the expected output. Output comes from my code like: If a user gives an input 987654 Output shows:

     98
     76
     56

But my expectation is:

     98
     76
     54

Here is another problem: this code does not work for less than 6 or greater than 6 digits. But I want to solve this problem for any number of digit.

Can you help me identifying and solving my problem?

Upvotes: 1

Views: 319

Answers (4)

Roberto Caboni
Roberto Caboni

Reputation: 7490

Before proposing my solution, I'll try to explain what's wrong in your code.

Analysis of the original code

First of all, since you have currently the fixed length limitation, your loop that checks if the number has exactly 6 digits can be omitted; the same check can be performed just checking the range:

if (number < 1000000 || number > 999999)
{
    printf("It allows exactly 6 digits\n");
}
else
{
    break;
}

The core of your logic is in the loop while (quotient != 0). It contains a lot of strange attempts you perform in order to compensate the previous mistake. It leads to the final reminder with a single digit instead of two, so you try to compensate it with this line

remainder = remainder * 10 + 6;

this obviously works only if the last digit is 6.


The root of the problem is in this row:

if (count == 1)
{
    value = value / 1000;
}

But why 1000? value represents the divider in the next loop, so you want it to obtain a reminder with two digit less (instead of 3), so the correct division is value = value / 100;.

All the subsequent correction come after this one. The other answers widely cover the correct solution storing the input within an integer.


A solution involving strings

Since you need a solution with any number of digits, you must be aware that using an int you'll be able to manage at most 10 digits (because the maximum value of an integer is INT_MAX (2147483647).

Using an integer you'll only be limited by the size of the string buffer you choose.

That's the code. Our only limitation is forcing the user to insert only an even number of digits:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    // Put variables for further proceed
    char number[101] = { 0 };
    int isValid = 0, count = 0;
   
    /*Input validation */
    while(!isValid)
    {
        count = 0;
        isValid = 1;
        char *p = number;

        printf("Enter a number: ");
        scanf("%100s", number);
        
        /* Check the validity of the string */
        while(*p != '\0')
        {
            count++;
            if(!isdigit(*p))
            {
                isValid = 0;
                break;
            }
            p++;
        }

        if( !(isValid = isValid && ( count % 2 == 0 ) ) )
          printf("Please insert an even number of digits (numbers only)\n");
    }
   
    /* Print the digits*/
    for(int i=0; i<count; i+=2)
        printf("%c%c\n", number[i], number[i+1] );

    return 0;
}
  • I defined an array of 101 characters (100 + one for the string terminator) and I say scanf to store up to 100 characters (%100s)
  • I complicated a bit the input validator just to avoid to loop twice through the string (the first using strlen(), needed to check the even digits requirement,and the second to check the digits-only requirement)
  • In the end I just print two characters at a time using %c format specifier reading them from the string number

The output:

Enter a number: 1234567      // Test the check on an input with an odd number of digits
Please insert an even number of digits (numbers only)
Enter a number: 1234567A     // Test the check on an input containing a non-digit char
Please insert an even number of digits (numbers only)
Enter a number: 1234567890123456     // Well formed input
12
34
56
78
90
12
34
56

Upvotes: 1

Drumil
Drumil

Reputation: 21

Here is my solution to this problem. Hope it satisfy your requirement.

#include <stdio.h>
int main()
{
    // Put variables for further proceed
    int number, remainder, quotient = 1, numberUpdate, temp,count = 0;
    int value = 1;
    printf("Enter a number: ");
    scanf("%d", &number);
    numberUpdate = number;
    temp = number;
    if(number < 100) {
        printf("%d",number);
    } else {
        while(numberUpdate > 100) {
            value = value*100;
            numberUpdate = numberUpdate/100;
        }
        while (temp > 0)
        {
            temp = number/value;
            number = number%value;
            value = value/100;
            printf("%d\n",temp);
        }
    }
    return 0;
}

Upvotes: 0

Cirrus Minor
Cirrus Minor

Reputation: 394

I've updated your code a bit, it should be working and handle the "0" digit within the code. For the "0" digit at the beginning of the code, you should input a string and not a number.

#include <stdio.h>
int main()
{
    // Put variables for further proceed
    int number, remainder, quotient = 1, numberUpdate, count = 0;
    int countUpdate = 0;
    int value = 10000;
   
  /*This for input validation. User can give exactly 6 digit as an input If 
   user breaks this condition then It 
   will redirect back to take input again */ 

    while (1)
    {
        int quotientUpdate = 1;
        printf("Enter a number: ");
        scanf("%d", &number);
        numberUpdate = number;
        while (quotientUpdate != 0)
        {
            quotientUpdate = numberUpdate / 10;
            numberUpdate = quotientUpdate;
            countUpdate++;
        }

        if (countUpdate < 2 || countUpdate % 2 != 0)
        {
            printf("Even number of digits only\n");
        }
        else
        {
            break;
        }
    }
   
   count = countUpdate / 2;
   numberUpdate = number;
   int d[count];
   for (int i = 0; i < count; i++)
   {
       d[i] = numberUpdate % 100;
       numberUpdate /= 100;
   }
   for (int i = count - 1; i >= 0; i--)
   {
       if (d[i] < 10) printf("0");
       printf("%d\n", d[i]);
   }

    return 0;
}

Upvotes: 1

Gerhardh
Gerhardh

Reputation: 12404

Your solution is a bit overcomplicated. If you want to use integers, you could do it like this (untested). Depending on range for your number, you might change to long long.

#include <stdio.h>
int main(void)
{
    int number;
    int digits = 1;
   
    while (digits & 1)
    {  // loop until we get an even number
        printf("Enter a number: ");
        int ret = scanf("%d", &number);
        if (ret != 1)
            continue;

        // count number of digits
        digits = 0;
        while (number != 0)
        {
            number /= 10;
            digits++;
        }

        if (digits & 1)
            printf("Please enter even number of digits.\n");
    }

    // If we are here, we have 2, 4, 6, ... digits

    // Calculate divider to chop first 2 digits
    int divider = 1;
    while (digits > 2)
    {
        divider *= 100;
        digits -= 2;
    }

    // chop remaining digits and print 2 of them
    while (divider)
    {
        pair = (number / divider) % 100;
        printf("%d\n", pair);
        divider /= 100;         
    }  
    return 0;
}

Another option would be to use strings instead of numbers and then simply print 2 characters per line.

Upvotes: 1

Related Questions