C++/Loops: Difference between revisions

From Wikiversity
< C++
Jump to navigation Jump to search
Content deleted Content added
Fell
Tags: Visual edit Mobile edit Mobile web edit
 
(39 intermediate revisions by 23 users not shown)
Line 1: Line 1:
{{TOCright}}
Loops allow a programmer to execute the same block of code repeatedly. We will make heavy use of [[Conditional_Statements | conditional statements]] in this section.


Loops allow a programmer to execute the k kisame block of code repeatedly. We will make heavy use of [[Conditional_Statements | conditional statements]] in this section.k
== The <tt>while</tt> Loop ==


== The <kbd>while</kbd> Loop ==
The <tt>while</tt> loop is really the only necessary repetition construct. The <tt>for</tt> loop, coming up, can be duplicated using a <tt>while</tt> loop, and with more control. A simple negation can perform the same behavior as an <tt>until</tt> loop.

The <kbd>while</kbd> loop is really the only necessary repetition construct. The <kbd>for</kbd> loop, coming up, can be duplicated using a <kbd>while</kbd> loop, and with more control. A simple negation can perform the same behavior as an <kbd>until</kbd> loop.


The syntax is as follows:
The syntax is as follows:
<syntaxhighlight lang="cpp">

while ( ''condition'' ) {
while ( ''condition'' ) {
//body
//body
}
}
</syntaxhighlight>


Again, the curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop. If the actual code looked something like this:
Again, the curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop. If the actual code looked something like this:
<syntaxhighlight lang="cpp">
while ( x == 4 )
y += x;
x += 1;
</syntaxhighlight>


means
while ( x == 4 ) while ( x == 4 ) {
<syntaxhighlight lang="cpp">
y += x; means y += x;
while ( x == 4 ) {
x += 1; }
x += 1;
y += x;
}
x += 1;
</syntaxhighlight>


There would be a problem. According to what was written, even though the second line after the <tt>while</tt> was indented, only the first line corresponds to the <tt>while</tt> loop. This is a huge problem because the variable involved in the condition (x) does not change, so it will always evaluate to true, making this an '''infinite loop'''. This could be alleviated by containing all statements intended to be a part of the loop body in '''{ }'''.
There would be a problem. According to what was written, even though the second line after the <kbd>while</kbd> was indented, only the first line corresponds to the <kbd>while</kbd> loop. This is a huge problem because the variable involved in the condition (x) does not change, so it will always evaluate to true, making this an '''infinite loop'''. This could be alleviated by containing all statements intended to be a part of the loop body in '''{ }'''.
<syntaxhighlight lang="cpp">
while ( x == 4 ) {
y += x;
x += 1;
}
</syntaxhighlight>


== The <kbd>do...while</kbd> Loop ==
while ( x == 4 ) {
y += x;
x += 1;
}


The <kbd>do...while</kbd> loop is nearly identical to the <kbd>while</kbd> loop, but instead of checking the conditional statement before the loop starts, the <kbd>do...while</kbd> loop checks the conditional statement after the first run, then continuing onto another iteration.
== The <tt>do...while</tt> Loop ==

The <tt>do...while</tt> loop is nearly identical to the <tt>while</tt> loop, but instead of checking the conditional statement before the loop starts, the <tt>do...while</tt> loop checks the conditional statement before continuing onto another iteration.


The syntax is as follows:
The syntax is as follows:
<syntaxhighlight lang="cpp">
do {
do {
//body
//body
} while (''condition'')
} while (''condition'');
</syntaxhighlight>


As you can see, it will run the loop at least once before checking the conditional.
As you can see, it will run the loop at least once before checking the conditional.


The <tt>do...while</tt> loop is still haunted by infinite loops, so exercise the same caution with the <tt>do...while</tt> loop as you would with the <tt>while</tt> loop. It's usefulness is much more limited than the <tt>while</tt> loop, so use this only when necessary.
The <kbd>do...while</kbd> loop is still haunted by infinite loops, so exercise the same caution with the <kbd>do...while</kbd> loop as you would with the <kbd>while</kbd> loop. Its usefulness is much more limited than the <kbd>while</kbd> loop, so use this only when necessary.


== The <tt>for</tt> Loop ==
== The <kbd>for</kbd> Loop ==
The <code>for</code> loop is a <code>while</code> loop that lets a programmer control exactly how many times a loop will iterate.
The <code>for</code> loop is a loop that lets a programmer control exactly how many times a loop will iterate.


The syntax is as follows:
The syntax is as follows:


<syntaxhighlight lang="cpp">
for (<i>expression for initialization</i> ; <i>expression for testing</i> ; <i>expression for ''re''initialization</i>) {
for (expression for initialization ; expression for testing ; expression for updating) {
//body
//body
}
}
</syntaxhighlight>


An example how the for loop works, let's look at one:
Here is an example of how the <code>for</code> loop works:


<syntaxhighlight lang="cpp">
for ( int i = 0; i < 10; ++i ) {
std::cout << i << std::endl;
for ( int i = 0; i < 10; ++i ) {
std::cout << i+1 << std::endl;
}
}
</syntaxhighlight>


The code above and below are more or less equivalent.
The code above and below are more or less equivalent.


<syntaxhighlight lang="cpp">
{
int i = 0;
int i = 0;
while ( i < 10 ) {
while ( i < 10 ) {
std::cout << i << std::endl;
std::cout << i+1 << std::endl;
++i;
++i;
}
}
</syntaxhighlight>
}


What does this loop do? Prior to the first iteration, it sets the value of i to 0. Next, it tests (like a normal <tt>while</tt> loop) if i is less than 10. If the statement returns true, the body of the loop is run and the program will print the value returned by the simple arithmetic statement i+1 and move the terminal cursor down to the next line. After the loop is finished, i is incremented (by 1), as specified in the update statement, and the conditional is tested again.
What does this loop do? Prior to the first iteration, it sets the value of <code>i</code> to <code>0</code>. Next, it tests (like a normal <kbd>while</kbd> loop) if <code>i</code> is less than 10. If the statement returns <code>true</code>, the body of the loop is run and the program will print the value returned by the simple arithmetic statement <code>i+1</code> and move the terminal cursor down to the next line. After the loop is finished, <code>i</code> is incremented (by 1), as specified in the update statement, and the conditional is tested again.


So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught your program to count!
So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught your program to count!


The variable used in <tt>for</tt> loops is generally an integer variable named i, j, or k, and is often initialized <i>prior</i> to the beginning of the <tt>for</tt> loop. Another option is to initialize the variable at the same time that you declare the variable's initial state:
The variable used in <kbd>for</kbd> loops is generally an integer variable named i, j, or k, and is often initialized <i>prior</i> to the beginning of the <kbd>for</kbd> loop. Another option is to initialize the variable at the same time that you declare the variable's initial state:


<source lang="c">
<syntaxhighlight lang="cpp">
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 10; i++) {
cout << i+1 << endl;
std::cout << i+1 << std::endl;
}
}
</syntaxhighlight>
</source>

If this is done properly, it is possible to nest <kbd>for</kbd> loops.


<syntaxhighlight lang="cpp">
If this is done properly, it is possible to nest <tt>for</tt> loops.


#include <iostream>
<source lang="c">
using namespace std;
int main(){
int input;
int input;


cout << "How many missiles will you fire?" << endl;
cout << "How many missiles will you fire?" << endl;
cin >> input;
cin >> input;
cout << endl;
cout << "\n";


for (int i = 0; i < input; i++) {
for (int i = 0; i < input; i++) {
for (int j = 10; j > 0; j--) {
for (int j = 10; j > 0; j--) {
cout << j << " ";
cout << j << " ";
}
}
cout << "Missile " << i+1 << " has launched." << endl;
cout << "Missile " << i+1 << " has launched." << endl;
}
}


cout << "All missiles have been launched." << endl;
cout << "All missiles have been launched." << endl;
return 0;
</source>
}
</syntaxhighlight>


What does this program do? The user is prompted to choose an integer, which is used in the conditional statement of the first <tt>for</tt> loop. Each iteration of the i loop will cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to continue. The output will look something like this:


What does this program do? The user is prompted to choose an integer, which is used in the conditional statement of the first <kbd>for</kbd> loop. Each iteration of the i loop will cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to continue. The output will look something like this:
<source lang="c">

How many missiles will you fire?
How many missiles will you fire?
3
3
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
All missiles have been launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
All missiles have been launched.
</source>


== Equivalence of C++ Looping Structures ==
== Equivalence of C++ Looping Structures ==


The <tt>while</tt> loop can take the place of <tt>do...while</tt> loops if the condition for the <tt>while</tt> loop is "rigged" to be true at least the first time around.
The <kbd>while</kbd> loop can take the place of <kbd>do...while</kbd> loops if the condition for the <kbd>while</kbd> loop is "rigged" to be true at least the first time around.


The <tt>while</tt> loop can take the place of <tt>until</tt> loops by negating the condition that would be specified for the <tt>until</tt> loop, as explained above.
The <kbd>while</kbd> loop can take the place of <kbd>until</kbd> loops by negating the condition that would be specified for the <kbd>until</kbd> loop, as explained above.


=== For and While loops ===
=== For and While loops ===
Line 119: Line 142:
}
}


This can easily be reformatted as:
This can easily be reformatted as (do recognize the extra enclosing brackets, and the two extra semicolons after the expressions in order to turn them into statements):


{
{
<initial statement>
<initial expression> ;
while (<condition>) {
while (<condition>) {
<block of code>
<block of code>
<update statement>
<update expression> ;
}
}
}
}


A <tt>for</tt> loop is more often used in by C++ programmers due to its conciseness as well as its separation of the looping logic (often using a loop control variable like "int i" or another simple iterator) from the loop's content. A <tt>while</tt> loop is often preferred if the initial statement or update statement requires more complex code than fits neatly into a the <tt>for</tt> construct. However, the two are fully equivalent therefore it is ultimately a coding style decision, not a technical decision whether to use one or the other.
A <kbd>for</kbd> loop is more often used in by C++ programmers due to its conciseness as well as its separation of the looping logic (often using a loop control variable like "int i" or another simple iterator) from the loop's content. A <kbd>while</kbd> loop is often preferred if the initial statement or update statement requires more complex code than fits neatly into the <kbd>for</kbd> construct. However, the two are fully equivalent therefore it is ultimately a coding style decision, not a technical decision whether to use one or the other.


== Infinite Loops ==
== Infinite Loops ==


One common programming mistake to create an ''infinite loop''. An infinite loop refers to a loop, which under certain valid (or at least plausible) input, will never exit.
One common programming mistake is to create an ''infinite loop''. An infinite loop refers to a loop, which under certain valid (or at least plausible) input, will never exit.


Beginning programmers should be careful to examine all the possible inputs into a loop to ensure that for each such set of inputs, there is an ''exit condition'' that will eventually be reached. In addition to preventing the program from hanging (i.e. never finishing), understanding all potential inputs and exit conditions demonstrates a solid understanding of the algorithm being written. Academic studies of programming languages often test students' ability to identify infinite loops for the very reason that doing so often requires a solid understanding of the underlying code.
Beginning programmers should be careful to examine all the possible inputs into a loop to ensure that for each such set of inputs, there is an ''exit condition'' that will eventually be reached. In addition to preventing the program from hanging (i.e. never finishing), understanding all potential inputs and exit conditions demonstrates a solid understanding of the algorithm being written. Academic studies of programming languages often test students' ability to identify infinite loops for the very reason that doing so often requires a solid understanding of the underlying code.


Compilers, debuggers, and other programming tools can only help the programmer so far in detecting infinite loops. In the fully general case, it is not possible to automatically detect an infinite loop. This is known as the [[w:Halting_Problem|halting problem]]. While the halting problem is not solvable in the fully general case, it is possible to determine whether a loop will halt for some specific cases.
Compilers, debuggers, and other programming tools can only help the programmer so far in detecting infinite loops. In the fully general case, it is not possible to automatically detect an infinite loop. This is known as the [[w:Halting_Problem|halting problem]]. While the halting problem is not solvable in the fully general case, it is possible to determine whether a loop will halt for some specific cases.

=== Example of Infinite loop ===
<syntaxhighlight lang=cpp>
#include <iostream>
int main()
{
while(1) {
// printf("Infinite Loop\n");
std::cout << ("Infinite loop\n");
}
return 0;
}
</syntaxhighlight>

This code will print infinite loop with out stopping.


==Where To Go Next==
==Where To Go Next==

{{Cpp_Lessons}}
{{:C++/Lessons}}


[[Category:C++]]
[[Category:C++]]
[[Category:Computer programming]]

Latest revision as of 14:35, 18 July 2024

Loops allow a programmer to execute the k kisame block of code repeatedly. We will make heavy use of conditional statements in this section.k

The while Loop

[edit | edit source]

The while loop is really the only necessary repetition construct. The for loop, coming up, can be duplicated using a while loop, and with more control. A simple negation can perform the same behavior as an until loop.

The syntax is as follows:

while ( ''condition'' ) {
    //body
}

Again, the curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop. If the actual code looked something like this:

while ( x == 4 )                   
    y += x;
    x += 1;

means

while ( x == 4 ) {
    y += x;
}
    x += 1;

There would be a problem. According to what was written, even though the second line after the while was indented, only the first line corresponds to the while loop. This is a huge problem because the variable involved in the condition (x) does not change, so it will always evaluate to true, making this an infinite loop. This could be alleviated by containing all statements intended to be a part of the loop body in { }.

while ( x == 4 ) {
    y += x;
    x += 1;
}

The do...while Loop

[edit | edit source]

The do...while loop is nearly identical to the while loop, but instead of checking the conditional statement before the loop starts, the do...while loop checks the conditional statement after the first run, then continuing onto another iteration.

The syntax is as follows:

do {
    //body
} while (''condition'');

As you can see, it will run the loop at least once before checking the conditional.

The do...while loop is still haunted by infinite loops, so exercise the same caution with the do...while loop as you would with the while loop. Its usefulness is much more limited than the while loop, so use this only when necessary.

The for Loop

[edit | edit source]

The for loop is a loop that lets a programmer control exactly how many times a loop will iterate.

The syntax is as follows:

for (expression for initialization ; expression for testing ; expression for updating) {
    //body
}

Here is an example of how the for loop works:

for ( int i = 0; i < 10; ++i ) {
    std::cout << i+1 << std::endl;
}

The code above and below are more or less equivalent.

int i = 0;
while ( i < 10 ) {
    std::cout << i+1 << std::endl;
    ++i;
}

What does this loop do? Prior to the first iteration, it sets the value of i to 0. Next, it tests (like a normal while loop) if i is less than 10. If the statement returns true, the body of the loop is run and the program will print the value returned by the simple arithmetic statement i+1 and move the terminal cursor down to the next line. After the loop is finished, i is incremented (by 1), as specified in the update statement, and the conditional is tested again.

So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught your program to count!

The variable used in for loops is generally an integer variable named i, j, or k, and is often initialized prior to the beginning of the for loop. Another option is to initialize the variable at the same time that you declare the variable's initial state:

for (int i = 0; i < 10; i++) {
    std::cout << i+1 << std::endl;
}

If this is done properly, it is possible to nest for loops.

#include <iostream>
using namespace std;
int main(){
int input;

cout << "How many missiles will you fire?" << endl;
cin >> input;
cout << "\n";

for (int i = 0; i < input; i++) {
    for (int j = 10; j > 0; j--) {
       cout << j << " ";
    }
    cout << "Missile " << i+1 << " has launched." << endl;
}

cout << "All missiles have been launched." << endl;
return 0;
}


What does this program do? The user is prompted to choose an integer, which is used in the conditional statement of the first for loop. Each iteration of the i loop will cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to continue. The output will look something like this:

How many missiles will you fire?
3
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
All missiles have been launched.

Equivalence of C++ Looping Structures

[edit | edit source]

The while loop can take the place of do...while loops if the condition for the while loop is "rigged" to be true at least the first time around.

The while loop can take the place of until loops by negating the condition that would be specified for the until loop, as explained above.

For and While loops

[edit | edit source]

A for loop is structured as follows:

for (<initial expression> ; <condition> ; <update expression>) {
   <block of code>
}

This can easily be reformatted as (do recognize the extra enclosing brackets, and the two extra semicolons after the expressions in order to turn them into statements):

{
    <initial expression> ;
    while (<condition>) {
        <block of code>
        <update expression> ;
    }
}

A for loop is more often used in by C++ programmers due to its conciseness as well as its separation of the looping logic (often using a loop control variable like "int i" or another simple iterator) from the loop's content. A while loop is often preferred if the initial statement or update statement requires more complex code than fits neatly into the for construct. However, the two are fully equivalent therefore it is ultimately a coding style decision, not a technical decision whether to use one or the other.

Infinite Loops

[edit | edit source]

One common programming mistake is to create an infinite loop. An infinite loop refers to a loop, which under certain valid (or at least plausible) input, will never exit.

Beginning programmers should be careful to examine all the possible inputs into a loop to ensure that for each such set of inputs, there is an exit condition that will eventually be reached. In addition to preventing the program from hanging (i.e. never finishing), understanding all potential inputs and exit conditions demonstrates a solid understanding of the algorithm being written. Academic studies of programming languages often test students' ability to identify infinite loops for the very reason that doing so often requires a solid understanding of the underlying code.

Compilers, debuggers, and other programming tools can only help the programmer so far in detecting infinite loops. In the fully general case, it is not possible to automatically detect an infinite loop. This is known as the halting problem. While the halting problem is not solvable in the fully general case, it is possible to determine whether a loop will halt for some specific cases.

Example of Infinite loop

[edit | edit source]
#include <iostream>
int main()
{
  while(1) {
    // printf("Infinite Loop\n");
     std::cout << ("Infinite loop\n");
  }
  return 0;
}

This code will print infinite loop with out stopping.

Where To Go Next

[edit | edit source]
Topics in C++
Beginners Data Structures Advanced

Template loop detected: C++/Lessons/Beginners

Template loop detected: C++/Lessons/Data Structures

Template loop detected: C++/Lessons/Advanced

Part of the School of Computer Science