5 hours · 7 marks
#include <iostream> // preprocessor directive
using namespace std; // namespace declaration
int main() { // entry point of every program
cout << "Hello World"; // statement
return 0; // return status to OS
}
A typical C++ program has: preprocessor directives, namespace declarations, global declarations (optional), the main() function (mandatory, execution starts here), and other user-defined functions/classes.
Character set: letters (A–Z, a–z), digits (0–9), special symbols (+ - * / = ; , . etc.), and white space.
Tokens are the smallest individual units of a program. Types of tokens:
int, class, if, while, return, new, delete, etc.{ } ( ) [ ] ; , :+ - * / % = == != < > && || ++ -- etc.A variable must be declared with a type before use: int age = 21;. C++ allows declaration anywhere before first use (unlike old C which required declarations at the top of a block).
An expression combines variables, constants and operators to produce a value, e.g. a + b * c. Expressions can be arithmetic, relational, logical, or assignment expressions.
| Category | Types | Typical size |
|---|---|---|
| Fundamental | int, char, float, double, bool, void | 4, 1, 4, 8, 1 bytes |
| Modifiers | signed, unsigned, short, long | modifies range/size |
| Derived | array, pointer, function, reference | depends on base type |
| User-defined | struct, union, class, enum, typedef | depends on members |
int to float in a mixed expression.float f = 9.7;
int a = (int) f; // C-style cast
int b = int(f); // function-style cast (C++)
int c = static_cast<int>(f); // C++ style cast (preferred)
static_cast, dynamic_cast, const_cast, reinterpret_cast — safer and more explicit than C-style casts.constconst float PI = 3.1416; // value cannot change after initialization
const int SIZE = 10;
// PI = 3.14; -> compile error
const is preferred over the C preprocessor macro #define because it is type-checked by the compiler and obeys scope rules.
A reference is an alias (another name) for an existing variable, declared with &. It must be initialized when declared and cannot be reseated afterward.
int a = 10;
int &ref = a; // ref is an alias for a
ref = 20; // a becomes 20 too
cout << a; // prints 20
References are commonly used for pass-by-reference function arguments and for returning objects by reference, avoiding costly copies.
if, if-else, else-if ladder, switch-case.for (entry-controlled, counter-based), while (entry-controlled), do-while (exit-controlled, executes at least once).break (exit loop/switch), continue (skip to next iteration), goto.for (int i = 1; i <= 5; i++) cout << i << " ";
int i = 0;
do { cout << i; i++; } while (i < 3);
A namespace groups related identifiers under a name to avoid naming collisions between libraries/modules.
namespace MyLib {
int value = 5;
void show() { cout << value; }
}
int main() {
MyLib::show(); // scope resolution operator ::
using namespace MyLib; // brings all names into scope
}
std is the standard namespace containing cout, cin, string, etc.
A function is a named block of code that performs a task and can be called repeatedly. Syntax: returnType name(parameters) { body }.
Multiple functions with the same name but different parameter lists (number/type of parameters) in the same scope. Resolved at compile time (static polymorphism).
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
Requests the compiler to substitute the function's code directly at the call site instead of a normal function call, avoiding call overhead — best for small, frequently used functions.
inline int square(int x) { return x * x; }
A parameter can have a default value used when the caller omits an argument. Default arguments must be specified from right to left.
void greet(string name, string msg = "Hello") {
cout << msg << ", " << name;
}
greet("Ram"); // uses default msg
greet("Ram", "Hi"); // overrides default
void increment(int &x) { x++; } // pass by reference — modifies caller's variable
int &getElement(int arr[], int i) { return arr[i]; } // return by reference
Pass-by-reference avoids copying (efficient for large objects) and allows the function to modify the caller's variable directly, unlike pass-by-value.
int arr[5] = {1,2,3,4,5};int *p = &arr[0];. Array name decays to a pointer to its first element.char name[20] = "Ram";) or the C++ std::string class which manages memory automatically and supports operators like + for concatenation.Structure (struct) | Union (union) |
|---|---|
| Each member gets its own memory; total size = sum of members | All members share the same memory location; size = size of largest member |
| All members can hold values simultaneously | Only one member holds a valid value at a time |
struct Point { int x, y; };
union Data { int i; float f; char c; };
enum defines a set of named integer constants, improving code readability.
enum Day { SUN, MON, TUE, WED, THU, FRI, SAT }; // SUN=0, MON=1 ...
Day today = WED;
enum Level { LOW = 1, MEDIUM = 5, HIGH = 10 }; // custom values
Memory allocated at run time on the heap, using new and released using delete (C++), as opposed to C's malloc()/free().
int *p = new int; // single variable
*p = 10;
delete p; // free memory
int *arr = new int[5]; // array
delete[] arr; // free array memory (note the [])
Failing to delete allocated memory causes a memory leak.
area() for circle, rectangle, and triangle. 5 marks#include <iostream>
using namespace std;
float area(float r) { return 3.1416 * r * r; } // circle
float area(float l, float b) { return l * b; } // rectangle
float area(float b, float h, bool tri) { return 0.5*b*h; } // triangle
int main() {
cout << area(5) << endl;
cout << area(4, 6) << endl;
cout << area(4, 6, true) << endl;
}
void byValue(int x) { x = 100; } // caller's variable unaffected
void byRef(int &x) { x = 100; } // caller's variable changed
int main() {
int a = 5;
byValue(a); cout << a; // 5
byRef(a); cout << a; // 100
}
inline request for large/recursive functions, not suitable for functions with loops or large bodies.new and delete operators with example. 5 marksnew allocates memory and returns a pointer to it; delete releases memory back to the system. See code in section 2.14. Emphasize: always match every new with a delete, and every new[] with delete[], to avoid memory leaks.*p). References use simpler syntax and are commonly used for function parameters.enum to represent days of the week and print whether a given day is a weekend. 5 marks#include <iostream>
using namespace std;
enum Day { SUN, MON, TUE, WED, THU, FRI, SAT };
int main() {
Day d = SAT;
if (d == SUN || d == SAT) cout << "Weekend";
else cout << "Weekday";
}
static_cast (general-purpose conversions checked at compile time), dynamic_cast (safe downcasting in polymorphic class hierarchies, checked at run time), const_cast (adds/removes const/volatile), reinterpret_cast (low-level reinterpretation of bit patterns, e.g. pointer type conversions).