Subscribe this Blog

Wikipedia

Search results

Notifications and New Posts!

Tuesday, April 21, 2020

Headache : Problems while Reversing the Number

In this blog, we will understand two problem while reversing the number by using C Programming. Let us understand these problems with different examples. To understand these problems let's start with simple program to Reverse the number.

Code 1: 
/*A C program to Reverse the Number where integer number is input through keyboard*/ 
#include<stdio.h>
#include<conio.h>
void main()
{
int n=123,rev=0,rem;
clrscr();
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf("Reverse Number is: %d",rev);
getch();
}

In above program number is 123, after executing computer will display Reverse number as 321.

Now problem No. 1:
If number entered through keyboard is 200 then displaying expected output as 002 is first problem. Code 1 will not give expected output as 002 for 200 number which we will enter through keyboard. As per Code 1, computer will display output as 2 only.

Now to solve problem number 1, I will modify Code 1, as follows:

Code 2 :
/*A C program to Reverse the Number where integer number is input through keyboard*/ 
#include<stdio.h>
#include<conio.h>
void main()
{
int n=123,rev=0,rem;
clrscr();
printf("\n Reverse Number is:");
while(n>0)
{
rem=n%10;
if(rem==0)
{
printf("%d",rem);
}
rev=rev*10+rem;
n=n/10;
}
printf("%d",rev);
getch();
}

Now due to Code 2, computer will display 002 output for 200 input. But Code 2 will generate problem for Input number such as 207. After writing Code 2 and execution, machine will display output as 0702 which is not expected. It means, if number is 207 then machine should display 702 as output but Code 2, will display 0702. This is problem number 2.

Problem No. 2: 
If input number is 207 then output should be 702. But due to Code 2, computer will display 0702 which is not desired output.

Now to solve Problem No. 2, I will modify Code 2, as follows:

Code 3:
/*A C program to Reverse the Number where integer number is input through keyboard*/ 
#include<stdio.h>
#include<conio.h>
void main()
{
int n=123,rem;
clrscr();
printf("\n Reverse Number is:");
while(n>0)
{
rem=n%10;
printf("%d",rem);
rev=rev*10+rem;
n=n/10;
}
getch();
}

Code 3 solves Problem No. 1 and Problem No. 2 but Code 3 is not right legally, because simply we are displaying digits from the entered number on output screen. In Code 3, we are not storing Reverse Number in any variable like rev.

I hope, you might have understood two problems while reversing entered number. If you will get any simple solution to solve above mentioned two problems then I will be happy with your answer. You can write your answer in comment box.

-
Regards,
#sdbhosale

No comments:

Post a Comment