3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by mattloto
0

Do you have a specific question? Please post your attempts at these things and we'll try to help you debug them.

Dave

0

Well for loops, there are 2 main loops. The first one is a "for" loop. Here is an example that prints the number 1-9:

for (int num=0;num<10;num++) {
cout << num << endl;
}

The "for" keyword tells the compiler that you are entering a for loop. Then in the parenthesis, there is 3 parts. The first part is the declaration. In the example, we declared a integer names "num" the value of 0. The variable "num" is only accessible inside of the brackets. The next part is the conditional. In simple terms, that means it is what the program checks for. In our case, it checks to see if "num" is less than 10. If the condition is true, the cycle continues. If it's false, then the loop breaks. The third part is what happens after every cycle. Every cycle, the variable num will be incremented by 1.

The next type of loop is a "while" loop. Here is the same example as before, but using a while loop instead of a for loop.

int num=0;
while(num<10) {
cout << num << endl;
num++;
}

The syntax of a while loop only has one part: the conditional. Every time the loop does a cycle, the program checks to see if what is inside of the parenthesis is true. If its true, the the loop continues. If its false, the loop ends. I hope that this helps

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.