/*
6.24 (Separating Digits) Write program segments that
accomplish each of the following:
A. Calculate the integer part of the quotient when integer is
divided by integer .
B. Calculate the integer remainder when integer is divided
by integer .
C. Use the program pieces developed in (a) and (b) to write a
function that inputs an integer between and and
prints it as a series of digits, each pair of which is separated
by two spaces. For example, the integer should print
as follows:
*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void numberSeparatedDigits(int);
int main(int argc, char** argv)
{
int numero;
cout << "Enter NUMBER between 1 - 32767 ----> ";
cin >> numero;
cout << "The number separeted in digits: " ;
numberSeparatedDigits(numero);
return 0;
}
void numberSeparatedDigits(int number)
{
int store = 0;
int store2 = 0;
if(number > 0)
{
if(number < 10)
{
store = number / 1;
cout << store;
}
//case for a number with 2 digits
elseif(number < 100)
{
store = number / 10;
store2 = number % 10;
cout << store << " ";
store = store2 / 1;
cout << store;
}
//if the number contains 3 digits
elseif(number < 1000)
{
store = number / 100;
store2 = number % 100;
cout << store << " ";
store = store2 / 10;
cout << store << " ";
store2 = number % 10;
store = store2 / 1;
cout << store;
}
//four digits
elseif(number < 10000)
{
store = number / 1000;
store2 = number % 1000;
cout << store << " ";
store = store2 / 100;
cout << store << " ";
store2 = number % 100;
store = store2 / 10;
cout << store << " ";
store2 = number % 10;
store = store2 / 1;
cout << store;
}
//Finallly 5 digits
elseif(number < 100000)
{
store = number / 10000;
store2 = number % 10000;
cout << store << " ";
store = store2 / 1000;
cout << store << " ";
store2 = number % 1000;
store = store2 / 100;
cout << store << " ";
store2 = number % 100;
store = store2 / 10;
cout << store << " ";
store2 = number % 10;
store = store2 / 1;
cout << store;
}
}
}
Not bad, you solved C before A and B. Now analyse your solution what may be used for A and what for B. (Hint: just look at your 5-digits procedure, what is constant, what changes.)
#include <iostream>
void print_seperate_digits( int number )
{
constchar separator[] = " " ; // two spaces
if( number < 0 ) // if the number is negative
{
std::cout << '-' << separator ; // print a negative sign
print_seperate_digits( -number ) ; //and then the digits of the positive number
}
// invariant: when we reach this point, number >= 0
elseif( number < 10 ) std::cout << number << separator ; // if it is a single digit number, print the digit
else // two or more digits
{
print_seperate_digits( number/10 ) ; // print the more significant digits
std::cout << number%10 << separator ; // print the last digit
}
}int main()
{
for( int n : { 0, -123456, 98765432 } )
{
std::cout << n << " => " ;
print_seperate_digits(n) ;
std::cout << '\n' ;
}
}