Program to reverse an integer entered by the user in C++ programming.
C++ Program to Reverse a Number :
This problem is solved by using while loop in this Program.
This program takes an integer input from the user and stores it in variable num.
The main logic of the program is in the while loop. The while loop will run till the number is greater than 0.
While loop is iterated until num != 0 is false.
In each iteration, the remainder when the value of num is divided by 10 is calculated, reverse is computed and the value of num is decreased 10 fold.
The while loop is mostly used in the case where the number of iterations is not known in advance.
Source Code:
#include <iostream>
/* iostream provides basic
input and output services for C++ programs */
using namespace std;
int main()
// Th execution of program start with the main function
{
int num, reverse=0, rem;
//Variable Declarations specify the type followed by the name
//Initialization is the process of assign the value to a variable
cout<<"Enter a number: ";
// cout is used to display the same statement in the output.
cin>>num;
// cin is used to enter the value by the user.
while(num!=0)
/*The while loop is used to repeat a
section of code an unknown number of
times until a specific condition is met*/
{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}
cout<<"Reversed Number: "<<reverse<<endl;
return 0;
}
0 Comments