Adsense 728 * 15

Search

Custom Search

Program to Reverse a Number in C, C++

Write a C, C++ program to reverse a number. In this program, A number is input by a user and our code will reverse this number. For reversing a number we'll use iterative approach.


Reverse a number using Recursion


How to Reverse a Number

Let's check the logic.

1. Take a input from user.

2.
 while(num!=0) {

          temp = num%10;   // Store the result in temp variable

          rev = (rev*10)+temp;

          num = num/10; 
        
      }
 

How this code is working 


 Suppose, A input number is 243. 

 While loop condition is true, as num is 243 

 rev = 0 * 10 + 3; 
 num = 24; 

 Now num is 24 still while loop condition is true, 

 rev = 3*10 + 4; 
 num = 2; 

 Now num is 2, again while loop is executed, 

 rev = 34 * 10 + 2 
 num = 0; 

 Now number is zero while loop will break


Program to Reverse a String


C++ Program to Reverse a Number



 #include<iostream>
  using namespace std;

  int main()
  {
     int num,temp,rev=0;

     cout << "Enter a number \n";
     cin  >> num;

 
     while(num != 0){

       temp = num%10;
       rev  = (rev*10) + temp;
       num  = num/10;

     }

     cout<<"\n Reverse of a input number is "<< rev;

     return 0;

 }




Output -

Enter a number   243

Reverse of a input number is   342

C Program to Reverse a Number


#include <stdio.h>

int main(void) {
 
    int num, temp, rev=0;

    printf("Enter a number");
    scanf("%d", &num);

 
    while(num != 0){

       temp = num % 10;
       rev  = (rev*10)+temp;
       num  = num/10;

    }

    printf("Reverse of a input number is  %d", rev);


    return 0;
}



Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books



No comments:

Post a Comment