Firstly, this is a homework assignment, and I am very new to programming in C. What I am trying to accomplish is the user puts in an integer, and then each individual digit of that integer is printed on a new line, like below:
Enter integer: 1234
The digits are:
1
2
3
4
My problem is that whatever integer you input, for some reason a 7 and a 4 are added on to the end. Below is my code and an example of the problem:
#include <stdio.h>
#define Success 0
int main()
{ int integer;
int reverse;
int digit;
printf("Enter Integer: ");
scanf("%d", &integer);
/* Reverse the numbers in the integer */
while (integer != 0) {
digit = integer%10;
reverse = (reverse * 10) + digit;
integer = integer / 10;
}
/* Print the numbers of the reverse integer, in reverse order */
while (reverse != 0) {
digit = reverse%10;
printf("%d\n", digit);
reverse = reverse / 10;
}
return Success;
}
Example of problem:
Enter Integer: 12345
1
2
3
4
5
7
4
Anyone have any ideas as to what might cause this outcome? By printing reverse I have narrowed it down to a problem with the first while loop.
Reverse is not initialized. This means there could be any value in that variable when you start touching it. Set it to 0 after you declare it and see what happens.