How can I rewrite this diagram in a C++ program?
Hello folks,
I've been working on this diagram for hours. My goal is to rewrite it in a C++ program.
I always do something wrong with the loop, which causes my final results to be wrong.
It is the second diagram.
int main() { int x; cin >> x; if (x < 0) { cout << "Fehler" << endl; } else { while (x <= 1) { cout << x << endl; x = x - 2; } } return 0; }
Thanks for the code 🙂 This makes your mistake obvious.
As long as x <= 1 you execute the while loop.
Example:
x = 2
Output:
//nothing
The program terminates without ever entering the while loop because 2 <= 1 is False. This is true for all x > 1.
x = 1
Output:
1
-1
-3
-4
….
You output the value x, then calculate x = 1 – 2 = -1. Since x is getting smaller and the while loop remains true, you have created an infinite loop. 😉
x = 0
Output:
0
Because of your first if condition, you never get into the while loop. Otherwise, it would have been the next candidate.
——-
What you want is something completely different. 😉
Depending on the input, you want the while to run until x <= 1.
It's good that you're willing to pay more for the test.
1. Receive a number >= 0
Is a good approach to avoid calculating negative values.
2. The main task
IF x <= 1
THEN print X and exit the function
OTHERWISE calculate x = x – 2 and continue
This means while corresponds to the time as long as x > 1.
By the way, with this while the above If query would not be necessary at all.
Tip for solving:
Create a table with the values for the variable. Start with the input value.
Then check whether the conditions for if / while / do while are True or False.
Note every change in the value of your variables.
man soll in der Schleife nur bleiben solange x <=1 NICHT gilt.