Loop
while (and do while) loop
- C
- C++
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;
}
src/cpp/basics/04-while-loop.cpp
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i <= 10)
{
cout << i << "\t" << i * i << endl;
++i;
}
cout << endl;
// do while loop
i = 1;
do
{
cout << i << "\t" << i * i * i << endl;
++i;
} while (i <= 10);
return 0;
}
for loop
- C
- C++
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;
}
src/cpp/basics/04-for-loop.cpp
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "For loop variant 1:\n";
for (i = 0; i < 5; i++)
{
cout << i << endl;
}
int j = 0;
cout << "\nFor loop variant 2:\n";
for (; j < 5; j++) // since j is already initialized, loop condition can
// start with null statement
{
cout << j << endl;
}
cout << "\nFor loop variant 3:\n";
for (int k = 0; k < 5; k++) // loop variable can be locally declared
{
cout << k << endl;
}
int size = 5;
int arr[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < size;)
{
sum += arr[i++]; // post increment i after accessing array element
}
cout << "sum = " << sum << endl;
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;
}