top of page

7) Reverse Number

We can reverse a number in c++ using loop and arithmetic operators. In this program, we are getting number as input from the user and reversing that number.

Write a c++ program to reverse given number.

Input: 123

Output: 321

Let's see a simple c++ example to reverse a given number.

back.png

#include <iostream>  

using namespace std;  

int main()  

{  

int n, reverse=0, rem;    

cout<<"Enter a number: ";    

cin>>n;    

  while(n!=0)    

  {    

     rem=n%10;      

     reverse=reverse*10+rem;    

     n/=10;    

  }    

 cout<<"Reversed Number: "<<reverse<<endl;     

return 0;  

}  

8) Swap two numbers without using third variable

We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:

  1. By + and -

  2. By * and /

Write a c++ program to swap two numbers without using third variable.

Input: a=10 b=20

Output: a=20 b=10

Program 1: Using + and -

Let's see a simple c++ example to swap two numbers without using third variable.

back.png

 #include <iostream>  

using namespace std;  

int main()  

{  

int a=5, b=10;      

cout<<"Before swap a= "<<a<<" b= "<<b<<endl;      

a=a*b; //a=50 (5*10)    

b=a/b; //b=5 (50/10)    

a=a/b; //a=10 (50/5)    

cout<<"After swap a= "<<a<<" b= "<<b<<endl;      

return 0;  

bottom of page