Write a program that has the user enter a number greater than 1 (Also validate the input using a loop). Proceed with the valid input as follows:
If the number is odd, multiply it by 3 and add 1.
If it’s even, divide it by 2.
Do this until the number equals one and print out the number of loops it took to reach 1.
My code outputs "Error, only positive numbers greater than 1." even when i do put a positive number greater than 1. How should i fix this?
#include <iostream>
usingnamespace std;
int main() {
double parity;
int number;
int i = 0;
parity = number % 2;
do {
cout << "Please enter a positive number greater than 1. ";
cin >> number;
while (number < 2)
; //note the semicolon
{ //this is not part of the loop, it always execute
cout << "Error, only positive numbers greater than 1. ";
cin >> number;
}
if (parity = 0) {
number = number / 2;
i++;
}
if (parity != 0) {
number = (3 * number) + 1;
i++;
}
} while (number != 1);
cout << "It took " << i << " loops to reach 1";
return 0;
}
The semicolon denotes the end of a statement for the compiler to convert in to machine code, a block of statements with a curly brace ({}) at the end and the beginning (such as if, else, else if or any control statement and) denotes this is one block.
For instance this block of code (uses this correctly :D):
1 2 3 4 5 6 7 8 9 10
int one = 1;
int answer = 42;
if (one < 0)
{ // note the curly brace: start of code block
cout << "One is less then the answer!"; // note the semicolon: @ end of statement
cout << "The answer, of course, is 42!";
} // note the curly brace here: end of code block
// *fin*
The same code only done incorrectly:
1 2 3 4 5 6 7 8 9 10
int one = 1;
int answer = 42;
if (one < 0); //ignores this condition and omits from machine code.
{ // note the curly brace: start of code block: this too is ignored.
cout << "One is less then the answer!"; // note the semicolon: @ end of statement
cout << "The answer, of course, is 42!";
} // note the curly brace here: end of code block: this too is ignored.
// *fin*
So when you typed your if statement and then put a semicolon it acts like it is no longer a block and just a statement and omits it from the machine code.