Revision approach
- Program design, tracing, debugging, justification
- C++17 example baseline
- Labeled Java-specific behavior
- Blueprint: six items
👁 Full explanation
Learn to design, trace, debug and justify small programs. C++17 is the default for valid C++ examples; Java-specific behavior is labeled. The official blueprint allocates six items. - State-table tracing before output choices
- Types → precedence → side effects
- Control flow → bounds
👁 Full explanation
Trace a small state table before looking at output choices. Check types, precedence, side effects, control flow and bounds in that order. - Recall function and array traversal
- Loop correctness argument
- Boundary and invalid-input tests
👁 Full explanation
Write one function, one array traversal and one loop correctness argument from memory; test boundaries and invalid inputs. - Rule-derived answers
- Comparisons for revision
- Qualified malformed questions in reference index
👁 Full explanation
Use comparisons for revision, but derive answers from rules and check that the question states the necessary assumptions.
CP01
Problem-to-program workflow
[Exam Focus]- Problem-to-program workflow
- Inputs, outputs, legal ranges, edge cases
- Manual small-case solution
- Algorithm → pseudocode or flowchart
- Implement → test → maintain
- Largest-of-three: best=first input
- Compare second, then third
- Zero initialization fails all-negative inputs
👁 Full explanation
Identify inputs, outputs, legal ranges and edge cases before coding. Solve one small case manually, choose an algorithm, express it as pseudocode or a flowchart, implement, test and maintain. For the largest of three numbers, initialize best to the first input, compare the second and third, then report best. Initializing best to zero fails when all inputs are negative. - Programming responsibilities
- Writing, testing, debugging, maintaining
- Actual versus required result
- Execution alone insufficient
👁 Full explanation
Programming includes writing, testing, debugging and maintaining instructions. A program can execute without solving its intended problem; compare its actual result with the required result.
1 related practice question
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Problem-to-program workflow
CP02
Algorithms and paradigms
[Exam Focus]- Algorithm properties
- Precise executable steps
- Termination for every legal input
- Definiteness: unambiguous meaning
- Effectiveness: performable steps
- Optional inputs, specified result
- Correctness against specification
- Efficiency: desirable, measurable
- Inefficient terminating algorithms still qualify
- Module's desirable-efficiency listing
👁 Full explanation
An algorithm gives precise, executable steps and terminates for every legal input. Definiteness means each step has an unambiguous meaning; effectiveness means a step can actually be performed. Inputs may be absent, but a useful algorithm specifies a result. Correctness means the result meets the specification. Efficiency is desirable and measurable, but an inefficient terminating algorithm is still an algorithm. Efficiency is also a desirable property of an algorithm. - Programming paradigms
- Procedural: procedures organize operations
- Structured: sequence, selection, iteration
- Object oriented: state and behavior
- Functional: function evaluation
- Conditional: construct, not paradigm
👁 Full explanation
Procedural programming organizes operations in procedures; structured programming combines sequence, selection and iteration; object oriented programming organizes state and behavior in objects; functional programming emphasizes function evaluation. A conditional statement is a construct, not a separate programming paradigm.
6 related practice questions
Blueprint: CP1 · Note references: CP-M, CP-N
- Algorithm properties
CP03
Language generations and portability
- Language generations
- First: machine instructions
- Second: symbolic assembly
- Third: C++, Java, general high-level
- Fourth: SQL, queries, application generators
- Fifth: loose historical category
- Declarative logic, constraints, AI/expert systems
- Generation independent of interpretation
👁 Full explanation
Machine instructions are conventionally first generation; symbolic assembly is second; general high-level languages such as C++ and Java are third. Database query and application generators such as SQL are conventionally fourth generation. Fifth generation is a loose historical category associated with declarative logic, constraints and AI/expert systems. Generations do not determine whether an implementation uses an interpreter. - Language portability and conventions
- Machine/assembly: instruction-set dependence
- Readable high-level source
- Recompile without platform assumptions
- Humans write assembly and high-level
- Python, Perl, PHP: conventional scripting
- C++: conventionally compiled
- Usage labels, not technical prohibitions
👁 Full explanation
Machine and assembly code depend on an instruction set. High-level source is easier to read and often portable after recompilation, provided it avoids platform assumptions. People can write both assembly and high-level programs. Python, Perl and PHP are commonly called scripting languages; C++ is conventionally compiled. These labels describe common use, not an absolute technical prohibition.
10 related practice questions
Note references: CP-M, CP-U
- Language generations
CP04
Compilation, linking and loading
[Exam Focus]- Conventional C++ toolchain
- Source → preprocessing → compilation proper
- Assembly → object files → linking
- Executable → loading → execution
- #include: preprocessing directive
- Compiler may emit assembly
- Assembler: object-file machine instructions
- Linker: external-symbol resolution
- Object files and libraries combined
- Loader: memory placement and startup
👁 Full explanation
In the conventional C++ toolchain: source → preprocessing → compilation proper → assembly → object files → linking → executable → loading → execution. Preprocessing handles directives such as #include; compilation may emit assembly; the assembler emits machine instructions in an object file. The linker resolves external symbols and combines object files and libraries. The loader places an executable and required components in memory and starts it. - Translation caveats
- GCC: first four stages
- Compiler output needn't be executable/native
- Java javac → bytecode
- JVM: interpretation or runtime compilation
- Interpreters execute program representations
- Line-by-line: beginner approximation
- Multiple compilation passes
- Whole-program one-step claim overbroad
👁 Full explanation
GCC documents the first four stages explicitly. A compiler need not emit a complete executable or even native machine code. Java javac produces bytecode, which a JVM interprets or compiles at runtime. Interpreters execute a program representation; “one source line at a time” is a beginner approximation. Compilation uses multiple passes, so “whole program in one step” is not literally universal.
16 related practice questions
Blueprint: CP1 · Note references: CP-M, CP-N, CP-C
- Conventional C++ toolchain
CP05
Identifiers, keywords and comments
- ASCII identifier rules
- Initial letter or underscore
- Subsequent letters, digits, underscores
- Keywords forbidden
- Case sensitivity: exitExam ≠ ExitExam
- delete, float: keywords
- FLOAT, variable_1234: valid
- 4thInput, T-3, spaces: invalid identifiers
- Reserved underscore patterns avoided
👁 Full explanation
In the basic ASCII identifier rules, start with a letter or underscore; continue with letters, digits or underscores. Do not use a keyword. C++ is case sensitive: exitExam and ExitExam differ; delete and float are keywords, but FLOAT is a legal identifier. variable_1234 is valid; 4thInput, T-3 and names containing spaces are not single identifiers. Avoid reserved underscore patterns in application code. - Comments and entry point
- // line comments
- /* ... */ block comments
- Intent, assumptions, maintenance
- Comments don't execute
- No automatic speed/reliability/portability improvement
- main: entry function, not keyword
👁 Full explanation
Comments use // to the line end or /* ... */ for a block. They explain intent and assumptions for maintenance; ordinary comments do not execute or automatically improve speed, reliability or portability. main is the conventional entry function name, not a C++ keyword.
11 related practice questions
Note references: CP-M, CP-N
- ASCII identifier rules
CP06
Declarations, constants and types
[Exam Focus]- Declaration versus initialization
- type name;
- type name = value;
- int age = 20;
- Declaration: name and type
- Initialization: initial value
- Later assignment replaces value
- Scalar a=b copies value
- Later b changes leave a unchanged
- Pointer assignment copies address
- Java object-reference assignment copies reference
👁 Full explanation
Write type name; or type name = value; for ordinary variables: int age = 20;. Declaration introduces a name and type; initialization gives its initial value; later assignment replaces a value. a=b copies a scalar value, so later changes to b do not change a. A pointer or Java object reference instead copies an address/reference. - Types, constants and aliases
- int: whole numbers
- float/double: fractional approximations
- char: character
- bool: logical values
- Implementation-dependent C++ sizes
- Java widths don't transfer
- short n ≡ short int n
- int short n: same signed short
- const int ≡ int const
- Ordinary const int requires initialization
- typedef: alias, not distinct type
👁 Full explanation
Use int for whole numbers, float/double for fractional approximations, char for a character and bool for logical values in C++. Type sizes depend on the implementation; do not import Java widths into C++. short n, short int n and int short n denote the same signed short type. const int n=5 and int const n=5 are equivalent; an ordinary const int needs initialization. typedef creates an alias, not a distinct new type.
9 related practice questions
Blueprint: CP1 · Note references: CP-M, CP-N
- Declaration versus initialization
CP07
Literals, conversions and sizeof
- Literals and storage sizes
- 'A': character literal
- "A": string literal
- Terminator storage beyond visible characters
- sizeof: bytes
- sizeof(char)==1
- Byte width and sizes implementation-dependent
- sizeof(array): total before pointer conversion
👁 Full explanation
Single quotes denote a character literal, such as 'A'; double quotes denote a string literal, such as "A". A string includes more storage than just its visible characters when a terminator is required. sizeof reports size in bytes, with sizeof(char)==1; the byte width and other sizes are implementation dependent. sizeof(array) gives total array storage before conversion to a pointer. - Conversion timing
- int x=5,y=2: x/y=2
- Double assignment after division: 2.0
- static_cast<double>(x)/y=2.5
- Cast before fractional operation
- In-range float→int: toward-zero truncation
👁 Full explanation
With int x=5,y=2, x/y is 2. Assigning that quotient to double gives 2.0, not 2.5. static_cast<double>(x)/y performs floating division and yields 2.5. Converting an in-range fractional floating value to int truncates toward zero. Cast before the operation if a fractional result is needed.
5 related practice questions
Note references: CP-M, CP-N
- Literals and storage sizes
CP08
Arithmetic and compound updates
- Arithmetic grouping and validity
- *, /, % before +, -
- Equal-precedence arithmetic: left grouping
- Integer division: toward-zero truncation
- a == (a/b)*b + a%b
- Identity requires valid division
- %: integral operands only
- (8.0*3)%5: invalid
- Division by zero: no ordinary output
- Signed overflow: no ordinary output
👁 Full explanation
Multiplication, division and remainder have higher precedence than addition and subtraction; equal-precedence arithmetic groups left to right. Integer division truncates toward zero. For integers, a == (a/b)*b + a%b when the division is valid. % requires integral operands in C++; (8.0*3)%5 is invalid. Division by zero and signed integer overflow cannot be given ordinary numeric outputs. - Compound assignment traces
- +=, -=, *=, /=, %=
- Operation then conversion to x's type
- Simple x op= y: x=x op y
- p=q=n=8: p+=n → 16
- p/=q → 2
- x=10: +=5, /=2 → 7
- x=x+x doubles, not generally increments
👁 Full explanation
x+=y, x-=y, x*=y, x/=y and x%=y update x using the operation and conversion to its type. For simple variables, trace them as x=x op y. Starting p=q=n=8, p+=n gives 16 and p/=q gives 2. Starting x=10, x+=5 then x/=2 gives 7. x=x+x doubles; it does not generally add one.
12 related practice questions
Note references: CP-M, CP-N
- Arithmetic grouping and validity
CP09
Increment operators and sequencing
- Prefix versus postfix
- Expression value versus stored value
- ++x: increment, yield new
- x++: yield old, increment
- a=8,b=5: a++ + --b=12
- Final a=9,b=4
- x=1,y=10,z=-3: (x++*y--)+ ++z=8
- Final x=2,y=9,z=-2
👁 Full explanation
Prefix ++x changes x and yields the new value; postfix x++ yields the previous value and also increments x. Separate the value used in the expression from the stored value after it. Starting a=8,b=5, a++ + --b uses 8+4, gives 12, and leaves a=9,b=4. Starting x=1,y=10,z=-3, (x++*y--)+ ++z gives 8 and leaves x=2,y=9,z=-2. - Grouping versus evaluation order
- Repeated unsequenced modifications unsafe
- C++17 operator-form stream sequencing
- cout<<x++<<" "<<++x: 5 7
- Before C++17: undefined behavior
- Bank options omit correct C++17 output
👁 Full explanation
Precedence determines grouping, not a universal evaluation order. Avoid expressions that modify a variable multiple times without sequencing. In C++17 and later, chained operator-form stream insertions are sequenced left to right: with x=5, cout<<x++<<" "<<++x prints 5 7. Before C++17 this expression has undefined behavior. For the C++17 expression above, 5 6, 5 5, 6 5 and 6 6 are all incorrect outputs.
3 related practice questions
Note references: CP-M, CP-E
- Prefix versus postfix
CP10
Boolean, bitwise and precedence rules
- Truth-value operations
- Relational and equality tests
- && conjunction, || disjunction
- ! negation
- C++ zero=false, nonzero=true
- Default bool output: 0/1
- boolalpha changes Boolean formatting
- a=3,b=5: (a==b) prints 0
👁 Full explanation
Relational and equality operators test values; && and || combine truth values; ! negates. In C++, zero converts to false and a nonzero number to true. Streams display bool as 0 or 1 unless boolalpha is set. With a=3,b=5, cout<<(a==b) prints 0. - Short circuit versus bitwise
- &: bits, no short circuit
- && right only after true left
- || right only after false left
- false && dangerousCall(): skipped
- x=1,y=0,z=4: (x&y)||++z
- Final z=5, Boolean result=1
- Grouping/postfix → unary → multiplicative
- Additive → shifts → relations → equality
- Bitwise & → ^ → |
- && → || → conditional
- Assignment → comma
👁 Full explanation
&& evaluates its right operand only if the left is true; || only if the left is false. Thus false && dangerousCall() skips the call. Bitwise & operates on bits and does not short circuit. With x=1,y=0,z=4, (x&y)||++z evaluates ++z, leaving z=5 and the Boolean result 1. The precedence ladder is grouping/postfix, unary, multiplicative, additive, shifts, relations, equality, bitwise &, ^, |, &&, ||, conditional, assignment, comma.
8 related practice questions
Note references: CP-M, CP-N
- Truth-value operations
CP11
Conditional and comma expressions
- Conditional and comma operators
- condition ? yes : no
- Condition then exactly one alternative
- Comma: left then right
- Comma result: right operand value
- Argument separators differ from comma operator
👁 Full explanation
condition ? yes : no evaluates the condition and exactly one alternative. The comma operator evaluates its left expression, then its right, and yields the right value. Do not confuse it with commas separating function arguments. - Conditional-comma trace
- a=6,b=8,x=2,y=4
- x>y false: (b--,y)
- Final b=7,c=4,a=6
- Unselected alternative unexecuted
- Internal semicolon: invalid syntax
- Comma restoration requires labeled interpretation
👁 Full explanation
For a=6,b=8,x=2,y=4, c=(x>y ? (a--,x) : (b--,y)) takes the false branch. b becomes 7, c receives 4 and a remains 6. Both alternatives are not executed. A semicolon in place of the internal comma is invalid syntax; a trace using a comma applies only after that syntax change.
2 related practice questions
Note references: CP-M, CP-N
- Conditional and comma operators
CP12
Decisions and flowcharts
[Exam Focus]- Decision grouping
- Independent consecutive if statements
- else: nearest unmatched if
- else-if: first true branch
- Nested S2: c1 && !c2
- Braces determine grouping
👁 Full explanation
A standalone if may execute independently of the following if. An else binds to its nearest unmatched if; an else-if ladder executes the first true branch only. In nested if(c1){if(c2) S1; else S2;}, S2 requires c1 true and c2 false. Braces determine grouping. - Decisions and flowchart evidence
- ph=15.3: warning plus Alkaline
- Separate range check and classification
- else/early return creates exclusivity
- Diamond: decision
- Rectangle: processing
- Parallelogram: input/output
- Terminator: start/end
- Pre-test: check before body
- Post-test: check after body
- Missing arrows/condition placement: indeterminate loop
👁 Full explanation
With ph=15.3, an invalid-range if can print its warning, and a separate classification ladder can also print Alkaline. They are not mutually exclusive unless linked by else or an early return. A flowchart decision is a diamond, processing a rectangle, input/output a parallelogram and start/end a terminator. A pre-test loop checks before its body; a post-test loop checks after. Identify a flowchart’s loop from its arrows and the placement of its conditions.
6 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N, CP-D
- Decision grouping
CP13
Switch and fall-through
- Traditional C++ switch
- Integral or enumeration selector
- case: constant expressions
- Matching label starts execution
- Fall-through until break/return/end
- default: unmatched value
- default needn't be last
👁 Full explanation
A traditional C++ switch selects using an integral or enumeration value. case labels are constant expressions. Execution starts at the matching label, then continues through subsequent statements until a break, return or the end. default handles an unmatched value but need not be the last physical label. - Switch fall-through trace
- Input 2: Bus.Truck.
- Case 2 enters, case 3 continues
- break: nearest switch or loop
- break doesn't terminate whole program
- case label: entry point
- No automatic branch isolation
👁 Full explanation
If case 2 prints Bus. and case 3 prints Truck. before the first break, input 2 prints Bus.Truck. A break exits the nearest switch or loop; it does not by itself terminate the entire program. A case label is an entry point, not an automatically isolated if branch.
2 related practice questions
Note references: CP-M, CP-N
- Traditional C++ switch
CP14
Loop mechanics
[Exam Focus]- Pre-test versus post-test loops
- while: condition before each body
- while: possibly zero executions
- do-while: body before condition
- do-while: at least once
- Repeat while condition true
- Menu/input attempt use case
👁 Full explanation
while(condition) checks before each body execution and may run zero times. do {body;} while(condition); runs the body once before checking; it repeats while the condition remains true. Use it when a menu or input attempt must occur at least once. - for execution order
- Initialization once
- Condition → body → update → condition
- for(;;): absent condition=true
- Known-count convenience, condition-control flexibility
- Indices 0..n-1: i=0,i<n,++i
- i=0,i<5,i+=2: 0 2 4
👁 Full explanation
for(initialization; condition; update) executes initialization once, then condition → body → update → condition. A missing condition in for(;;) acts as true. A for loop is convenient for a known count but can also be condition controlled. To print indices 0 through n-1, use i=0; i<n; ++i. Starting i=0 with i<5 and i+=2 prints 0 2 4.
11 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Pre-test versus post-test loops
CP15
Control transfers
- Control-transfer scope
- break: nearest loop or switch
- continue: skip current iteration remainder
- for continue → update
- while continue → condition
- return: leave current function
- Optional return result
- main return: normal program end
👁 Full explanation
break exits the nearest enclosing loop or switch. continue skips the rest of the current loop iteration: a for loop then runs its update; a while loop goes directly to its condition. return leaves the current function and may supply a result. In main it ends the program normally. - goto label tracing
- Transfers within same function
- Follow reached labels
- a → b → end
- Graduating fourth
- Year unreachable from entry a
- Structured alternatives ease reasoning
👁 Full explanation
A goto transfers to a label within its function; follow the label reached rather than reading lines in source order. In the sequence a: print Graduating; goto b; c: print Year; goto a; b: print fourth;, entry at a prints Graduating fourth and reaches the end. Year is not printed. Structured alternatives usually make such logic easier to reason about.
8 related practice questions
Note references: CP-M, CP-N
- Control-transfer scope
CP16
Iteration counts and nontermination
- Loop state tables
- Condition inputs, body output, updated values
- i=0,j=8: i<j, i++,j--
- Entries (0,8),(1,7),(2,6),(3,5)
- Odd-i continue: two prints
- Outer i=1,i<5,i+=5: once
- Inner j=10,j>i,--j: nine prints
👁 Full explanation
Make a table with condition inputs, body output and updated values. For i=0,j=8; i<j; i++,j--, body entries are (0,8),(1,7),(2,6),(3,5). If odd i triggers continue, printing occurs twice. With outer i=1; i<5; i+=5, the outer loop runs once; an inner j=10; j>i; --j prints nine times. - Progress and early exit
- n=1,n<=18,n+=2
- Break before multiples of seven
- Output: 1 3 5
- Fixed a=6>b=5: infinite while
- data[0]=5: %10 guard false
- Conditional-only increment: no progress
- No output, infinite loop
- <=10→<10 alone insufficient
👁 Full explanation
For n=1; n<=18; n+=2, print n unless n%7==0 then break: output is 1 3 5. A while(a>b) with fixed a=6,b=5 never changes its true condition. In data[10]={5,10,...,50}, i=0, advancing i only if data[i]%10==0 causes no progress because data[0]=5. It prints nothing and loops indefinitely; changing <=10 to <10 alone does not repair progress.
6 related practice questions
Note references: CP-M, CP-N
- Loop state tables
CP17
Functions and reusable modules
[Exam Focus]- Functions and call syntax
- Named task grouping
- int add(int a,int b){return a+b;}
- add(x,y): no call-site parameter types
- Parameters: definition names
- Arguments: supplied expressions/values
- void: no return value
- Side effects still possible
- return; permits early void exit
👁 Full explanation
A function groups a named task. C++ definition: int add(int a,int b){return a+b;}. Call it with add(x,y);, without parameter type declarations at the call site. Parameters are names in the definition; arguments are supplied expressions or values. A void function produces no return value but can have side effects and return; to exit early. - Reusable organization
- Method: class/object-associated function
- Methods can return values
- Modules: responsibilities behind interfaces
- Reuse reduces duplication
- Independent functions: understandable, testable
- Libraries: reusable components
- Frameworks: organizing structure
- Frameworks often invoke callbacks
👁 Full explanation
A method is a function associated with a class or object; methods can return values. Modules group related responsibilities behind interfaces. Reuse reduces duplication; independent functions are easier to understand and test. A library provides reusable components; a framework also supplies an organizing structure and often calls application callbacks.
11 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Functions and call syntax
CP18
Value, reference and pointer parameters
[Exam Focus]- Pass-by-value isolation
- Separate parameter object from argument
- func: a*=5,b+=5,return a+b
- func(9,3)=53
- Caller values remain 9,3
👁 Full explanation
A C++ value parameter is a separate object initialized from the argument. In func(int a,int b){a*=5;b+=5;return a+b;}, calling func(9,3) returns 53 and leaves the caller values 9 and 3 unchanged. - Aliasing and copied addresses
- int& aliases caller variable
- Reference swap changes originals
- int*: copied address
- *p=value mutates pointed object
- p=anotherAddress changes local pointer
- int a[] parameter adjusts to int*
- Element mutation possible
- Array length passed separately
- Java always passes by value
- Object reference copied, caller variable unaliased
👁 Full explanation
An int& parameter aliases the caller variable, so swap(int& a,int& b) changes both originals. An int* parameter copies an address; *p=value changes the pointed-to object, but p=anotherAddress only changes the local pointer. An array parameter int a[] is adjusted to int*: elements can change, and the length must be passed separately. Java always passes by value, including a copy of an object reference; it does not pass caller variables by reference.
2 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Pass-by-value isolation
CP19
Overloads, defaults and inline
- Overload resolution and defaults
- Same name, different parameter count/types/order
- Return type alone insufficient
- Argument types then required conversions
- No unique best match: ambiguity
- sum(x,y,z=0): two/three arguments
- Ordinary defaults occupy trailing positions
👁 Full explanation
Overloads share a name but differ in parameter count or types/order. Return type alone cannot distinguish them. Choose a candidate using argument types, then required conversions; report ambiguity if there is no unique best match. int sum(int x,int y,int z=0) allows two or three arguments; defaults occupy trailing positions in ordinary declarations. - inline meaning
- No compulsory call-site expansion
- Small frequent functions: optimization candidates
- Optimizer decides expansion
- Linkage/definition rules also matter
- Not simply a speed command
👁 Full explanation
inline does not compel the compiler to copy a function body at a call. Small frequently used functions may be good optimization candidates, but actual expansion is the optimizer’s decision. Inline also has language linkage/definition rules, so it is not simply a speed command.
2 related practice questions
Note references: CP-M, CP-N
- Overload resolution and defaults
CP20
Scope, lifetime and static locals
- Scope versus lifetime
- Scope: name usability
- Lifetime: object existence
- Local name: block restriction
- Inner names may shadow outer
- Global availability requires visible declaration
- ::name selects hidden global
👁 Full explanation
Scope is where a name can be used; lifetime is when its object exists. A local name is restricted to its block; an outer name may be shadowed. A namespace/global variable is available where its declaration is visible, not magically in every file. C++ ::name selects a global name hidden by a local one. - Automatic versus static local
- Automatic: fresh on entry
- Static: initialized once
- Static value persists, name stays local
- Even +1, odd +2, static x=0
- Five calls: 1,3,5,7,9
- Sum=25
- Namespace/static integers: zero-initialized
- Uninitialized local int: no assumed zero
👁 Full explanation
An automatic local is created anew on entry. A static local is initialized once and retains its value across calls even though its name remains local. If static x=0 changes by +1 when even and +2 otherwise, five calls return 1,3,5,7,9, whose sum is 25. Namespace/static storage integers are zero initialized; an ordinary uninitialized local int has no usable assumed zero value.
3 related practice questions
Note references: CP-M, CP-N
- Scope versus lifetime
CP21
Recursion and call tracing
[Exam Focus]- Recursive termination
- Direct or indirect self-call
- Base case plus progress
- Every supported input must reach base
- factorial(0)=1
- factorial(n)=n*factorial(n-1), n>0
- factorial(3)=3*2*1*1=6
- Negative inputs: reject/separately define
- n-1 doesn't reach zero from negative
👁 Full explanation
A recursive function calls itself directly or indirectly. It needs a base case and progress toward it for all supported inputs. factorial(0)=1 and factorial(n)=n*factorial(n-1) for positive n. factorial(3) expands to 3*2*1*1=6. Negative inputs require rejection or a separate definition; they do not reach zero under n-1. - Recursive call tracing
- Conditions before expansion
- if(n<m) return 0;
- f(1,4): immediate zero
- Unreachable recursion contributes nothing
- Record local parameters and pending operations
- Unwind return values
- Smaller instances commonly used
- Base branch alone doesn't prove reachability
👁 Full explanation
Evaluate conditions before expanding a recursive call. For if(n<m) return 0;, f(1,4) returns immediately; unreachable recursive branches add nothing. Record each call’s local parameters and pending operation, then unwind returned values. Recursion commonly uses smaller instances, but merely having a base-case branch does not prove it will be reached.
4 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Recursive termination
CP22
Arrays and bounds
- Built-in array model
- Fixed count, same type
- Contiguous storage
- int a[4]={10,20,30,40};
- Valid indices: 0..3
- a[4]: undefined C++ access
- No predicted nearby-memory output
- Java: ArrayIndexOutOfBoundsException
👁 Full explanation
A built-in C++ array has a fixed number of same-type elements in contiguous storage: int a[4]={10,20,30,40};. Valid indices are 0 through 3. a[4] is outside the array; accessing it has undefined behavior. Java checks bounds and throws ArrayIndexOutOfBoundsException. Do not predict a C++ out-of-range value from nearby memory. - Array declarations and initialization
- Standard bound: compile-time constant
- Variable-length locals: compiler extension
- int a[5]={1,2,3}: remaining zeros
- Uninitialized automatic int array differs
- a[i] ≡ *(a+i)
- Brackets not required for element access
👁 Full explanation
A standard built-in array bound must be a compile-time constant; variable-length local arrays are compiler extensions. int a[5]={1,2,3}; fills the remaining elements with zeros. An uninitialized automatic array of int is different. a[i] equals *(a+i), so elements can be accessed using pointer notation without explicitly writing brackets.
3 related practice questions
Note references: CP-M, CP-N
- Built-in array model
CP23
Array algorithms and matrix indexing
[Exam Focus]- Array traversal algorithms
- Sum: total=0, add each once
- Maximum/minimum: initialize from a[0]
- First verify nonempty array
- Fifty inputs: count-controlled loop
- Positive-only sum: if(x>0) total+=x
- Skip nonpositive: continue for x<=0
- Counting versus filtering responsibilities
👁 Full explanation
For a sum, start total=0 and add each element once. For a maximum/minimum, initialize from a[0] only after confirming the array is nonempty. For 50 inputs where nonpositive values are skipped, use a count-controlled loop and either if(x>0) total+=x; or continue for x<=0. These constructs solve different parts of the task. - Two-dimensional indexing
- int a[R][C]: R rows, C elements
- Zero-based row then column
- Row-major offset: r*C+c
- Bank 4×4: a[1][1]=6
- a[2][3]=6, a[3][3]=2
- Java length belongs to each array
- arr.length-2 endpoint: incomplete traversal
👁 Full explanation
int a[R][C] has R rows, each with C elements. a[r][c] uses zero-based row then column. Its element offset is r*C+c in row-major storage. In the 4x4 matrix example, a[1][1]=6, a[2][3]=6 and a[3][3]=2. In Java, length belongs to each array; a traversal ending at arr.length-2 visits fewer elements than a full traversal.
2 related practice questions
Blueprint: CP1, CP2 · Note references: CP-M, CP-N
- Array traversal algorithms
CP24
C strings and std::string
- C-string termination and storage
- Character array ending '\0'
- "Hello": six char positions
- strlen: five visible characters
- Terminator excluded from strlen
- sizeof fixed array: allocated bytes
- Capacity may exceed strlen+1
- cout<<a: terminated sequence, not address
👁 Full explanation
A C string is a character array ending in '\0'. "Hello" needs six char positions; strlen counts five visible characters and excludes the terminator. sizeof a fixed char array reports its allocated bytes, which can exceed strlen+1. cout<<a prints a terminated char sequence, not its numeric address. - Text APIs and capacity
- <cstring>: strcpy(destination,source)
- strcat(destination,source), strlen, strcmp
- Sufficient destination capacity
- strcmp equality: zero
- Otherwise sign, not necessarily ±1
- <string>: owning resizable std::string
- +: concatenation, ==: content
- size()/length(): stored-character count
- substr(start,count): segment
- No std::string toUpperCase()/trim() members
👁 Full explanation
<cstring> supplies strcpy(destination,source), strcat(destination,source), strlen and strcmp. Supply enough destination capacity; strcmp returns zero for equal content, otherwise a sign, not necessarily exactly -1 or 1. C++ std::string in <string> owns resizable text; + concatenates, == compares content, size()/length() counts stored characters and substr(start,count) extracts a segment. Standard std::string has no Java-style toUpperCase() or trim() member.
1 related practice question
Note references: CP-M, CP-N
- C-string termination and storage
CP25
Pointers and dereferencing
- Pointer identity versus pointed value
- int x=10, int* p=&x
- *p: read/write x
- &p: pointer variable's address
- p=&a,q=&b: p=q redirects
- No change to a or b
- *p=*q: pointed-value copy
- Uninitialized/null/dangling dereference forbidden
👁 Full explanation
int x=10; int* p=&x; stores x’s address in p. *p reads or writes x; &p is the address of the pointer variable itself. With p=&a,q=&b, p=q redirects p to b and leaves a and b unchanged. By contrast *p=*q copies the pointed-to value. Never dereference an uninitialized, null or dangling pointer. - Arrays and pointer levels
- Common array-to-first-element pointer conversion
- Array isn't assignable pointer variable
- int** pp=&p
- **pp reaches x
- void*: holds object address
- Convert appropriately before C++ dereference
👁 Full explanation
An array expression commonly converts to a pointer to its first element, but the array is not itself an assignable pointer variable. A pointer-to-pointer int** pp=&p allows **pp to reach x. A void* can hold an object address but requires conversion to a suitable object pointer before dereferencing in C++.
2 related practice questions
Note references: CP-M, CP-N
- Pointer identity versus pointed value
CP26
Pointer arithmetic and allocation
- Scaled pointer arithmetic
- p+k: k elements
- k*sizeof(*p) byte displacement
- Assume sizeof(float)==4
- Address 7000: p+3 → 7012
- cout<<p++: old address, advance
- cout<<*p++: old element, advance
- ++*p: change element
- p+q: invalid
- Same-array subtraction: element distance
👁 Full explanation
If p points inside an array, p+k advances k elements, or k*sizeof(*p) bytes. Under the explicit assumption sizeof(float)==4 and first address 7000, p+3 has numeric address 7012. cout<<p++ displays the old address then advances p; cout<<*p++ displays the old element then advances p. ++*p changes the element. Pointer addition p+q is invalid; subtracting pointers within the same array gives an element distance. - Allocation and pointer boundaries
- Within-array or one-past arithmetic
- One-past dereference forbidden
- new T ↔ delete
- new T[n] ↔ delete[]
- Prefer resource-owning standard containers
- Primitive initialization must be requested
👁 Full explanation
Arithmetic must stay within an array or its one-past position; one-past may not be dereferenced. C++ new T creates a dynamic object, delete releases it; new T[n] pairs with delete[]. Prefer resource-owning standard containers in real programs. Allocation does not automatically initialize every primitive value unless initialization is requested.
1 related practice question
Note references: CP-M, CP-N
- Scaled pointer arithmetic
CP27
Structures and member access
- Structures and member access
- Named members, possibly differing types
- House definition: price and rooms
- House h{150000,3}: object creation
- h.rooms: dot access
- p->rooms ≡ (*p).rooms
- Pointer must reference live object
- Type definition alone creates no instance
👁 Full explanation
A struct groups named members, possibly of different types. struct House{double price; int rooms;}; defines a type; House h{150000,3}; creates an object. h.rooms uses a dot. House* p=&h; p->rooms is equivalent to (*p).rooms. The pointer must refer to a live object before member access. A type definition alone does not create an ordinary instance. - Aggregate and recursive structure rules
- Initialization in declaration order
- Default member initializer: int rooms=3
- C++11 list initialization rejects narrowing
- Exactly representable floating constant exception
- 25.00→float not necessarily narrowing
- 25.0f clarity, language-version check
- Structures copied, passed, returned
- No full self-instance member
- Self-type pointer allowed
👁 Full explanation
Aggregate initialization assigns members in declaration order. Modern C++ permits default member initializers such as int rooms=3;. C++11 list initialization rejects narrowing; a constant floating value exactly representable in the target floating type can be permitted, so 25.00 to float is not necessarily narrowing. Use 25.0f for clarity and check the language version. Structures can be copied, passed and returned; a structure cannot contain a full instance of itself, but may contain a pointer to its own type.
4 related practice questions
Note references: CP-M, CP-N
- Structures and member access
CP28
Console streams and input state
- Console streams and spelling
- <iostream>, std::cin/std::cout
- Explicit qualification or introduced names
- cout <<: output insertion
- cin >>: formatted input extraction
- std::endl: newline plus flush
- Cout, Int: incorrect case
- std: :cout: invalid printed spelling
👁 Full explanation
Include <iostream> and qualify std::cin/std::cout or introduce the names explicitly. cout is the standard output stream; << inserts values. cin is standard input; >> extracts formatted values. std::endl inserts a newline and flushes. C++ names are case sensitive: Cout, Int and std: :cout are not equivalent valid spellings of cout, int and std::cout. - Input state and output formatting
- getline(cin,text): full line
- Numeric extraction leaves pending newline
- Consume newline before line read
- Check input failure before value use
- Exact double 4 may print 4
- Text, spaces, newlines affect traces
👁 Full explanation
Read a full line with getline(cin,text). After formatted numeric extraction, consume the pending newline before a line read when required. Input failure must be tested before trusting a value. Console output formatting matters: by default a double storing an exact 4 may print 4 rather than 4.0. Text, spaces and newlines are part of an output trace.
4 related practice questions
Note references: CP-M, CP-N
- Console streams and spelling
CP29
File streams and safe reading
- File stream types and modes
- <fstream>: file-stream header
- ofstream writes, ifstream reads
- fstream: both directions
- Default ofstream argument: ios::out
- Ordinary effect: create/truncate
- Signature versus effective out|trunc
- ios::app: every write at end
- ios::ate: initial seek to end
- ios::binary: binary mode
👁 Full explanation
Include <fstream>. ofstream writes, ifstream reads, and fstream can do both. The constructor’s default ofstream mode argument is ios::out; its ordinary effect is to create/truncate the file. Distinguish the default mode argument from effective out|trunc behavior. ios::app places each write at the end; ios::ate initially seeks to the end; ios::binary requests binary mode. - Safe file-reading lifecycle
- if(!file): opening failure
- while(file>>record)
- while(getline(file,line))
- EOF discovered by attempted read
- while(!file.eof()): possible invalid extra record
- Close or rely on destruction
- ofstream class versus <fstream> header
👁 Full explanation
Check if(!file) after opening. Read using while(file>>record) or while(getline(file,line)), because end-of-file is discovered by an attempted read. while(!file.eof()) can process an invalid extra record. Close or rely on stream destruction to release the resource. “ofstream” is a class, whereas <fstream> is the header.
2 related practice questions
Note references: CP-M, CP-F
- File stream types and modes
CP30
Math functions and iterative powers
[Exam Focus]- Mathematical functions
- <cmath>: sqrt, pow, floor, ceil
- <cstdlib>: integer abs also
- sqrt(16)=4, pow(3,4)=81, abs(-7)=7
- ceil(x): least integer-valued result ≥x
- floor(x): greatest integer-valued result ≤x
- ceil(-2.7)=-2, floor(-2.7)=-3
- Negative truncation differs from floor
👁 Full explanation
Use <cmath> for sqrt, pow, floor and ceil; integer abs is also provided by <cstdlib>. sqrt(16)=4; pow(3,4)=81; abs(-7)=7. ceil(x) is the least integer-valued result >=x; floor(x) the greatest <=x. Thus ceil(-2.7)=-2 and floor(-2.7)=-3; truncation toward zero differs from floor for negatives. - Iterative exponentiation
- No built-in C++ exponentiation operator
- ^: bitwise XOR
- **: not power operator
- Nonnegative integer e: r=1
- Repeat r*=b exactly e times
- 4^3 → 64
- Powers/factorials: fixed-width overflow risk
- Specify valid input range
👁 Full explanation
C++ has no built-in exponentiation operator: ^ is bitwise XOR and ** is not a power operator. To compute b^e for a nonnegative integer e, start r=1 and repeat r*=b exactly e times; b=4,e=3 gives 64. Large powers and factorials can overflow fixed-width types; specify a valid input range.
11 related practice questions
Blueprint: CP2, CP3 · Note references: CP-M, CP-N
- Mathematical functions
CP31
Proofs and loop invariants
[Exam Focus]- Proof methods
- Direct P⇒Q: assume P, derive Q
- Contrapositive: ¬Q⇒¬P
- Contradiction: false claim assumption → impossibility
- Counterexample refutes universal claim
- Induction: base case
- P(k) assumption → P(k+1)
👁 Full explanation
To prove an implication P⇒Q, a direct proof derives Q assuming P; a contrapositive proves not Q⇒not P; a contradiction assumes the claim false and derives an impossibility. A single counterexample disproves a universal claim. Induction proves a base case and proves P(k+1) assuming P(k). - Loop-invariant summation proof
- Initial sum=0,i=1
- Guard: i<=n
- Invariant: sum=(i-1)*i/2
- Initialization establishes invariant
- Add i → i*(i+1)/2
- Increment i restores invariant
- Exit: i=n+1
- Result: sum=n*(n+1)/2
- Termination measure: n-i+1
- Nonnegative, decreasing while guard holds
- Assumptions: n>=0, no overflow
👁 Full explanation
For sum=0,i=1; while(i<=n){sum+=i;++i;}, use invariant sum=(i-1)*i/2. It holds initially. Adding i gives i*(i+1)/2, then incrementing i restores the invariant. Exit gives i=n+1 and sum=n*(n+1)/2. Termination needs a separate decreasing nonnegative measure n-i+1 while the guard holds. Assume n>=0 and no arithmetic overflow. This connects mathematical proof to actual code.
Blueprint: CP3 · Note references: CP-P, CP-M
- Proof methods
CP32
Debugging, exceptions and maintenance
[Exam Focus]- Error categories and debugging
- Syntax: grammar violation
- Type: semantic rejection despite valid syntax
- Runtime: during execution
- Logic: wrong behavior
- Bug: defect
- Debugging: locate and correct
- First useful diagnostic, nearby tokens/declarations
- Repair and rebuild
- Debugger requires runnable program
👁 Full explanation
A syntax error violates grammar; a type error can be syntactically well formed but rejected during semantic checking. A runtime error occurs during execution; a logic error gives the wrong behavior. A bug is a defect; debugging locates and corrects it. Read the first useful compiler diagnostic, inspect nearby tokens and declarations, repair and rebuild; a debugger is useful after a runnable program exists. - Testing and maintenance tools
- Ordinary, boundary, invalid inputs
- First actual/expected state divergence
- Exceptions: matching-handler control transfer
- No arbitrary undefined-behavior recovery
- Refactoring: structure improved, behavior preserved
- Version control: records, comparisons, rollback
- Documentation: use, design, maintenance assumptions
👁 Full explanation
Test ordinary, boundary and invalid inputs and trace the first point where actual state differs from expected state. Exceptions transfer control to a matching handler for exceptional conditions; they do not make arbitrary undefined behavior recoverable. Refactoring improves internal structure while preserving observable behavior. Version control records changes, supports comparison and rollback; documentation explains use, design and maintenance assumptions.
10 related practice questions
Blueprint: CP2 · Note references: CP-M, CP-N
- Error categories and debugging
CP33
Static typing and Java distinctions
- Static versus dynamic typing
- Static: types checked before execution
- C++ auto: inferred static type
- Dynamic: operations checked using runtime values
- No mandatory explicit static declarations
- Static typing allows type inference
👁 Full explanation
Static typing checks types before execution; type inference can still infer a static type, as with C++ auto. Dynamic typing checks operations using runtime values; it does not mean variables must have explicit static declarations. Static typing does not always require explicit type annotations. - Java versus C++ APIs
- Java boolean, fixed-width numeric primitives
- Object references
- Java String: immutable
- substring(begin,end): exclusive end
- equals: content, ==: references
- Java arrays: length field
- Scanner nextInt() → pending nextLine() newline
- C++ std::string: mutable
- substr(start,count): different API
👁 Full explanation
Java uses boolean, fixed-width numeric primitive types and references to objects. Java String is immutable, substring(begin,end) uses an exclusive end, equals compares content and == compares references. Java arrays have a length field. Scanner nextInt() can leave a newline for nextLine(). C++ std::string is mutable and uses substr(start,count); the two APIs must not be merged.
1 related practice question
Note references: CP-M, CP-N
- Static versus dynamic typing
CP34
Malformed-code interpretation
- Evidence before output prediction
- Complete code required
- Diagram edges, conditions, labels required
- Post-test loop
- Entry body before decision
- Branch returns to body
- Post-test do-while: answer B
- Literal invalid versus labeled intended trace
- Documented OCR correction only
👁 Full explanation
A program trace requires the complete code, and a diagram question requires its edges, conditions and labels. When entry reaches the body rectangle before the decision diamond and a decision branch returns to the body, the body executes before the condition is tested. This is a post-test do-while loop. Check that a program is valid before tracing it; state any syntax changes before analyzing the resulting program. - Malformed-code reference cases
- Pointer members: p->m, (*p).m
- Cout/Cin ≠ cout/cin
- C1 ≠ c1, car_mode ≠ car_model
- goto skips unreached output statements
- Assignment trace: z=5, a=1
- Intended z=5 then a=1
- Case matters: Z ≠ z
- Negative-value test: x < 0
- C++ entry point: int main()
- C++ spelling: int and cout
- Quotes and comma punctuation repair
- No invented unique literal output
👁 Full explanation
Match pointer-member names exactly: Cout/Cin, C1 and car_mode do not match cout/cin, c1 and car_model. In the goto sequence above, Year is not printed because control does not reach its label. With valid C++ syntax for the stated assignments, the trace yields z=5 then a=1. Printing Z when only z is declared refers to a different, undeclared identifier. Use <0 for a less-than-zero comparison and the standard int main() declaration for a C++ entry point. Check int and cout case, quotation marks and comma-expression punctuation before tracing a C++ expression. Predict output only after the program and its execution conditions are clear.
14 related practice questions
Note references: CP-M, CP-N
- Evidence before output prediction
CP35
Interpret programming questions precisely
- Ambiguous question options
- Linking versus loading
- Machine instructions versus executable files
- Data members and initialization
- Equivalent short declarations
- Language version and narrowing conversions
- Equivalent pointer-member expressions
👁 Full explanation
Evaluate every choice against the language rules; more than one statement may be valid, or none may be valid. Distinguish linking from loading. Distinguish binary representation, machine code and executable files. Assess class membership and possible initialization separately; both statements can be correct. Check whether alternative short declarations are equivalent. Check the C++ version and narrowing rules before evaluating an initialization. Array subscripting and equivalent pointer access can refer to the same element. - Incorrect-key and wording traps
- Static typing versus explicit annotations
- Scalar declaration: int x;
- Void function definitions
- int myFunction(){}: may compile
- Reaching int function end: undefined behavior
- break exits the innermost loop
- Const spelling and required initialization
- SS167: counting versus skipping
- Loop exit versus iteration skip
- Inspect, rebuild, and retest
- Rebuild and retest complete repair
👁 Full explanation
Use the definition of static typing rather than equating it with explicit annotations. An ordinary integer declaration can be written int x;. A void function definition can be complete without returning a value; int myFunction(){} can compile, but reaching its end is undefined behavior. A break statement exits the enclosing loop or switch. Check required initialization when evaluating const declarations, including alternative const spellings. Distinguish counting iterations from skipping inputs, and terminating a loop from ending only the current iteration. After inspecting and changing code, rebuild and retest to complete debugging.
27 related practice questions
Note references: CP-M, CP-N
- Ambiguous question options
No matching topics. Clear the search or change the filter.
Blueprint learning outcomes
- CP1 · Understanding the principles of computer programming
CP01, CP02, CP04, CP06, CP12, CP14, CP17, CP18, CP21, CP23 - CP2 · Design, code, debug and solve problems in using programming concepts
CP01, CP12, CP14, CP17, CP18, CP21, CP23, CP30, CP32 - CP3 · Apply the principle of mathematical knowledge to prove statements and solve problems in computing science
CP30, CP31