optional · CSS study notes
II.1 Basic Programming Elements and Concepts
⬆️ P-I.II. Programming Fundamentals · Question Bank · Chapter II (2016–2026)
🧠
Remember: Token → expression → statement → program.
Start here — what you should be able to do
- Name the tokens in
int total = price * quantity;. - Predict the effect of integer division, precedence and increment operators.
- Explain the difference between a syntax error and a wrong algorithm.
Reading order: foundation checks → full notes and examples → exam traps → self-test without notes → past-paper answers. All sections below remain part of the topic; code examples are kept in full.
Foundation checks
Operator essentials
| Family | Examples | Remember |
|---|---|---|
| Arithmetic | • - * / % | Integer division discards the fractional part; % is integer remainder. |
| Comparison | == != < <= > >= | A test produces a Boolean result. |
| Logical | &&, ` | |
| Assignment | = += -= | Assignment changes a value; equality tests it. |
| Increment | ++x, x++ | Prefix updates before yielding the value; postfix yields the old value. |
- Precedence: multiplication/division bind before addition/subtraction; parentheses make intent explicit.
- Trace safely: use separate statements; do not infer an evaluation order merely from associativity.
- Literal versus named constant:
10is a literal;const int limit = 10;introduces a named constant.
1. Core Concepts
- Algorithm: a finite, ordered sequence of unambiguous steps to solve a problem. Must be finite, definite, effective, and produce output from given input.
- Program: an algorithm expressed in a programming language that a computer can execute
- Syntax: the grammatical rules of a language; a syntax error breaks compilation
- Semantics: the meaning of a valid statement; a logic error compiles fine but produces wrong results
- Keyword/Reserved word: words with predefined meaning in a language (e.g.
if,while,return) that can't be used as identifiers - Identifier: a programmer-chosen name for a variable, function, or other entity — must start with a letter/underscore, no spaces, case-sensitive, cannot match a keyword
- Literal/Constant: a fixed value written directly in code (e.g.
10,3.14,'A',"hello") — never changes during execution - Operator: a symbol that performs an operation on operand(s) — arithmetic (
+ - * / %), relational (== != < >), logical (&& || !), assignment (= += -=), bitwise (& | ^ ~ << >>) - Operand: the value(s) an operator acts upon
- Expression: a combination of operands and operators that evaluates to a single value (e.g.
a + b * 2) - Statement: a complete instruction, terminated appropriately (e.g.
;in C/C++). Building block of a program — one or more statements form a function body. - Token: the smallest individual unit of a program recognized by the compiler — keywords, identifiers, literals, operators, and punctuators are all tokens
- Comment: non-executable text for human readers, ignored by the compiler/interpreter (
//single-line,/* */multi-line in C/C++)
2. The 5 Fundamental Elements of a Program
A useful introductory model groups common program operations into five elements. Each one also has a standard flowchart shape and a typical pseudocode form, so you can move between "what it does," "how it's drawn," and "how it's written" for each:
| # | Element | What It Does | Flowchart Shape | Pseudocode Form |
|---|---|---|---|---|
| 1 | Input | Brings data into the program from the user/file/device | Parallelogram | READ x / INPUT x |
| 2 | Output | Sends a result out to the user/file/device | Parallelogram | WRITE result / PRINT result |
| 3 | Operation (Processing) | Performs a computation, assignment, or data transformation | Rectangle | total = price * qty |
| 4 | Condition (Selection) | Branches the flow based on a true/false test | Diamond | IF x > 0 THEN ... ELSE ... ENDIF |
| 5 | Looping (Iteration) | Repeats a block of steps while/until a condition holds | Diamond, with a backward arrow looping to an earlier step | WHILE x < 10 DO ... ENDWHILE |
- Input and Output share the same shape (parallelogram) — the direction of data is shown by the flow/arrow and wording, not a different symbol
- Looping has no shape of its own — it reuses the diamond (decision) for the repeat-test, plus an arrow that loops back to an earlier step instead of moving forward
- The oval (Start/End) and plain arrows (flow direction) are structural shapes that frame these 5 "doing" elements but aren't one of them
3. Combined Example: Input → Operation → Condition → Looping → Output
Problem: read numbers one at a time and add them up, stopping as soon as the user enters 0; then print the total.
Pseudocode:
BEGIN
sum = 0 // Operation (initialize)
READ x // Input
WHILE x != 0 DO // Looping (repeat) + Condition (the test itself)
sum = sum + x // Operation
READ x // Input (get the next value)
ENDWHILE
WRITE sum // Output
END
Flowchart (textual):
Start (oval) → Input x (parallelogram) → Decision: x != 0? (diamond) → Yes → sum = sum + x (rectangle) → Input x (parallelogram) → loop back to the Decision → No → Output sum (parallelogram) → End (oval)
This one example uses all 5 elements: two Inputs, two Operations, one Condition (the loop test), the Looping behavior (the arrow back to the diamond), and one Output.
4. Worked Example
Consider the statement: int total = price * quantity;
- Tokens:
int,total,=,price,*,quantity,; intis a keyword;total,price,quantityare identifiers*and=are operators;price * quantityis an expression- The whole line is a statement (a declaration + assignment combined)
- If
quantitywere misspelled asquntitywhere declared elsewhere, that's a syntax/naming error; if*were mistakenly typed as+, the code still compiles but gives the wrong total — a logic (semantic) error
5. 💻 Code Examples: C & C++
The same "5 elements" (input, output, operation, condition, looping) and vocabulary (keyword, identifier, literal, operator, expression, statement, token) shown side by side:
C:
#include <stdio.h>
int main(void) {
int total; // declaration (keyword: int, identifier: total)
int price = 50, quantity = 3; // literals: 50, 3
total = price * quantity; // expression + assignment statement
printf("Total = %d\n", total); // statement (function call) -- Output
return 0; // keyword: return
}
C++:
#include <iostream>
using namespace std;
int main() {
int total; // declaration
int price = 50, quantity = 3; // literals
total = price * quantity; // expression + assignment statement
cout << "Total = " << total << endl; // statement -- Output
return 0;
}
- Both programs use all the vocabulary from the Worked Example above:
int/identifiers/literals/operators/expression/statement/tokens — C++ simply swapsprintf/scanfforcout/cin
6. MCQ Traps
- A syntax error is caught at compile time; a logic error is not — the program runs but gives wrong output
- A keyword cannot be reused as a variable name; an identifier is user-defined
- Algorithm is language-independent; a program is a specific implementation in one language
- A literal is a fixed value in the source code itself; a variable is a named storage location whose value can change
- Every keyword is a token, but not every token is a keyword — tokens is the broader category (keywords, identifiers, literals, operators, punctuators)
7. ✅ Self-Test Questions (with Answers)
Q1. Give an example each of a syntax error and a logic error in a simple program.
Answer
- Syntax error: breaks grammar, such as a missing semicolon; diagnosed during translation.
- Logic error: legal code implements the wrong rule, such as addition instead of multiplication.
- Finding logic errors: compare a dry run with known expected results; testing and analysis can reveal them.
- Exam example:
if (a = 5)is legal assignment but is usually wrong when an equality test was intended.
// SYNTAX ERROR -- missing semicolon; will not compile
int a = 5
cout << a;
// LOGIC ERROR -- compiles and runs, but the answer is wrong
int length = 5, width = 3;
int area = length + width; // should be length * width
cout << area; // prints 8, but the correct area is 15
| Aspect | Syntax Error | Logic Error |
|---|---|---|
| Detected by | Compiler, at compile time | Nobody automatically; by testing/tracing |
| Does it run? | No executable is produced | Yes, runs normally |
| Output | None | Wrong output |
| Typical cause | Missing ; , misspelt keyword, unbalanced braces | Wrong operator, wrong formula, wrong condition |
- MCQ trap: writing
if (a = 5)instead ofif (a == 5)is a logic error, not a syntax error —=is a legal assignment that yields 5, which is non-zero and therefore always true. - A separate category is failure during execution.
- Invalid operations such as out-of-bounds access can have undefined behaviour; a crash is not guaranteed.
Q2. Why is an algorithm considered language-independent?
Answer — key points
- An algorithm is a finite, ordered sequence of unambiguous steps that solves a problem — it specifies the logic of what must be done and in what order, not how a particular compiler is to be instructed.
- It is expressed in ordinary English, pseudocode or a flowchart, none of which have compiler-enforced syntax, so the same algorithm can be implemented in C, C++, Java, Python or even carried out by hand with pencil and paper and still produce identical results.
- A program, by contrast, is one concrete implementation of an algorithm, bound to the keywords, data types, libraries and syntax rules of a single language — change the language and the program must be rewritten, while the algorithm stays untouched.
// ALGORITHM: read two numbers, output the larger.
// C++ implementation of that language-independent logic:
int a, b;
cin >> a >> b;
cout << ((a > b) ? a : b);
// In C the same algorithm becomes scanf/printf;
// in Python, input()/print() -- the LOGIC is unchanged.
- Algorithm → design stage, abstract, notation-free, judged on correctness and efficiency
- Program → implementation stage, concrete, syntax-bound, judged additionally on compilability
MCQ trap: an algorithm must satisfy finiteness — a set of steps that never terminates (an infinite loop with no exit) is not a valid algorithm, no matter how clearly it is written.
Q3. List the five fundamental elements of any program, and name the flowchart shape used for each.
Answer — key points
- Regardless of the language, every program is assembled from five fundamental elements.
- These are the "doing" elements
- the oval (terminator) for Start/End and plain arrows for flow direction merely frame them and are not counted among the five.
| # | Element | Function | Flowchart Shape |
|---|---|---|---|
| 1 | Input | Brings data into the program | Parallelogram |
| 2 | Output | Sends results out to user/file/device | Parallelogram |
| 3 | Operation (Processing) | Computation, assignment, transformation | Rectangle |
| 4 | Condition (Selection) | Branches the flow on a true/false test | Diamond |
| 5 | Looping (Iteration) | Repeats a block while a condition holds | Diamond, plus a backward arrow |
#include <iostream>
using namespace std;
int main() {
int n, sum = 0; // 3. OPERATION (initialise)
cin >> n; // 1. INPUT
for (int i = 1; i <= n; i++) // 5. LOOPING (+ 4. CONDITION i <= n)
sum += i; // 3. OPERATION
if (sum > 100) // 4. CONDITION
cout << "Large\n"; // 2. OUTPUT
cout << "Sum = " << sum; // 2. OUTPUT
return 0;
}
// Input 5 -> Sum = 15
MCQ trap: Input and Output share the same parallelogram — the direction of data is shown by the arrow and the wording, not by a different symbol. Likewise looping has no symbol of its own; it reuses the decision diamond.
Q4. Why do condition and looping share the same flowchart shape (the diamond)?
Answer — key points
- Because a loop is simply a decision that is re-entered.
- At the heart of every loop lies a single true/false test — "should the body run again?" — and that test is logically identical to the test inside an
ifstatement, so it is drawn with the same diamond (rhombus) symbol. - What distinguishes iteration from selection is not the shape but the flow of the arrows: in a selection both branches move forward and eventually rejoin, whereas in a looping construct one branch arrow loops backward to an earlier point in the chart, creating a cycle.
- Standard flowcharting (ANSI/ISO 5807) therefore defines no separate "loop" symbol — repetition is expressed as decision + backward arrow.
| Aspect | Condition (Selection) | Looping (Iteration) |
|---|---|---|
| Symbol used | Diamond | Diamond |
| Direction of flow | Both branches go forward and rejoin | One branch goes BACKWARD to an earlier step |
| Times body runs | At most once | Zero, one or many times |
| C++ construct | if / if-else / switch | while / for / do-while |
if (x > 0) cout << x; // decision: forward only, runs at most once
while (x > 0) { cout << x; x--; } // SAME test, but control returns to it each pass
- MCQ trap: the diamond is reserved for decisions only — it is never used for input/output (parallelogram) or processing (rectangle).
- Note also that a pre-test loop (
while,for) places the diamond before the body, while a post-test loop (do-while) places it after, which is whydo-whilealways executes at least once.
Q5. What is a token, and name the five categories of tokens in a typical high-level language.
Answer — key points
- A token is the smallest individual unit of a program that is meaningful to the compiler — the atomic element produced when the lexical analyser (the first phase of compilation) scans the source text and strips out whitespace and comments.
- Everything a compiler sees is ultimately a stream of tokens
- if a sequence of characters cannot be recognised as a valid token, the compiler reports a lexical/syntax error.
- The five standard categories are:
- Keywords — reserved words with a fixed meaning:
int,if,while,return,void - Identifiers — user-defined names:
total,main,studentAge - Constants / Literals — fixed values:
10,3.14,'A',"hello" - Operators — symbols that perform operations:
+,-,*,=,==,&& - Punctuators / Special symbols (separators) —
;,( ){ }[ ]#
int total = price * 5;
// Tokens: int | total | = | price | * | 5 | ; -> 7 tokens
// int = keyword, total & price = identifiers,
// = and * = operators, 5 = literal, ; = punctuator
- Lexical detail: comments/whitespace generally carry no runtime operation, but can separate tokens; removing them carelessly can change tokenisation.
Q6. Differentiate between a literal and an identifier with one example each.
Answer
- Literal: a value written directly in source, such as
42,3.14,'A'or"hello". - Identifier: a name for a variable, constant, function or another entity.
- Named constant:
const int limit = 42;uses an identifier and a literal together. - Basic identifier rule: letters/underscore followed by letters, digits or underscores; no spaces or keywords. Avoid implementation-reserved names.
- Remember: a literal is not a variable, but its representation can still occupy storage, especially a string literal.
int marks = 95; // marks -> IDENTIFIER, 95 -> integer literal
double pi = 3.14159; // pi -> identifier, 3.14159 -> floating literal
char grade = 'A'; // grade -> identifier, 'A' -> character literal
// 3.14159 = pi; // ERROR: a literal can never be assigned to
- Valid identifiers:
total,_count,studentMarks2,MAX_SIZE - Invalid identifiers:
2marks(starts with a digit),total marks(space),int(keyword),roll-no(hyphen is an operator)
MCQ trap: Total and total are distinct identifiers. "A" includes a terminating null character; 'A' is a character literal. The literal's type differs between C and C++, so do not assign a universal one-byte size to every character literal.
8. 📜 Past-Paper Questions & MCQs (CSS 2016–2026)
2018 · Paper-I · Q3(c) · 1 mark
Recall cue: Expand compound assignment while preserving the original right-hand expression.
Q. Write an equivalent instruction to w += 2*z + 4; without the += operator.
Answer — key points
w = w + 2 * z + 4;
2018 · Paper-I · Q3(d) · 2 marks
Recall cue: Post-increment uses the old value; pre-decrement changes the value first; trace each statement.
Q. Predict the values of a and b after every instruction: a=5, b=6; a=(b++)+3; b=--a;
Answer — key points
a = (b++) + 3:b(6) is used first, so a = 9, thenbbecomes 7. → a = 9, b = 7.b = --a:ais decremented first to 8, then assigned. → a = 8, b = 8.
2024 · Paper-I · Q4(b) · 6 marks
Recall cue: Use floating-point 9.0/5.0; substitute Celsius; add 32; check a known conversion.
Q. Read a Celsius degree and display the Fahrenheit value using F = (9/5) × C + 32.
Answer — key points
float c; cin >> c;
cout << "Fahrenheit = " << (9.0 / 5) * c + 32;
- Use
9.0 / 5. In C/C++ the integer expression9 / 5equals 1 and gives a wrong answer.
2025 · Paper-I · Q4(b) · 6 marks
Recall cue: Initialise the result matrix; use row, column and inner-product loops; print all four results.
Q. Write a C++ program to calculate and display the product of two 2 × 2 matrices.
Answer — key points
int A[2][2], B[2][2], C[2][2] = {{0,0},{0,0}};
for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) cin >> A[i][j];
for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) cin >> B[i][j];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
C[i][j] += A[i][k] * B[k][j];
for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) cout << C[i][j] << " "; cout << endl; }
Recall check and coverage
- Explain the three learning outcomes at the top without looking.
- Reproduce one example or trace and test a boundary case.
- Answer each self-test, then compare with the key.
- Attempt each recorded past-paper task on this page.
Recorded written references: 2018 · Paper-I · Q3(c) · 1 mark; 2018 · Paper-I · Q3(d) · 2 marks; 2024 · Paper-I · Q4(b) · 6 marks; 2025 · Paper-I · Q4(b) · 6 marks
Evidence limit: this page preserves the question records found in your Notion notes. Disputed labels and questions not checked against original PDFs remain flagged in the Question Bank; this is not a claim of exhaustive original-paper verification.