Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Reverse of a Given Number

This code takes an integer input, reverses the order of its digits using a while loop, and then displays both the original and reversed numbers. The program effectively calculates the reverse of the input number by extracting and rearranging its digits.

#include<stdio.h>
main()
{
  int dummy,n,rev=0,x;
  printf("Enter a number\n");
  scanf("%d",&n);
  dummy=n;
  while(n>0)
  {
    x=n%10;
    rev=rev*10+x;
    n=n/10;
  }
  printf("The reverse of %d is %d\n",dummy,rev);
}
C Programming Examples
OUTPUT
Enter a number
456
The reverse of 456 is 654
C Programming Examples

Explanation:

This C program is designed to reverse the digits of a given number. It reads an integer from the user, reverses the digits, and then displays the reversed number. Here’s a step-by-step explanation of the code:

Header File:

  • The program includes the standard C library header <stdio.h> for input and output operations.

Main Function:

  • The main function is the entry point of the program.

Variable Declaration:

Several variables are declared:

  • n (int): It stores the user input, which is the number to be reversed.
  • dummy (int): This variable is used to store the original number because n will be modified during the reversal process.
  • rev (int): This variable is used to store the reversed number.
  • x (int): It is used to store individual digits extracted from n.

User Input:

The program prompts the user to enter a number:

  • “Enter a number” for n.

The user’s input is read and stored in the variable n using scanf.

Initialization:

  • The dummy variable is set to the same value as n. This is done to keep a copy of the original number for later display.

While Loop for Reversal:

  • A while loop is used to reverse the digits of the number stored in n.
  • The loop continues as long as n is greater than 0.

Digit Extraction and Reversal Calculation:

  • Within the loop, x is used to store the rightmost digit of n. This is done by calculating n % 10, which gives the remainder when n is divided by 10. This remainder is the rightmost digit.
  • The rev variable is updated to reverse the number. To do this, it multiplies the current reversed number by 10 (shifting its digits to the left) and then adds the rightmost digit x.
  • The rightmost digit is removed from n by dividing it by 10 (n = n / 10).

Display Reversed Number:

  • After the loop completes, the program displays the reversed number, which is stored in the rev variable, and also shows the original number.

End of Program:

  • Once the result is displayed, the program reaches the end of the main function and terminates.
Spread the love
Scroll to Top
Scroll to Top