C++ | Program That Accept 6-digits integer and then print back in reverse order



So here is the code and the explanation below :

#include <iostream>
using namespace std; // else you need to code like this std::cout << "blablah";

int main() {
    int n, d;
    int i = 0, total=0;
    cout << "Enter number:";
    cin >> n;
    cout << "\nThe reverse number is : " << endl;
    while (i <= 5)
    {
        d = n%10; // n remainder 10
        total = total + d;
        cout << d << endl; // print out remainder
        n = n/10; // integer divide by 10
        i++; 
    }

    cout << "\nThe sum of the six digits is = " << total << endl ;
    return 0;
}


This program simply accept 6 digits number. ( well you can actually modify it for more )
But for the purpose to finish up my assignment, I keep it simple.  The 6 digits integer is stored in integer n which is actually a single integer (etc: 12456). And then it will enter the reversal loop, (the while loop).

This "while" loop count This loop actually find the remainder of the integer 123456 divide by 10 and store it in d. This method will get the last digits of a the number. Integer d temporarily store all the remainder which will be sum up in total. The initial value of total is 0. (total = 0) and then added by 6. then 5, 4, 3, 2, 1. and thus total sum of those number is 21. And it actually print out each remainder stored in d.  After the remainder is print out, integer n is divide by 10 (etc: 123456 / 10 ). As integer only holds integer and ignore floating points, so integer n is now 12345. And the cycle continue until i is more than 5 which will break the loop and print out the total sum of the 6 digits.

(* I used Code::Blocks the open source cross-platform IDE on windows 7)

So here is the sample output:


Popular posts from this blog

Extra : Play DOTA 2 Offline The Simplified Way

Create a Custom Blogger Header Part 2

Tips Tingkatkan Kelajuan Blog