C Program 1 – To find the reversal of a given number

Assume the number 1234, after reversal the number becomes 4321.

Input: One number, Ex 1234, declared to num

Output : One number, Ex 4321, rev is the variable

Logic:

  1. separate each digit using modulo operator from the right and bring that number to front
  2. divide the given number by 10, so the right most digit will be discarded.
  3. run till the number becomes <=0

output the result

#include <stdio.h>
#include <conio.h>

int main()
{
    int num,rev=0;
    printf("enter the number to be reversed");
    scanf("%d", &num);

    while(num>0) //till the number is positive, perform the process
    {
    rev=rev*10 + (num%10);
//separate each digit and bring it to the first
    num=num/10;
    }
    printf("The reversal is %d ",rev);
    getch();
    return 0;
}

Comments

  1. can anyone explain the procedure of the above program step-by-step.plz

    ReplyDelete

Post a Comment

Popular Posts