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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int num1, num2; char str[10]; printf("\nEnte the Number : "); scanf("%d", &num1); sprintf(str, "%d", num1); strrev(str); num2 = atoi(str); printf("\nReversed Number : "); printf("%d", num2); return (0); } |
Output :
1 2 |
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”
1 |
sprintf(str,"%d",num1); |
Step 2 : Reverse the String Using Strrev Function
- Strrev will reverse String
- eg “1234” will be reversed as “4321”
1 |
strrev(str); |
Step 3 : Convert String to Number
- [A to I ] = [ Alphabet to Integer ] = atoi
- Atoi function Converts String to Integer
1 |
num2 = atoi(str); |