Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

COMPUTER SKILL 2

Edition 2 2014

Unit Four
Control Structure
A simple C++ statement is each of the individual instructions of a program, like the variable
declarations and expressions seen in previous sections. They always end with a semicolon (;),
and are executed in the same order in which they appear in a program.
But programs are not limited to a linear sequence of statements. During its process, a program
may repeat segments of code, or take decisions. For that purpose, C++ provides flow control
statements that serve to specify what has to be done by our program, when, and under which
circumstances.
Many of the flow control statements explained in this section require a generic (sub)
statement as part of its syntax. This statement may either be a simple C++ statement, -such as a
single instruction, terminated with a semicolon (;) - or a compound statement. A compound
statement is a group of statements (each of them terminated by its own semicolon), but all
grouped together in a block, enclosed in curly braces: {}:
{statement1; statement2; statement3 ;}
The entire block is considered a single statement (composed itself of multiple sub statements).
Whenever a generic statement is part of the syntax of a flow control statement, this can either be
a simple statement or a compound statement.

Selection statements: if and else


The ability to control the flow of your program, letting it make decisions on what code to
execute, is valuable to the programmer. The if statement allows you to control if a program
enters a section of code or not based on whether a given condition is true or false.
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

C++ programming language provides following types of decision making statements. Click the
following links to check their detail.

Statement Description
if statement An if statement consists of a Boolean expression followed
by one or more statements.
if...else statement An if statement can be followed by an optional else
statement, which executes when the Boolean expression is
false.
switch statement A switch statement allows a variable to be tested for equality
against a list of values.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).
An if statement consists of a Boolean expression followed by one or more statements. The if
keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its syntax
is:

Syntax:
The syntax of an if statement in C++ is:

if(boolean_expression)
{
// statement(s) will execute if the boolean
expression is true
}

If the Boolean expression evaluates to true, then the block of code inside the if statement will be
executed. If Boolean expression evaluates to false, If it is false, statement(s) (block of code) is
not executed (it is simply ignored), then the first set of code after the end of the if statement
(after the closing curly brace) will be executed.
Following is the general from of a typical decision making structure found in most of the
programming languages:
Example 1:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number > 0)
{
// Checking whether an integer is positive or not.
cout << "You entered a positive integer: "<<number<<endl;
}
cout<<"This statement is always executed because it's outside if statement.";
return 0;
}

Example 2:

#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 10;

// check the boolean condition


if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}

Output
a is less than 20;
value of a is : 10

For example, the following code fragment prints the message (x is 100), only if the value
stored in the x variable is indeed 100:

1 if (x == 100)
2 cout << "x is 100";

If x is not exactly 100, this statement is ignored, and nothing is printed. If you want to include
more than a single statement to be executed when the condition is fulfilled, these statements shall
be enclosed in braces ({}), forming a block:
1 if (x == 100)
2 {
3 cout << "x is ";
4 cout << x;
5 }

As usual, indentation and line breaks in the code have no effect, so the above code is
equivalent to:

if (x == 100) { cout << "x is "; cout << x; }

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

Syntax:
The syntax of an if...else statement in C++ is:

If (boolean_expression)
{
// statement(s) will execute if the boolean
expression is true
}
else
{
// statement(s) will execute if the boolean
expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram:

Example
#include <iostream>
using namespace std;

int main ()
{
// local variable declaration:
int a = 100;

// check the boolean condition


if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}

Output:
a is not less than 20;
value of a is : 100
#include <iostream>
using namespace std;
int main()
{
int number; cout<< "Enter an integer: ";
cin>> number;
if ( number >= 0)
{
cout << "You entered a positive integer: "<<number<<endl;
}
else
{
cout<<"You entered a negative integer: "<<number<<endl;
}
cout<<"This statement is always executed because it's outside if...else statement.";
return 0;
}

Example:

1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not 100";

This prints x is 100, if indeed x has a value of 100, but if it does not, and only if it does not, it
prints x is not 100 instead.

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:
The syntax of an if...else if...else statement in C++ is:

if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}

One example where the use of else if provides a convenient solution is checking multiple ranges
for a value. For example, if we want to convert a final grade in a scale of 0 to 100 to a letter
grade (for example, 90 to 100 corresponds to an A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and
less than 60 is F), we could use the following fragment of code:

if (grade >= 90)


{
letter_grade = 'A';
}
else if (grade >= 80)
{
letter_grade = 'B';
}
else if (grade >= 70)
{
letter_grade = 'C';
}
else if (grade >= 60)
{
letter_grade = 'D';
}
else
{
letter_grade = 'F';
}

Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;

// check the boolean condition


if( a == 10 )
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;

return 0;
}
Output:
Value of a is not matching
Exact value of a is : 100

Example:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number > 0)
{
cout << "You entered a positive integer: "<<number<<endl;
} else if (number < 0){
cout<<"You entered a negative integer: "<<number<<endl;
} else {
cout<<"You entered 0."<<endl;
}
cout<<"This statement is always executed because it's outside nested if..else statement.";
return 0;
}

This prints whether x is positive, negative, or zero by concatenating two if-else structures.
Again, it would have also been possible to execute more than a single statement per case by
grouping them into blocks enclosed in braces: {}.

Switch Statement
Consider a situation in which, only one block of code needs to be executed among
many blocks. This type of situation can be handled using nested if...else statement
but, the better way of handling this type of problem is using switch...case
statement.

The syntax of the switch statement is a bit peculiar. Its purpose is to check for a
value among a number of possible constant expressions. It is something similar to
concatenating if-else statements, but limited to constant expressions. Its most
typical syntax is:

syntax is:

switch (expression)
{
case constant1:
group-of-statements-1;
break;
case constant2:
group-of-statements-2;
break;
.
.
.
default:
default-group-of-statements

It works in the following way: switch evaluates expression and checks if it is


equivalent to constant1; if it is, it executes group-of-statements-1 until it finds the
break statement. When it finds this break statement, the program jumps to the end
of the entire switch statement (the closing brace).

Flowchart of switch Statement


Example: C++ switch Statement
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;
switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
break;
case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/': cout<<num1<<" / "<<num2<<" = "<<num1/num2;
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
cout<<"Error! operator is not correct";
break;
} return 0;
}
Output:

Select an operator either + or - or * or /


-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2
The break statement at the end of each case cause switch statement to exit. If
break statement is not used, all statements below that case statement are also
executed.

Exercise:
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;
switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/': cout<<num1<<" / "<<num2<<" = "<<num1/num2;
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
cout<<"Error! operator is not correct";
break;
}
cin.get();
return 0;
}
What is the output for:
Select an operator either + or - or * or /
+
Enter two operands: 2.3
4.5

What is the output for:


Select an operator either + or - or * or /
+
Enter two operands: 2.3
4.5

Loop Types

There may be a situation, when you need to execute a block of code several numbers of times.
In general statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:

C++ programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.

Loop Type Description


while loop Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the loop
body.
for loop Execute a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
do...while loop Like a while statement, except that it tests the condition at the
end of the loop body
nested loops You can use one or more loop inside any another while, for or
do..while loop.

C++ for loop


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax:
The syntax of a for loop in C++ is:

for (initialization; condition; increment )


{
statement(s);
}

Here is the flow of control in a for loop:


The initialization step is executed first, and only once. This step allows you to

declare and initialize any loop control variables. You are not required to put a statement
here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the for loop terminates.
Flow Diagram:

Example:
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}

return 0;
}

Here is the countdown example using a for loop:

1 // countdown using a for loop


2 #include <iostream>
3 using namespace std;
4
5 int main ()
6 {
7 for (int n=10; n>0; n--) {
8 cout << n << ", ";
9 }
10 cout << "liftoff!\n";
return 0;
11 }

Output:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
The three fields in a for-loop are optional. They can be left empty, but in all cases the
semicolon signs between them are required. For example, for (;n<10;) is a loop without
initialization or increase (equivalent to a while-loop); and for (;n<10;++n) is a loop with
increase, but no initialization (maybe because the variable was already initialized before the
loop). A loop with no condition is equivalent to a loop with true as condition (i.e., an infinite
loop).
Because each of the fields is executed in a particular time in the life cycle of a loop, it may be
useful to execute more than a single expression as any of initialization, condition, or statement.
Unfortunately, these are not statements, but rather, simple expressions, and thus cannot be
replaced by a block. As expressions, they can, however, make use of the comma operator (,):
This operator is an expression separator, and can separate multiple expressions where only one is
generally expected. For example, using it, it would be possible for a for loop to handle two
counter variables, initializing and increasing both:

1 for ( n=0, i=100 ; n!=i ; ++n, --i )


2 {
3 // whatever here...
4 }
This loop will execute 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (i.e., that n is not equal to i).
Because n is increased by one, and i decreased by one on each iteration, the loop's condition will
become false after the 50th iteration, when both n and i are equal to 50.

Example: A for loop with no increment


#include <iostream>
1
using namespace std;
2
int main()
3
{
4
int x;
5
6
for(x=0; x != 123; ) {
7
cout << "Enter a number: ";
8
cin >> x;
9
}
10
return 0;
11
}
12

Example: The body of a for loop can be empty

1 #include <iostream>
2 using namespace std;
3 int main()
4 {
5 int i;
6 int sum = 0;
7 // sum the numbers from 1 through 10
8 for(i=1; i <= 10; sum += i++) ;
9
10 cout << "Sum is " << sum;
11 return 0;
12 }
13

while loop
A while loop statement repeatedly executes a target statement as long as a given condition is
true.

Syntax:
The syntax of a while loop in C++ is:

while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For example, let's have a look at a countdown using a while-loop:

1
2 // custom countdown using while
3 #include <iostream>
4 using namespace std;
5 int main ()
6 {
7 int n = 10;
8 while (n>0) {
9 cout << n << ", ";
1 --n;
0 }
1 cout << "liftoff!\n";
1 }
1
2
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!

The first statement in main sets n to a value of 10. This is the first number in the countdown.
Then the while-loop begins: if this value fulfills the condition n>0 (that n is greater than zero),
then the block that follows the condition is executed, and repeated for as long as the condition
(n>0) remains being true.
The whole process of the previous program can be interpreted according to the following
script (beginning in main):
1. n is assigned a value
2. The while condition is checked (n>0). At this point there are two possibilities:
o condition is true: the statement is executed (to step 3)
o condition is false: ignore statement and continue after it (to step 5)
3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n and decreases n by 1)
4. End of block. Return automatically to step 2.
5. Continue the program right after the block:
print liftoff! and end the program.
A thing to consider with while-loops is that the loop should end at some point, and thus the
statement shall alter values checked in the condition in some way, so as to force it to become
false at some point. Otherwise, the loop will continue looping forever. In this case, the loop
includes --n, that decreases the value of the variable that is being evaluated in the condition (n)
by one - this will eventually make the condition (n>0) false after a certain number of loop
iterations. To be more specific, after 10 iterations, n becomes 0, making the condition no longer
true, and ending the while-loop.

The do-while loop


It behaves like a while-loop, except that condition is evaluated after the execution of statement
instead of before, guaranteeing at least one execution of statement, even if condition is never
fulfilled
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:
The syntax of a do...while loop in C++ is:

do
{
statement(s);
}while( condition )
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.
Flow Diagram:

Example
#include <iostream> Output:
using namespace std;
int main () value of a: 10
{ value of a: 11
value of a: 12
// Local variable declaration:
value of a: 13
int a = 10; value of a: 14
// do loop execution value of a: 15
do value of a: 16
{ value of a: 17
cout << "value of a: " << a << endl; value of a: 18
a = a + 1; value of a: 19
}while( a < 20 );
return 0;
}

For example, the following example program echoes any text the user introduces until the user
enters goodbye:

1 #include <iostream> Enter text: hello


2 #include<string> You entered: hello
3 using namespace std; Enter text: who's there?
4 int main () You entered: who's there?
5 { Enter text: goodbye
6 string str; You entered: goodbye
7 do {
8 cout << "Enter text: ";
9 cin >> str;
10 cout << "You entered: " << str << '\n';
11 } while (str != "goodbye");
12 return 0;
13 }
14

The do-while loop is usually preferred over a while-loop when the


statement needs to be executed at least once, such as when the condition
that is checked to end of the loop is determined within the loop statement
itself. In the previous example, the user input within the block is what will
determine if the loop ends. And thus, even if the user wants to end the loop
as soon as possible by entering goodbye, the block in the loop needs to be
executed at least once to prompt for input, and the condition can, in fact,
only be determined after it is executed.

Nested loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.

Syntax:
The syntax for a nested for loop statement in C++ is as follows:

for ( init; condition; increment )


{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}

The syntax for a nested while loop statement in C++ is as follows:

while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
do
{
The syntax forstatement(s);
a nested do...while
// youloop
can statement
put more instatements.
C++ is as follows:
do
{
statement(s);
}while( condition );

}while( condition );

Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:

#include <iostream> 2 is prime


using namespace std; 3 is prime
5 is prime
7 is prime
int main ()
11 is prime
{ 13 is prime
int i, j; 17 is prime
19 is prime
for(i=2; i<100; i++) { 23 is prime
for(j=2; j <= (i/j); j++) 29 is prime
.
if(!(i%j)) break; // if factor found, not prime
.
if(j > (i/j)) cout << i << " is prime\n"; .
} 89 is prime
return 0; 97 is prime
}

Loop Control Statements (Jump statements):


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. C++ supports the
following control statements. Click the following links to check their detail.

Control Statement Description


break statement Terminates the loop or switch statement and transfers execution
to the statement immediately following the loop or switch.
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
goto statement Transfers control to the labeled statement. Though it is not
advised to use goto statement in your program.
C++ break statement
The break statement has the following two usages in C++:
When the break statement is encountered inside a loop, the loop is immediately

terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.

Syntax:
The syntax of a break statement in C++ is:

break;

Flow Diagram:

Example:

#include <iostream> OUTPUT


using namespace std; value of a: 10
int main () value of a: 11
{ value of a: 12
// Local variable declaration: value of a: 13
int a = 10; value of a: 14
value of a: 15
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
{
// terminate the loop
break;
}
}while( a < 20 );

return 0;
}

C++ continue statement


The continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, program control passes to the conditional tests.

Syntax:
The syntax of a continue statement in C++ is:

continue;
Flow Diagram:

Example:

#include <iostream> OUTPUT


using namespace std; value of a: 10
value of a: 11
int main () value of a: 12
{ value of a: 13
// Local variable declaration: value of a: 14
int a = 10; value of a: 16
value of a: 17
// do loop execution value of a: 18
do value of a: 19
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );

return 0;
}
The Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally
used for this purpose. Since none of the three expressions that form the for loop are required, you
can make an endless loop by leaving the conditional expression empty.

#include <iostream> When the conditional expression is absent, it is


using namespace std;
assumed to be true. You may have an
int main () initialization and increment expression, but C+
{
+ programmers more commonly use the for(;;)
for( ; ; )
{
construct to signify an infinite loop.
printf("This loop will run forever.\n");
} NOTE: You can terminate an infinite loop by
pressing Ctrl + C keys.
return 0;
}
Exercise:
Exercise 1:
1
2
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int counter = 0;
8
9 while(counter < 5)
1 {
0 counter++;
1 cout << "Looping! ";
1 }
1
2 cout << "\nCounter: " << counter << ".\n"
1 ;
3 return 0;
1 }
4
1
5

Exercise 2:
1 #include <iostream>
2 using namespace std;
3 int main()
4 {
int counter = 1;
5
6
while ( counter <= 10 )
7
{
8
cout << counter << " ";
9
counter++;
10
}
11
12
cout << endl;
13
return 0;
14
}
15
Exercise 3:

1
2
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int len;
8
9 cout << "Enter length (1 to 79): ";
1
0 cin >> len;
1
1 while(len>0 && len<80) {
1 cout << '.';
2 len--;
1 }
3 return 0;
1 }
4
1
5

Exercise 4:

1
2
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int len;
8
9 cout << "Enter length (1 to 79): ";
1
0 cin >> len;
1
1 while(len>0 && len<80) {
1 cout << '.';
2 len--;
1 }
3 return 0;
1 }
4
1
5
Exercise 5: Demonstrates WHILE loops using fibonacci
series

Exercise 6:
1
2 #include <iostream>
3 using namespace std;
4 int main()
5 {
6 int counter;
7
cout << "How many hellos? ";
8
9 cin >> counter;
1 do
0 {
1 cout << "Hello\n";
1 counter--;
1 } while (counter >0 );
2
1 cout << "counter is: " << counter <<endl
3 ;
1 return 0;
4 }
1
5

Exercise 7:

1
#include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 int num;
8
9
do {
1
0 cout << "Enter a number (100 to stop): ";
1
1 cin >> num;
1 } while(num != 100);
2
1
return 0;
3
1 }
4
Exercise: The body of a for loop can be empty
1
2
3
4
5
6
7
8
9 #include <iostream>
1
0 using namespace std;
1
1 int main() {
1 int table = 11;
2
const int table_min = 2;
1
3 const int table_max = 12;
1
4 // Create the top line of the table
1 cout << " |";
5 for(int i = 1 ; i <= table ; i++)
1 cout << " " << setw(3) << i << " |";
6
cout << endl;
1
7
1 // Create the separator row
8 for(int i = 0 ; i <= table ; i++)
1 cout << "------";
9 cout << endl;
2
0
2 for(int i = 1 ; i <= table ; i++) {
1 cout << " " << setw(3) << i << " |";
2
2 // Output the values in a row
2 for(int j = 1 ; j <= table ; j++)
3 cout << " " << setw(3) << i*j << " |";
2
cout << endl;
4
2 }
5
2
6 return 0;
2 }
7
2
8
2
9
3
0
3
1

You might also like