Monday, August 4, 2014

C Program to Reverse a Given Number

This C Program reverses a given number by using modulo operation.
Here is source code of the C program to reverse a given number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program to accept an integer and reverse it
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     long  num, reverse = 0, temp, remainder;
  9.  
  10.     printf("Enter the number\n");
  11.     scanf("%ld", &num);
  12.     temp = num;
  13.     while (num > 0)
  14.     {
  15.         remainder = num % 10;
  16.         reverse = reverse * 10 + remainder;
  17.         num /= 10;
  18.     }
  19.     printf("Given number = %ld\n", temp);
  20.     printf("Its reverse is = %ld\n", reverse);
  21. }

$ cc pgm42.c
$ a.out
Enter the number
567865
Given number   = 567865
Its reverse is = 568765

No comments:

Post a Comment