Part B: Repetition Statements: Step 1 - Make It More Precise
Part B: Repetition Statements: Step 1 - Make It More Precise
Create a new project and copy-and-paste the following algorithm into your program. It is
somewhat of a famous algorithm called the 3n+1 problem (Google it for details). No one
is quite sure if it will eventually reach 1 for any input n.
main:
read n
while n is not 1 do
print n
if n is odd then
set n to 3 * n + 1
else
set n to n / 2
end
Step 1 - Solution
The computer must take different actions depending on whether n is even or odd. We need if
statement to decide between the two cases:
main:
read n
while n is not 1 do:
if(n%2==1)
compute n = 3 * n + 1;
else
compute n = n/2;
end
Step 2 – Solution
How can we get a positive integer from the user? If we just read in a number, it's
possible that the user might type in a negative number or zero. If we follow what
happens when the value of n is negative or zero, we'll see that the program will go on
forever. This is bad. In this case, the problem is probably no big deal, but in general we
should try to write programs that are foolproof. One way to fix this is to keep reading in
numbers until the user types in a positive number:
main:
read n (Let n be the user's response ;)
while n is not positive:
print an error message;
read another value for n;
n++
while n is not 1:
if n is odd:
compute n = 3 * n + 1;
else
compute n = n/2;
end
The first while loop will end only when n is a positive number, as required. (A common
beginning programmer's error is to use an if statement instead of a while statement
here: "If n is not positive, ask the user to input another value." The problem arises if the
second number input by the user is also non-positive. The if statement is only executed
once, so the second input number is never tested. With the while loop, after the second
number is input, the computer jumps back to the beginning of the loop and tests
whether the second number is positive. If not, it asks the user for a third number, and it
will continue asking for numbers until the user enters an acceptable input.)
Step 3 – Solution
Code
#include<stdio.h>
int main()
{
int n;
start: scanf("%d",&n);
printf("output\n");
print: printf("%d\n",n);
while (n<=0)
{
printf("The number must be positive. Please try again\n");
n++;
scanf("%d",&n);
}
if(n==1) goto start;
if(n%2==1)
n = 3*n + 1;
else
n = n/2;
goto print;
return 0;
}
Output:
1- For giving a negative number
Example: -4
Output -4
Error Message “The number must be positive, Please try again”
2- For giving a zero (0)
Output 0
Error Message “The number must be positive, Please try again”
3- Giving positive number
Example: 5
Output
5
16
8
4
1