INTEGER DIVISION AND REMAIN


In the module "Arithmetic Expressions" we talked about the features of the division operation in C ++.
Recall that for integer data (type int), you can use two division operations.
/ - integer division, when the fractional part is discarded as a result of the division operation
% - calculation of the remainder of the division

ЗАПОМНИМ!
n C and C ++, the result of dividing an integer by an integer is always an integer, the remainder when dividing is discarded.

Пример:
int a, b;
a = 10;
b = 3;
int c = a / b;   // Answer: с = 3
int d = a% b;    // Answer: d = 1
These operations are very important in programming. They need to be understood and used correctly. And this requires practice!

 

The need to use the operation of calculating the remainder of the division is visible when working with digits of a number.

Task:
A three-digit number is given. Display all the digits of this number on the screen and get a new number formed by a permutation of units and hundreds

The most difficult question that arises for beginners is how to get and get its numbers from a number.
In fact, everything is solved quite simply, if you recall the mathematics. And mathematics tells us that any number can be decomposed into the sum of the bit terms.
For example: 365=3*100+6*10+5*1 . We see that each digit is a factor of the corresponding digit. 
  
Select all digits of the number in separate variables
e = n % 10;        //  operator n % 10   - units of the number n 365 % 10 = 5 

d = n / 10 % 10;   // operator n / 10 - reduces the number by 10 times, that is, it discards the last digit from the number (365 / 10 = 36), 
                   // Now we can calculate the number of tens by applying the familiar operation to the result - calculate the remainder of the division by 10, 36 % 10 = 6
 
s = n / 100;       // to get hundreds, it’s enough to discard two digits from the number on the right, that is, divide twice by 10  (n / 10 /10 or n / 100) 365 / 100 = 3

Having the stored digits of a number, we can make any number from them, multiplying the desired digit by the corresponding digit:
for example, the line below will get a new number from the original number n, which has hundreds and ones rearranged:
1) the old number of units (stored in variable e) is multiplied by 100
2) the old number of tens (stored in the variable d) is multiplied by 10
3) we can multiply the old number of hundreds simply by 1, or simply take the value stored in the variable s
Then the values from points 1, 2 and 3 are simply added up and we get a new number:

n1 = e * 100 + d * 10 + s;

The whole program will look like this:
#include<iostream>
using namespace std;
main()
{
  int n, e, d, s;
  cin >> n;
  e = n % 10;     
  d = n / 10 % 10;  
  s = n / 100;
  cout << e << " " << d << " " << s << " " << e * 100 + d * 10 + s;
}