Tuesday, 30 April 2013

PROGRAM TO FIND REVERSE OF A NUMBER

This program prompts user to enter a number and then stores the reverse of this number in another variable and then prints it.
Suppose for example, if user entered 5689, then the reverse of this number will be 9865.




Source code 1 :-
/****************************************************************************/
#include<stdio.h>
#include<conio.h>

int main()
{
    long num,rev=0;
    clrscr();

    printf("ENTER A NUMBER : ");
    scanf("%ld",&num);

    while(num)
    {
        rev=(rev*10)+num%10;
        num/=10;
    }
    printf("REVERSE = %ld",rev);

    getch();
    return 1;
}
/*****************************************************************************/

If the user just wants the reverse of the number then you can also store the number inputted by user as a string and then print the reverse of the string. The same thing I have used in the following program.

Source code 2 :-
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char num[50];
    int i;
    clrscr();
    printf("ENTER THE NUMBER : ");
    gets(num);

    printf("\nREVERSE OF THE NUMBER IS : \n");

    for(i=strlen(num)-1;i>=0;i--)
        printf("%c",num[i]);

    getch();
    return 1;
}
/******************************************************************************/

 By using the second code the following output is also possible (this output is not possible if we use source code 1) :-

No comments:

Post a Comment