C++ ENG: BASMA RAMADAN
Iteration statements (loops)
for
Syntax of for loop
for(initialization; condition ; increment/decrement)
C++ statement(s);
EX 1:
for(int i=1; i>=2; i++){
cout<<"Value of variable i is: "<<i<<endl;
EX 2:
for (int n=10; n>0; n--) {
cout << n << ", ";
Jump statements
The break statement
Example:
for (int n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
C++ ENG: BASMA RAMADAN
The continue statement
Example:
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
Exercises
Write a program in C++ to print a square pattern with # character.
####
####
####
####
int size;
cout << "\n\n Print a pattern like square with # character:\n";
cout << "--------------------------------------------------\n";
cout << " Input the number of characters for a side: ";
cin >> size;
for (int row = 1; row <= size; ++row)
{
for (int col = 1; col <= size; ++col)
{
cout << "# ";
}
cout << endl;
Write a program in C++ to display the pattern like right angle triangle using an asterisk. Go
*
**
C++ ENG: BASMA RAMADAN
***
****
*****
int i,j,rows;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
cout<<"*";
cout<<endl;
}
Write a program in C++ to display the pattern like right angle triangle with number.
1
12
123
1234
12345
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
cout<<k++<<" ";
cout<<endl;
}
Write a program in C++ to make such a pattern like right angle triangle using number which will repeat
the number for that row.
1
C++ ENG: BASMA RAMADAN
22
333
4444
55555
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
cout<<i;
cout<<endl;
}
-Find sum of 10 numbers.
-Search for odd numbers between 1 to 21and print them.