Friday, 10 January 2014

C Program to Reverse the digits of a number in 3 Steps

C program to reverse the digits of a number ? [ In 3 Steps ]

Problem Statement : Reversing the digits of number without using mod (%) Operator ?

Prerequisite :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
 int num1, num2;
 char str[10];
 clrscr();

    printf("nEnte the Number : ");
    scanf("%d",&num1);

    sprintf(str,"%d",num1);

    strrev(str);

    num2 = atoi(str);

    printf("nReversed Number : ");
    printf("%dn",num2);
    getch();
}
Output :
Enter the Number : 123
Reversed Number : 321

Explain Logic :
Step 1 : Store Number in the Form of String
  • Sprintf function sends formatted output to string variable specified
  • Number will be stored in String variable “str”
sprintf(str,"%d",num1);
Step 2 : Reverse the String Using Strrev Function
  • Strrev will reverse String
  • eg “1234″ will be reversed as “4321″
strrev(str);
Step 3 : Convert String to Number
  • [A to I ] =  [ Alphabet to Integer ] = atoi
  • Atoi function Converts String to Integer
num2 = atoi(str);

No comments:

Post a Comment