Skip to main content

Loop

while (and do while) loop

src/c/basics/04-while-loop.c
#include <stdio.h>

int main()
{
int i = 1, i2 = 0;

while (i < 10)
{
i2 = i * i;
printf("%d\t%d\n", i, i2);
i++;
}

// do while loop
printf("\nExample of do-while loop:\n");
i = 1;
do
{
i2 = i * i;
printf("%d\t%d\n", i, i2);
i++;
} while (i < 10);

return 0;
}

for loop

src/c/basics/04-for-loop.c
#include <stdio.h>

int main()
{
int i = 10;
int i2 = 0;

for (i = 1; i < 10; i++)
{
i2 = i * i;
printf("%d\t%d\n", i, i2);
}

return 0;
}

Break and continue

src/cpp/basics/04-break-continue.cpp
#include <iostream>
using namespace std;

int main()
{
int i = 0;

for (;;) // forever for loop
{
i++;

if (i > 10)
break;

if ((i % 2) == 0)
{
continue; // jumps to the loop beginning
}
else
{
cout << i << endl; // print odd numbers
}
}

return 0;
}