We, the C programmers, sometimes face a problem that we are to reverse a number or a string. On many online judges there are some problems like number reversion. On these cases, what will we do? We may consider the following code to reverse a number:
#include <stdio.h>
int main()
{
int i, x = 12345, rev[5];
for(i = 0; i < 5; i++){
rev[i] = x % 10;
x = x/10;
printf("%d", rev[i]);
}
return 0;
}
Output:
54321
But this program can reverse only 12345. We can make it more efficient in this way:
#include <stdio.h>
int main()
{
int i, x, rev[30];
scanf("%d", &x);
for(i = 0; x != 0 ; i++){
rev[i] = x % 10;
x = x/10;
printf("%d", rev[i]);
}
return 0;
}
Input:234567
Output:765432
But it’s a long process too. We can write the program as follows to make it more efficient:
#include <stdio.h>
int main()
{
int x, rev = 0;
scanf("%d",&x);
while (x != 0)
{
rev = rev * 10 + x % 10;
x = x/10;
}
printf("%d\n", rev);
return 0;
}
Input:456789
Output:987654
Here we have seen three programs which can be used to reverse any number. You may write more efficient programs. Please do that by yourself. Now we will write a program to reverse a string. Please consider the following program:
#include<stdio.h>
int main()
{
char temp, str[100]= "Bangladesh";
int i=0,j=9;
while(i<j){
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
puts(str);
return 0;
}
Output:hsedalgnab
But it’s not efficient program as only a fixed string “Bangladesh” can be reversed. We can make it efficient as follows:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100],temp;
int i=0,j;
gets(str);
j=strlen(str)-1;
while(i<j){
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
puts(str);
return 0;
}
Input:dhaka
Output:akahd
But we can make our program more efficient using strrev() function defined in header file. If you aren’t familiar to this function, you can read this article - use of strrev() function in C programming. By using it, we can get one of the most efficient program of reversing any number or string. Please consider the following program:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
gets(str);
puts(strrev(str));
return 0;
}
Input:coder
Output:redoc
By using it you can reverse any number or function. Hope you have understood the reversion of a number or string in C. Happy Coding!!!