So, I've never programmed anything before and I kinda started playing with it, and Im trying to make a very simple thing, it counts to 20 after I press 0 and its supposed to stop when it hits 20 seconds, but it won't stop.
Your condition inside the while loop is incorrect. You should loop while the count hasn't reached 20. If you don't want to run the while loop unless zero is entered, then you contain your loop inside an if statement.
// program test "Loop"
#include <iostream>
#include <windows.h>
usingnamespace std;
int main ()
{
int n;
int *np;
np = &n;
int c = 1;
cout << "Push 0 and enter: ";
cin >> n;
if (c<21) {
while (c<21) {
cout << c << ", ";
++c;
}
} else {
cout << ".\nFinished.\n";
}
system("PAUSE");
return 0;
}
I'm just as fresh as you are, and as a result having started I have found it very beneficial to do my brackets a particular way not to save lines but for absolute clarity of reading. There's no right answer from what I can tell but I do it like this:
Sorry for a blurb of unrelated but equally basic code, personally I have found viewing as many simple arguments as possible the best way to learn so far anyhow.
EDIT: LOL @ tabulation... Time for more functions and less nesting.
@Krofna
You did forget that Tryed wanted a Sleep(1000), so that each number took a second before being printed. So, here is my version. This program will keep looping til a '0' is pressed.
@whitenite1
Ah, didnt notice sleep, but np, easy to add
Also I being lazy to add a do while loop mainly beacuse i didnt write that code in compiler, but in a post counting 4 spaces as a replacement for tab lol.
int main ()
{
int n;
int *np;
np = &n;
int c = 1;
cout << "Push 0 and enter: ";
cin >> n;
while (n==0) {
cout << c << ", ";
++c;
Sleep(1000);
}
if (c>20) {
*np = 1;
cout << "Finished.\n";
}
(sic)
First, if n contains a value other than zero when the while loop is encountered, the loop never executes. If n contains the value of zero when the while loop is encountered, the loop never stops since you never told it when to stop. As a result of this, you have an infinite loop. To remedy this, incorporate the break statement or rethink your condition.
Second, your if statement is outside the while loop, therefore, it has no effect.