{ } C++
Plus Two Computer Applications (Commerce) · Chapter 01

Review of C++ Programming

4 sections
Interactive loop & control-flow tracer
9 review questions
1.1

Basics of C++

1.1

Tokens, Data Types & Type Conversion

A C++ program is built from tokens — the smallest individually meaningful pieces of the language. Every token belongs to one of five categories:

Token typeWhat it is
KeywordsReserved words with a fixed meaning to the compiler, e.g. int, if, while.
IdentifiersUser-defined names for variables, functions, labels, etc.
LiteralsConstants that never change during a run — integer, floating-point, character and string constants.
PunctuatorsSymbols such as , ; { } that shape the syntax of a construct.
OperatorsSymbols that trigger an operation — arithmetic, relational, logical, assignment and the special >>/<< operators.

The five fundamental data types are int, char, float, double and void; each (except void) has its own size and range, which can be adjusted with the type modifiers signed, unsigned, short and long. When an expression mixes different data types, the compiler performs implicit conversion (always promoting the lower type to the higher one); when the programmer explicitly names the target type, it is called type casting.

1.1.1

Statements: Declaration, Input, Output & Assignment

A variable must be declared with a data type before use, and may optionally be initialised at the same time. Prefixing a declaration with const locks the variable's value for the rest of the program.

int n, sum; // declaration int n = 10; // initialisation const int n = 10; // cannot be changed later

Input uses the extraction operator >> (get from) with cin, and output uses the insertion operator << (put to) with cout. Both are binary operators and both can be cascaded — chained several times in one statement:

cin >> a >> b >> c; cout << "Sum of " << n << " numbers = " << sum;

The assignment statement stores a value in a variable using =. The compound assignment operators +=, -=, *=, /=, %= combine an arithmetic operation with assignment, and ++/-- increment or decrement a variable by 1. Used in prefix form (++a) the variable is changed first and then used; in postfix form (a++) it is used first and then changed.

  • b = a++; — equivalent to b = a; a = a + 1; (use-and-change).
  • b = ++a; — equivalent to a = a + 1; b = a; (change-and-use).
1.1.2

Structure of a C++ Program

A typical program opens with a pre-processor directive (#include) to bring in a header file, followed by a using namespace statement so identifiers such as cin, cout and endl need not be written as std::cin, std::cout and std::endl. Execution always begins and ends inside main().

#include <iostream> using namespace std; int main() { float length, breadth, peri, area; cout << "Enter the length and breadth: "; cin >> length >> breadth; peri = 2 * (length + breadth); area = length * breadth; cout << "Perimeter = " << peri << endl; cout << "Area = " << area << endl; return 0; }

endl ends the current line, working like '\n'. A program with no selection or loop, like the one above, runs in a purely sequential fashion — one statement after another.

1.2

Control Statements

1.2.1

Selection Statements: if and switch

C++ offers two families of selection statement. The if statement comes in three shapes — simple if, if–else, and the multi-branch else if ladder — while switch chooses among several cases by matching an expression's value against a set of constants, falling back on an optional default case when nothing matches.

if (ce1 > ce2) final_ce = ce1; else final_ce = ce2; if (ce3 > final_ce) final_ce = ce3; // no else needed

An else if ladder tests conditions one after another until one is true; the final else catches every case the earlier conditions missed:

if (ch >= 'A' && ch <= 'Z') cout << "Uppercase letter"; else if (ch >= 'a' && ch <= 'z') cout << "Lowercase letter"; else if (ch >= '0' && ch <= '9') cout << "Digit"; else cout << "Other character";

A switch works well only when the branching condition is an equality test on an integer or character value; an else if ladder based on ranges or relational comparisons cannot be converted to switch. The conditional operator ?: can also replace a simple if–else: final_ce = (ce1>ce2) ? ce1 : ce2;

1.2.2

Looping Statements: while, for and do–while

Every loop has four parts — initialisation, test, update, and a body — and loops fall into two families:

  • Entry-controlled (while, for) — the test is checked before the body runs, so the body may execute zero times.
  • Exit-controlled (do–while) — the test is checked after the body runs, so the body always executes at least once.

In a for loop all three expressions sit together in the header; in while and do–while, initialisation happens before the loop and the update sits inside the body.

while → unknown count, entry-checkedfor → known countdo–while → runs at least once
int num, sum = 0, dig; cin >> num; while (num > 0) { // while: sum of digits dig = num % 10; sum = sum + dig; num = num / 10; }

Try the equivalents of this trace — and the for-loop and do–while versions of similar problems — in the playground below.

1.3

Nested Loops

1.3

A Loop Inside a Loop

Placing one loop inside the body of another is called nesting. The inner loop must run through all of its iterations for every single iteration of the outer loop — much like a clock, where the second-hand completes one full sweep for each single tick of the minute-hand. The two loops must use different control variables.

for (i = 1; i <= 2; ++i) // outer loop for (j = 1; j <= 3; ++j) // inner loop cout << "\n" << i << " and " << j;
IterationOuter (i)Inner (j)Output
1111 and 1
2121 and 2
3131 and 3
4212 and 1
5222 and 2
6232 and 3

The outer loop's control variable changes only once the inner loop has fully finished. This is exactly how a triangle of stars can be built — the outer loop picks the row, the inner loop prints that many stars:

for (i = 1; i <= 5; ++i) { // outer: rows cout << "\n"; for (j = 1; j <= i; ++j) // inner: stars in a row cout << '*'; }
1.4

Jump Statements

1.4.1

goto

The goto statement transfers control unconditionally to any labelled statement in the same function. It works, but is discouraged in structured programming because it makes program flow hard to follow.

int i = 1; start: cout << i; ++i; if (i <= 50) goto start;
1.4.2 – 1.4.3

break and continue

break and continue both alter the normal flow of a loop, but in opposite ways:

continuebreak
Skips only the rest of the current iterationEnds the loop completely
Control moves to the update expression, then the next testControl moves to the statement right after the loop
Loop keeps running (unless the next test fails)Loop never runs again
Careless use in while/do–while can cause an infinite loopCommonly used with switch as well as loops
for (i = 1; i <= 10; ++i) { if (i == 6) continue; // skip printing 6 cout << i << "\t"; } // Output: 1 2 3 4 5 7 8 9 10

Inside a nested loop, break only exits the innermost loop it sits in — the outer loop is unaffected and continues to its next iteration.

Try It Yourself

Loop & Control-Flow Tracer

Pick a classic program, adjust its input, then press Run to watch the loop control variable move iteration by iteration — the same way you would hand-trace a program on paper.

while ( num > 0 ) { ... }

Digits of this number are added one at a time, right to left.

num = 123
Self-Assessment

Question & Answer Review

Tap a question to reveal the answer — a quick way to check understanding of C++ fundamentals before moving to Chapter 2.

01What is a token in C++, and what are its five categories?
A token is the smallest individually meaningful unit that makes up a C++ program. The five categories are keywords, identifiers, literals, punctuators, and operators.
02What role does the #include statement play in a program?
It is a pre-processor directive that attaches a header file to the program, making the predefined identifiers and functions declared in that header (such as cin and cout from iostream) available for use.
03List the type modifiers available in C++.
signed, unsigned, short and long.
04What are the four components every loop needs?
An initialisation expression, a test expression, an update expression, and a loop body.
05Give an example of an entry-controlled loop and explain why it is called that.
while and for are entry-controlled loops: the test expression is evaluated before the loop body runs, so the body may be skipped entirely if the condition starts out false.
06Which single operator can substitute a simple if–else statement?
The conditional (ternary) operator ?: — for example, final_ce = (ce1>ce2) ? ce1 : ce2; is equivalent to a simple if–else assigning the larger of the two.
07Distinguish between break and continue.
break terminates the loop entirely and sends control to the statement right after it. continue only skips the remaining statements of the current iteration and moves on to the loop's update expression and next test, so the loop keeps running.
08Why is goto discouraged in structured programming, even though it works?
Because it transfers control unconditionally to any labelled point in the function, jumping backward or forward freely makes the program's flow difficult to trace and maintain — the same effect can almost always be achieved more clearly with loops and selection statements.
09In a nested loop, when does the outer loop's control variable change?
Only after the inner loop has completely finished all of its iterations for the current value of the outer variable — the inner loop must run to completion (or exit via break) before the outer loop's update expression executes.