Reverse of Entered Number

Beginner

Introduction

In this lab, we will learn how to find the reverse of the given number, in the C++ programming language. The concept of finding the reverse of the entered number can be used to check for Palindrome.

Create a C++ Source File

First, we need to create a C++ source file in the ~/project directory. Open the terminal and type the command below to create a file named main.cpp:

touch ~/project/main.cpp

Then use a text editor to edit the main.cpp file.

Write the C++ Code

Add the following code to the main.cpp file, which will find the reverse of a given number.

#include <iostream>
#include <math.h>

using namespace std;

//Returns the reverse of the entered number
int findReverse(int n)
{
    int reverse = 0; //to store the reverse of the given number
    int remainder = 0;

    //logic to compute the reverse of a number
    while (n != 0)
    {
        remainder = n % 10; //store the digit at the units place
        reverse = reverse * 10 + remainder;
        n /= 10;
    }

    return reverse;
}

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " ===== Program to compute the Reverse of the entered number. ===== \n\n";

    //variable declaration
    int n;
    int reverse = 0;

    //taking input from the command line (user)
    cout << " Enter a positive integer to find the reverse of :  ";
    cin >> n;

    //Calling a method that returns the reverse of an entered number
    reverse = findReverse(n);

    cout << "\n\nThe entered number is " << n << " and it's reverse is :" << reverse;

    cout << "\n\n\n";

    return 0;
}

This code snippet defines two functions, findReverse, and main. findReverse takes any integer as an argument and returns the reversed number. main is the main function of the program, which takes input from the user and calls findReverse to return the reversed number.

Compile and Run the C++ Code

To compile and run the program, type the following command in the terminal:

g++ ~/project/main.cpp -o ~/project/main && ~/project/main

Summary

In this lab, we learned how to find the reverse of a given number in the C++ programming language. This concept can be used to check for Palindrome. By using loops we can break down each number of the given integer and reverse it, to find the final reversed value. We also learned how to compile, run, and test this C++ program.

Other Tutorials you may like