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 type | What it is |
| Keywords | Reserved words with a fixed meaning to the compiler, e.g. int, if, while. |
| Identifiers | User-defined names for variables, functions, labels, etc. |
| Literals | Constants that never change during a run — integer, floating-point, character and string constants. |
| Punctuators | Symbols such as , ; { } that shape the syntax of a construct. |
| Operators | Symbols 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.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:
| continue | break |
| Skips only the rest of the current iteration | Ends the loop completely |
| Control moves to the update expression, then the next test | Control 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 loop | Commonly 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.