Program Control Repetition

Program Control Repetition


Repetition 

Repetition is a repeated action. Repeating instruction(s) until the condition given is fullfilled.
There are 3 operations in repetition :
1. For
2. While
3. Do-While

  • For
The syntax is : 

for (initializaton; condition; increment/decrement)
{
       statement(s);
}

Example (a program to count 1 to 5):

#include <stdio.h>

int main ()
{
    int i;
    for (i = 1; i <= 5; i++)
    {
          printf("%d\n", i);
    }
     return 0;
}

To make an infinite loop, remove all parameters : for ( ; ; )
to stop the infinite loop, use break;

A nested loop is a loop inside loop. Here is the example of nested loop.
(A program to print right angle triangle)

#include <stdio.h>

int main ()
{
    int i, j;
    for (i = 1; i <= 5; i++)
    {
          for (j = 1; j <= i; j++)
         {
                printf("*");
         }
         printf("\n");
    }
     return 0;
}

  • While
The syntax is :

while (condition)
{
      statement(s);
}

Example (a program to count from 1 to 5):

#include <stdio.h>

int main ()
{
    int i = 1;
    while (i <=5)
    {
          printf("%d\n", i);
          i++;
    }
     return 0;
}

  • Do - While
The syntax is :

do
{
     statement(s);
} while (condition);

The difference between While and Do-While is :
in while, if the value is false then the statement(s) will not be executed.
in do-while, the statement(s) will be executed at least one time.

  • Break and Continue
Break is for ending loop or for ending the switch operation.
Continue is to do the next loop and when it's inside a repetition, it will skip all the rest of statements.




Princess Jesslyn Lorenza
2201750036

binus.ac.id
skyconnectiva.com




Comments