Unit 2: Basics of C++
2.1 Introduction to structure of C++ program
2.2 Header Files
2.3 Access Modifiers
2.4 Tokens, Expressions and Control Structures
2.5 Predefine and User Define Data Types
2.1 Introduction to structure of C++ program
A C++ program follows a specific structure that defines how the source code is written,
compiled, and executed. Understanding this structure is important because it helps beginners
organize code properly and ensures smooth execution by the compiler. Every C++ program
consists of different sections such as preprocessor directives, functions, and the `main () `
function, which acts as the entry point.
#include <iostream> // Preprocessor directive
using namespace std; // Namespace declaration
// Global declarations (if any)
int main() // Main function
// Body of main function
cout << "Hello, World!"; // Statement
return 0; // Program terminates successfully
Main Components of a C++ Program
1. Documentation Section (Comments)
Used to describe the purpose of the program, author details, or logic explanation.
Example:
cpp
// this program prints Hello World
2. Preprocessor Directives
Statements beginning with `#` which include libraries or perform preprocessing before
compilation.
Example:
cpp
#include <iostream>
3. Namespace Declaration
Specifies the scope of identifiers.
Example:
cpp
using namespace std;
4. Global Declarations (Optional)
Variables, constants, or functions defined outside `main()` and accessible throughout the
program.
5. `main () ` Function
The entry point of every C++ program.
Syntax:
cpp
int main()
// program statements
return 0;
}
6. Program Statements (Body of main)
Actual logic is written here using variables, operators, control structures, functions, etc.
7. Return Statement
`return 0;` indicates successful termination of the program.
Key Notes
The order of sections must be maintained (preprocessor → namespace → main).
Every C++ statement ends with a semicolon (`;`).
Braces `{ }` define the beginning and end of a block of code.
`main()` is mandatory, but other functions can be added as per requirement.
2.2 Header Files
Header Files in C++
Introduction
A header file in C++ is a file that contains pre-written code, such as function
declarations, classes, macros, and constants, which can be reused in multiple programs.
They save time and effort by allowing programmers to use standard functions (like
`cout`, `cin`, `sqrt()`, etc.) without writing them from scratch.
Header files are included in a program using the preprocessor directive `#include`.
Types of Header Files
1. Standard Header Files (Predefined)
Provided by C++ and stored in the compiler’s library.
Examples:
`<iostream>` → for input/output (`cin`, `cout`)
`<cmath>` → for mathematical functions (`sqrt`, `pow`, `sin`)
`<string>` → for string operations
`<fstream>` → for file handling (`ifstream`, `ofstream`)
2. User-defined Header Files
Created by the programmer to store commonly used functions or class declarations.
Syntax:
cpp
#include "myheader.h"
```
Example:
If you create a file `myheader.h` with some functions, you can reuse it in multiple
C++ programs.
Syntax of Including Header Files
cpp
#include <headerfile> // For standard library header files
#include "headerfile" // For user-defined header files
Example:
1. Using Standard Header File
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
2. Using User-Defined Header File
File: `myheader.h`
cpp
void greet() {
cout << "Welcome to C++ Programming!" << endl;
}
```
File: `[Link]`
cpp
#include <iostream>
#include "myheader.h"
using namespace std;
int main() {
greet();
return 0;
}
Advantages of Header Files
Code reusability (no need to rewrite common functions).
Modularity (separates interface from implementation).
Makes programs more organized and easy to maintain.
2.3 Access Modifiers
Introduction
Access modifiers (also called access specifiers) in C++ define the scope and visibility of
class members (data and functions).
They control how the members of a class can be accessed inside and outside the class.
By default, all members of a class are private unless specified.
Types of Access Modifiers in C++*
1. Public
Members declared as `public` are accessible from anywhere in the program.
Example:
cpp
#include <iostream>
using namespace std;
class Student {
public:
string name;
void display() {
cout << "Name: " << name << endl;
}
};
int main() {
Student s;
[Link] = "Rahul"; // Accessible outside the class
[Link]();
return 0;
}
2. Private
Members declared as `private` are accessible only within the class.
They cannot be accessed directly outside the class.
Example:
cpp
class Account {
private:
int balance;
public:
void setBalance(int b) {
balance = b; // Allowed
}
int getBalance() {
return balance;
}
};
int main() {
Account a;
// [Link] = 1000; ❌ Not allowed
[Link](1000); // ✅ Access through public function
cout << "Balance: " << [Link]();
return 0;
}
3. Protected
Members declared as `protected` are accessible:
Inside the same class.
In derived classes (through inheritance).
But not accessible directly from outside the class.
Example:
cpp
class Person {
protected:
string name;
};
class Student : public Person {
public:
void setName(string n) {
name = n; // Accessible in derived class
}
void display() {
cout << "Name: " << name << endl;
}
};
int main() {
Student s;
[Link]("Anita");
[Link]();
// [Link] = "XYZ"; ❌ Not allowed outside class
return 0;
}
Comparison Table
| Access Modifier | Inside Class | Derived Class | Outside Class |
| ---------------------| ------------ | ------------- | ------------- |
| Public | ✔ Allowed | ✔ Allowed | ✔ Allowed |
| Private | ✔ Allowed | ❌ Not Allowed | ❌ Not Allowed |
| Protected | ✔ Allowed | ✔ Allowed | ❌ Not Allowed |
Key Points
Use private for data members to ensure data security (Encapsulation).
Use public for functions that need to provide access to data.
Use protected when designing inheritance-based relationships.
2.4 Tokens, Expressions and Control Structures
1. Tokens in C++
Definition:
Tokens are the smallest units in a C++ program that carry meaning to the compiler.
Types of Tokens:
1. Keywords
Reserved words with special meaning.
Example: `int`, `float`, `if`, `while`, `return`.
2. Identifiers
Names given to variables, functions, classes, etc.
Example: `sum`, `studentName`.
3. Constants
Fixed values that do not change during program execution.
Example: `10`, `3.14`, `'A'`, `"Hello"`.
4. Operators
Symbols used to perform operations.
Example: `+`, `-`, `*`, `/`, `%`, `==`.
5. Special Symbols
Characters with special meaning.
Example: `{ }`, `;`, `()`, `[]`.
6. Strings
Sequence of characters enclosed in double quotes.
Example: `"C++ Programming"`.
2. Expressions in C++
Definition:
An expression is a **combination of constants, variables, operators, and functions that
produces a value.
Types of Expressions
1. Arithmetic Expressions
Perform mathematical calculations.
Example: `a + b * c`.
2. Relational Expressions
Compare two values; result is either true (1) or false (0).
Example: `x > y`, `a == b`.
3. Logical Expressions
Combine conditions using logical operators (`&&`, `||`, `!`).
Example: `(age > 18 && marks > 50)`.
4. Assignment Expressions
Assign values to variables.
Example: `x = 10`, `sum = a + b`.
5. Conditional (Ternary) Expression
Shorthand for `if-else`.
Syntax: `condition ? expr1 : expr2`
Example: `max = (a > b) ? a : b;`
3. Control Structures in C++
Definition:
Control structures determine the flow of execution of statements in a program.
Types:
A. Sequence Structure
Default execution, statements are executed one after another.
Example:
cpp
int a = 5, b = 10;
int sum = a + b;
cout << sum;
B. Selection (Decision-making) Structures
1. if Statement
cpp
if (x > 0)
cout << "Positive";
2. if-else Statement
cpp
if (x % 2 == 0)
cout << "Even";
else
cout << "Odd";
3. Nested if
cpp
if (x > 0) {
if (x < 100)
cout << "Positive and less than 100";
}
4. switch Statement
cpp
switch (grade) {
case 'A': cout << "Excellent"; break;
case 'B': cout << "Good"; break;
default: cout << "Invalid";
}
C. Iteration (Looping) Structures
1. for Loop
cpp
for (int i = 1; i <= 5; i++)
cout << i;
2. while Loop
cpp
int i = 1;
while (i <= 5) {
cout << i;
i++;
}
3. do-while Loop
cpp
int i = 1;
do {
cout << i;
i++;
} while (i <= 5);
D. Jumping Statements
break → Exit from loop/switch.
continue → Skip current iteration and continue next.
goto → Jump to a labeled statement (not recommended).
Summary
Tokens → Building blocks of a program.
Expressions → Combinations that evaluate to a value.
Control Structures → Direct the flow of execution (sequence, decision, looping,
jumping).
2.5 Predefine and User Define Data Types
1. Predefined (Built-in) Data Types
Also called primitive data types.
Provided by C++ compiler and directly usable.
Used to declare variables for storing basic kinds of values.
Common Predefined Data Types
Data Size (Approx) Description Example
Type
int 2 or 4 bytes Stores integers (whole numbers). int age = 21;
float 4 bytes Stores decimal (single precision). float pi = 3.14;
double 8 bytes Stores decimal (double precision). double area = 45.678;
char 1 byte Stores a single character. char grade = 'A';
bool 1 byte Stores logical values (true/false). bool flag = true;
void — Represents no value/empty. void functionName();
Summary
Predefined Data Types: Provided by C++ (basic building blocks).
Derived Data Types: Formed from basic ones (arrays, pointers).
User-Defined Data Types: Designed by programmer (struct, class, enum, typedef).