I have to write a program that takes one integer and follows these rules. First, print this number. When the number is even, change the number to itself divided by 2. Print the resulting number. When the number is odd, change the number to itself multiplied by 3. Then add 1 to the number. Print the result. Continue following these rules until the number you have left is 1 (which will be printed as well).
e.g. given 22 print:
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
This is what I have so far:
Code:
#include <stdio.h>
int main()
{
int x;
{
printf("Enter a number: ");
scanf("%d", &x);
if (x % 2 == 0)
printf("%d\n", x / 2 );
else if (x % 2 != 0)
{
printf("%d\n", x * 3 + 1); }
else
{ printf("%d\n", x = 1); }
}
return 0;
}
When you enter in an even or odd number it works but the program just stops. eg I enter 22 it prints 11 and just stops.
If I do this with a while loop how do I do it?
Any help is appreciated, but please explain.