Free C++ Lessons (Part 3)

Lessons and Tutorials in the Programming Language C.

For Loop:

for loop is a programming language statement which allows code to be repeatedly executed.

Syntax:

for (condition) {
   statements;
}

Example 1:

We want a word to be printed 5 times.

 

  • i++” means post increment.
  • n” means newline.

Result:

 

Example 2:

We want to calculate the factorial of a number.

 

Result:

 

While Loop:

while loop is a control flow statement that allows a code to be executed over and over until a specific situation is met, which is set up in the while statement.

note:

You don’t have to write an endless loop, it will tie up computer resources.

Syntax:

while (condition) {
   statements;
}
 

Example:

In this example the program asks the user repeatedly to enter an even number, while the number entered is an odd number.

  • n%2!=0″ means that the reminder of the division of n by 2, must not be 0.

Result:

 

comments powered by Disqus
Loading