Adsense 728 * 15

Search

Custom Search

C Program to Reverse a Number

Write a 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 an iterative approach.

C Program to Reverse a Number


Program to Reverse a number using Recursion


How to Reverse a Number in C



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; 
        
      }
 

Explanation -  


 Suppose, An 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 <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