Currently new to C and took up the exercise to reverse a number using a temporary variable. The code goes as follows:
#include <stdio.h>
#include <math.h>
int main(){
int a, length=1, rem, temp;
printf("Enter number to be reversed: ");
scanf("%d",&a);
/* calculating length of number */
while (1){
if (a/(int)pow(10,length)==0){
break;
}
else{
length++;
}
}
printf("%d\n", length);
/* reversing logic */
for (int i= 1; i <= length; i++){
rem = a%10;
temp += rem*(pow(10,(length-i)));
a /= 10;
}
printf("%d\n",temp);
return 0;
}
The problem is that the parts 'calculating length of number' and 'reversing logic' work perfectly fine independently but the later one breaks down and return some -ve number when the aforementioned code is executed. The former parts executes perfectly returning '4' for test case 'a = 1234'.
#include <stdio.h>
#include <math.h>
int main(){
int a, length=1, rem, temp;
printf("Enter number to be reversed: ");
scanf("%d",&a);
length = 4 /* hardcoding the length */
/* reversing logic */
for (int i= 1; i <= length; i++){
rem = a%10;
temp += rem*(pow(10,(length-i)));
a /= 10;
}
printf("%d\n",temp);
return 0;
}
This code executes perfectly for example for test case 'a = 1234' giving '4321'. Please provide insights why this problem may be occurring?