Uploaded by Abanob hany Wasfy

c++ section 3

advertisement
C++
section 3
• Loops can execute a block of code as long as a
specified condition is reached.
C++ While
Loop
• Loops are handy because they save time, reduce
errors, and they make code more readable.
The while loop loops through a block of code as
long as a specified condition is true:
C++ While Loop
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
Example 2: Sum of Positive Numbers Only
C++ do...while Loop
The do...while loop is a variant of the while loop with one important difference: the body
of do...while loop is executed once before the condition is checked.
Example : Sum of Positive Numbers Only
Example 2: Display Numbers from 1 to 5
difference between while and do while c++
difference between while and do while c++
the main difference between a while loop and do while loop is that while
loop check condition before iteration of the loop. On the other hand, the
do-while loop verifies the condition after the execution of the statements
inside the loop.
Furthermore, the while loop is known as the entry-controlled loop.
Conversely, the do while loop is called the exit-controlled loop.
Infinite while loop
If the condition of a loop is always true, the loop runs for infinite times (until the memory
is full). For example,
Infinite while loop
Instead of true, you can also give a non-zero integer.
Infinite while loop
you can also give a condition that always evaluates to true. For example, the condition 1
== 1 or 0 == 0 is always true. No matter how many times the loop runs, the condition is
always true.
Infinite while loop
C++ Infinite While Loop with No Update to Control Variables
C++ For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Statement 1 is executed (one time) before the
execution of the code block.
Statement 2 defines the condition for executing
the code block.
Statement 3 is executed (every time) after the
code block has been executed.
C++ For Loop
The example below will print the numbers 0 to 4:
C++ For Loop
This example will only print even values between 0 and 10:
C++ Break
You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement. The break statement can also be used to
jump out of a loop.
This example jumps out of the loop when i is equal to 4:
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
C++ Break and Continue in While Loop
You can also use break and continue in while loops:
Break Example
C++ Break and Continue in While Loop
Continue Example
Download