How unit 2 is examined
This unit covers C++ control flow (branching, looping, jumping) and the operators; the marks come from listing branching and looping statements, increment and decrement, membership operators, logical and arithmetic operators, break and continue, and the types of loops.
Control instructions
Low weight
Definition. Control instructions decide the order in which statements execute; C++ has sequence, selection (decision), repetition (loop) and jump control instructions.
Key points.
- Sequence control runs statements one after another in the order written.
- Branching (selection) statements choose a path on a condition:
if,if-else,switchand the conditional operator?:. - Looping statements repeat a block:
for,whileanddo-while. - Jump statements transfer control unconditionally:
break,continueandgoto.
if (a > b) cout << a; // branching
for (i = 0; i < 3; i++) ; // looping
switch (n) { case 1: break; } // branching, multiway
Answer frame. Open with the definition; list branching then looping then jump statements, each with one syntax line as above; close by saying each statement is detailed in its own topic below.
Asked: [7 marks] (Dec 2020) Write down various branching and looping statements available in C++.
if statement
Not asked since 2022
Definition. The if statement executes a block only when its condition is true (non-zero).
Key points.
- Syntax:
if (condition) { statements; }. - Any non-zero value is true and zero is false.
- Without braces only the single next statement belongs to the
if. - A common bug is writing
=instead of==inside the condition.
if-else statement
Not asked since 2022
Definition. The if-else statement runs one block if the condition is true and another block if it is false.
Key points.
- Syntax:
if (c) { A } else { B }; exactly one of A or B runs. - Chains use
else ifto test several conditions in order; the first true one wins. - Nested
ifis anifinside anotherif; anelsepairs with the nearest unmatchedif.
Use of logical operators
Not asked since 2022
Definition. Logical operators combine or negate conditions and give true (1) or false (0).
Key points.
&&(AND) is true only when both operands are true.||(OR) is true when at least one operand is true.!(NOT) reverses a truth value.&&and||short-circuit: the right operand is skipped when the left already decides the result.
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 |
Example. With x=10, y=3 and arithmetic + - * / %: x+y=13, x-y=7, x*y=30, x/y=3, x%y=1; (x>5 && y<2) is 0, (x>5 || y<2) is 1, !(x>5) is 0.
int x = 10, y = 3;
cout << x + y << " " << x % y << "\n"; // 13 1
cout << (x > 5 && y < 2) << (x > 5 || y < 2) << !(x > 5); // 010
Asked: [7 marks] (Jun 2020) Explain Logical operators and Arithmetic operators with example.
Hierarchy of logical operators
Not asked since 2022
Definition. Precedence order decides which logical operator is evaluated first: ! highest, then &&, then ||.
Key points.
!binds tighter than&&, which binds tighter than||; relational operators bind tighter than all three.- So
a || b && cmeansa || (b && c). - Associativity of
&&and||is left to right; of!is right to left. - Parentheses override precedence and make code clearer.
Arithmetic operators
Not asked since 2022
Definition. Arithmetic operators perform mathematical calculation: +, -, *, / and %.
Key points.
/on two integers gives an integer quotient (10/3 = 3); one float operand gives a float result.%gives the remainder and works only on integers (10%3 = 1).*,/,%have higher precedence than+,-, all left to right.- Worked values are given under logical operators above.
Asked: [7 marks] (Jun 2020) Explain Logical operators and Arithmetic operators with example (see the example under Use of logical operators).
Relational operators
Not asked since 2022
Definition. Relational operators compare two values and give 1 (true) or 0 (false).
Key points.
- The six operators are
<,<=,>,>=,==and!=. ==tests equality while=assigns.- Relational operators have higher precedence than
==/!=for the ordering ones, and lower than arithmetic. - They are used as conditions in
ifand loops.
Assignment operators
Not asked since 2022
Definition. ==The assignment operator = stores the value of the right side in the variable on the left.==
Key points.
- Compound forms
+=,-=,*=,/=,%=combine an operation with assignment:a += 5meansa = a + 5. - Assignment associates right to left, so
a = b = 3sets both. - The left side must be a modifiable variable (an lvalue).
- Assignment has very low precedence.
Increment and decrement operators
Low weight
Definition. ++ adds 1 and -- subtracts 1 from a variable; the prefix form changes the value before it is used and the postfix form after.
Key points.
- Pre-increment
++aincrements first, then the new value is used. - Post-increment
a++uses the old value first, then increments. --aanda--behave the same way for decrement.- They work on variables only, never on constants such as
5++.
int a = 5, b;
b = a++; cout << a << " " << b; // 6 5 (use, then add)
b = ++a; cout << a << " " << b; // 7 7 (add, then use)
b = a--; cout << a << " " << b; // 6 7
b = --a; cout << a << " " << b; // 5 5
Answer frame. Open with the definition; explain prefix versus postfix in two lines; give the program above with its output; close with the difference (prefix: change then use, postfix: use then change).
Asked: [7 marks] (Jun 2020) Write a C++ program using increment and decrement operators with suitable example.
Conditional operator
Not asked since 2022
Definition. The conditional (ternary) operator ?: is the only three-operand operator: condition ? expr1 : expr2.
Key points.
- If the condition is true
expr1is the result, otherwiseexpr2. - It is a compact replacement for a simple
if-else. - Example:
max = (a > b) ? a : b;. - Both results should be of compatible types.
Bitwise operators
Not asked since 2022
Definition. Bitwise operators work on the individual bits of integer operands: &, |, ^, ~, <<, >>.
Key points.
&AND,|OR and^XOR compare bit by bit;~flips every bit.<<shifts left (multiplies by 2 per place) and>>shifts right (divides by 2).- For
6 (110)and3 (011):6&3=2,6|3=7,6^3=5,~6=-7,6<<1=12,6>>1=3. - Do not confuse
&with the logical&&.
Special operators
Low weight
Definition. Special operators are & (address-of), * (indirection or pointer dereference), . and -> (member access) and sizeof (size in bytes).
Key points.
&xgives the address ofx, and*pgives the value stored at the address in pointerp.- The membership operators are
.(dot, through an object),->(arrow, through a pointer to an object) and::(scope resolution, through a class or namespace name). p->mis the same as(*p).m, and the operators work with both structures and classes.sizeof(type or variable)returns its size in bytes at compile time, for examplesizeof(int)is 4 andsizeof(double)is 8 on common systems.
struct S { int m; } s, *p = &s;
s.m = 1; p->m = 2; // dot on object, arrow on pointer
// void A::show() { } // :: names the class the function belongs to
cout << sizeof(int); // 4
Answer frame. Open with "membership operators give access to members of a class or structure"; define ., -> and :: in turn; show the code above; close by naming when each is used.
Asked: [7 marks] (Dec 2020) What is mean by membership operator in C++?
Loops: while loop
Not asked since 2022
Definition. A loop repeats a block while a condition holds; while (cond) { body } tests the condition before every pass, so it is entry-controlled and may run zero times.
Key points.
- Loop kinds:
for,while(entry-controlled) anddo-while(exit-controlled). - Entry-controlled loops test first and can execute zero times; the exit-controlled
do-whiletests last and runs at least once. whileneeds initialisation before the loop and an update inside it, or it never ends.- Example:
int i=1; while(i<=3){ cout<<i<<" "; i++; }prints1 2 3.
Asked: [7 marks] (Jun 2020) Explain various types of Loops used in C++ with suitable example (see while, for and do-while sections).
for loop
Not asked since 2022
Definition. The for loop packs initialisation, condition and update in one line: for (init; cond; update) { body }.
Key points.
- Initialisation runs once, then the condition is tested before each pass, and the update runs after each pass.
- It is entry-controlled and best when the number of repetitions is known.
- Example:
for(int i=1;i<=3;i++) cout<<i<<" ";prints1 2 3. for(;;)is an infinite loop.
do-while loop
Not asked since 2022
Definition. The do-while loop executes its body first and then tests the condition: do { body } while (cond);.
Key points.
- It is exit-controlled, so the body runs at least once even when the condition is false.
- A semicolon must follow the closing
while(cond). - Example:
int i=0; do { cout<<i; i++; } while(i<0);prints0, while awhileloop would print nothing.
Odd loop
Not asked since 2022
Definition. An odd loop is a loop that does not follow the fixed for-count pattern: it runs an unknown number of times, or uses several variables or an unusual exit.
Key points.
- Typical forms are
while(1)orfor(;;)left only bybreak, or a loop that repeats until the user types a stop value. - The number of passes is not known beforehand.
- The condition can be omitted or moved to the body, with
breakending the loop.
Nested loop
Not asked since 2022
Definition. A nested loop is a loop placed inside the body of another loop.
Key points.
- For each pass of the outer loop the inner loop runs completely.
- Total passes are the outer count times the inner count.
- It is used for tables, matrices and patterns.
- Example: outer
i=1..2, innerj=1..2gives pairs11 12 21 22.
break
Not asked since 2022
Definition. break immediately leaves the nearest enclosing loop or switch.
Key points.
- Syntax is
break;and control moves to the statement after the loop or switch. - In
switchit stops fall-through to the next case. - In nested loops it exits only the innermost loop.
for (int i = 1; i <= 5; i++) {
if (i == 2) continue; // skip 2
if (i == 4) break; // leave loop at 4
cout << i << " ";
} // 1 3
Asked: [7 marks] (Jun 2020) Explain Break and Continue keyword with appropriate program (see the program above and continue below).
continue
Not asked since 2022
Definition. continue skips the rest of the current pass and jumps to the next iteration of the loop.
Key points.
- Syntax is
continue;; inforit goes to the update expression, inwhileanddo-whileto the condition test. - Unlike
break, the loop itself does not end. - In the program above,
continueskips 2,breakstops at 4, so the output is1 3.
Case control structure
Not asked since 2022
Definition. switch selects one of many blocks by matching an integer or character expression with case labels.
Key points.
- Syntax:
switch(expr) { case 1: ...; break; case 2: ...; break; default: ...; }. - Case values must be integer or character constants and unique.
- Without
breakexecution falls through into the following cases. defaultruns when no case matches.
goto
Not asked since 2022
Definition. goto label; transfers control unconditionally to the statement marked label: in the same function.
Key points.
- Example:
goto end; ... end: cout<<"done";. - It breaks structured flow and makes programs hard to follow, so it is avoided.
- It cannot jump into another function.
Exit statement
Not asked since 2022
Definition. exit(status) from <cstdlib> terminates the whole program immediately.
Key points.
exit(0)means normal termination and a non-zero value signals an error.- It ends the program from any function, unlike
breakorreturn. - It closes open files and calls static destructors.
Last-minute revision
- Branching:
if,if-else,switch,?:; looping:for,while,do-while; jumps:break,continue,goto. ++achanges then uses;a++uses then changes: froma=5,b=a++gives a=6, b=5 andb=++agives a=7, b=7.&&needs both true,||needs one,!reverses; precedence!then&&then||.- With 10 and 3:
/gives 3 and%gives 1;%works only on integers. - Membership operators:
.object,->pointer,::scope resolution. whileandforare entry-controlled;do-whileis exit-controlled and runs at least once.breakleaves the loop;continueskips to the next iteration.6&3=2, 6|3=7, 6^3=5, ~6=-7, 6<<1=12, 6>>1=3.switchneedsbreakto stop fall-through;exit(0)ends the program.
Memory hooks
- Pre = change then use; post = use then change.
- NOT, AND, OR: highest to lowest binding.
- Dot for the object, arrow for the pointer.
- While looks first, do-while leaps first.
- Break breaks out, continue carries on.
Coverage checklist
- control instructions: Dec 2020 branching and looping statements.
- if
- if-else
- use of logical operator: Jun 2020 logical and arithmetic operators.
- hierarchy of logical operators
- arithmetic operators: Jun 2020 logical and arithmetic operators.
- relational operators
- assignment operators
- increment and decrement operators: Jun 2020 program.
- conditional operators
- bit wise operators
- special operators, “&,*,.,>, “sizeof”: Dec 2020 membership operator.
- Loops control structure: while loop: Jun 2020 types of loops.
- for loop
- do – while loop
- odd loop
- nested loop
- break: Jun 2020 break and continue.
- continue: Jun 2020 break and continue.
- case control structure
- go to
- exit statement