Repetitive Structures



Repetitive structures (or loops) in C++ are used to repeatedly execute a block of code as long as a condition is true.


for Loops

for loops are used when you know exactly how many times you want to execute a block of code.


Syntax:

for (initialization; condition; increment) 
{
     // code to be executed in loop
}

Example:

#include 
using namespace std;
int main()
{
      for (int i = 0; i < 5; ++i)
      {
          cout << "Value of i: " << i << endl;
      }
      return 0;
}

while Loops

while loops are used when you want to execute a block of code as long as a condition is true. The block of code may not execute at all if the condition is false from the start.


Syntax:

while (condition)
{
      // code to be executed in loop
}
    

Example:

#include 
using namespace std;
int main()
{
      int i = 0;
      while(i < 5)
      {
          cout << "Value of i: " << i << endl;
          ++i;
      }
      return 0;
}

do-while Loops

do-while loops are similar to while loops, but ensure the execution of the block of code at least once, as the condition is checked at the end of the loop.


Syntax:

do
{
    // code to be executed in loop
} while (condition);

Example:

#include 
using namespace std;
int main()
{
      int i = 0;
      do
      {
            cout << "Value of i: " << i << endl;
            ++i;
      } while(i < 5);
      return 0;
}

Color Contrast

Text Size

Text Spacing

Reading Aids


In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!


Summary

In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!


Chatbot