Introduction to C++
Introduction to C++
C++ is a powerful, high-performance, general-purpose programming language
developed by Bjarne Stroustrup in 1983 as an extension of the C
programming language. It adds object-oriented programming (OOP) features
and additional functionalities to C, making it versatile for system/software
development, game programming, and more.
Key Features of C++
1. Object-Oriented Programming (OOP): Supports classes, objects,
inheritance, polymorphism, encapsulation, and abstraction.
2. Rich Standard Library: Includes a wide variety of functions and data
structures like the Standard Template Library (STL).
3. Low-Level Manipulation: Allows direct memory access using pointers.
4. Cross-Platform: Code can run on various operating systems with minor
adjustments.
5. Efficiency: Offers fine-grained control over hardware resources.
Tokens in C++
A token is the smallest unit of a C++ program. Tokens include:
1. Keywords: Reserved words that have a special meaning in the language.
Example: int, return, if, else, for.
2. Identifiers: Names used for variables, functions, arrays, etc., defined by
the programmer. Example: count, sum, calculate().
3. Literals: Fixed values directly written in the code. Example: 10, 3.14,
'a', "Hello".
4. Operators: Symbols that perform operations on variables and values.
Example: +, -, *, /, =.
5. Punctuation: Characters that structure the code. Example: {, }, ;, ,.
6. Comments: Non-executable text for documentation. Example: //
Single-line comment, /* Multi-line comment */.
Precedence and Associativity of Operators
Operator precedence determines the order in which operators are evaluated in
expressions. If multiple operators are in an expression, operators with higher
precedence are evaluated first. Associativity determines the direction of
evaluation when two operators of the same precedence appear.
Example:
int result = 10 + 20 * 3; // Multiplication (*) is evaluated before
addition (+)
Table of Common Operators by Precedence:
Precedence Operators Associativity
1 (Highest) :: Left to Right
2 ++ (postfix), -- Left to Right
3 *, /, % Left to Right
4 +, - Left to Right
5 <, <=, >, >= Left to Right
6 ==, != Left to Right
7 && Left to Right
8 `
9 (Lowest) = (assignment) Right to Left
Associativity Example:
int x = 5, y = 10, z;
z = x = y; // Right-to-left associativity: y is assigned to x, and
then x is assigned to z
Understanding tokens and precedence is crucial for writing clear, efficient, and
bug-free C++ programs.
Data Types in C++
In C++, data types define the type of data that can be stored in a variable. They
determine the size, type of values, and permissible operations on variables.
Categories of Data Types
1. Primitive Data Types (Basic or Fundamental)
2. Derived Data Types
3. User-Defined Data Types
1. Primitive Data Types
These are the basic types provided by C++.
Size
Type Description Example
(Typical)
int Integer numbers 4 bytes int x = 10;
float
Single-precision floating-point float y = 3.14;
4 bytes
numbers
double
Double-precision floating-point double z = 2.71;
8 bytes
numbers
char Single character 1 byte char c = 'A';
bool isOpen =
bool Boolean values (true or false) 1 byte true;
void
Represents no value (used for void function();
N/A
functions)
2. Derived Data Types
Derived types are based on fundamental types.
Type Description Example
Collection of elements of the int arr[5] = {1, 2, 3, 4, 5};
Array
same type
Pointer Stores the address of a variable int *ptr = &x;
Group of statements performing int sum(int a, int b) { return
Function a+b; }
a task
Reference Alias for another variable int &ref = x;
3. User-Defined Data Types
These types are defined by the user for more complex data structures.
Type Description Example
Type Description Example
class MyClass { int data;
Class Defines a blueprint for objects };
struct MyStruct { int id;
Structure Groups different types of data };
enum Color { Red, Green,
Enumeration Enumerated constants Blue };
Creates a new name for an typedef int Age; Age a =
Typedef/Using 30;
existing type
Shares memory for different union Data { int i; char
Union c; };
variables
Modifiers for Data Types
Modifiers adjust the size or range of basic data types:
Modifier Effect Example
signed Default for numeric types signed int x;
unsigned Non-negative values only unsigned int x;
short Reduces the size of integers short int x;
long Increases the size of integers long int x;
Special Notes
1. Size and Range: The size of data types may vary depending on the
system (32-bit or 64-bit architecture).
o Example: int is typically 4 bytes, but may differ.
2. Type Casting: You can convert one data type to another using:
o Implicit casting: int x = 5.5; (truncates to 5)
o Explicit casting: float x = (float)5 / 2;
Control Structures in C++
Control structures determine the flow of execution of a program. They allow
programmers to specify the order in which statements are executed based on
conditions or iterations.
Types of Control Structures
1. Sequential Control
2. Decision-Making Control
3. Loop Control
4. Jump Control
1. Sequential Control
Default flow of execution where statements are executed one after the
other.
Example:
int a = 10;
int b = 20;
cout << "Sum: " << (a + b) << endl; // Executes sequentially
2. Decision-Making Control
Used to make decisions and execute different parts of the code based on
conditions.
Type Description Syntax
Executes if the condition is if (condition) { /* statements */ }
if
true
Executes one block if true, if (condition) { /* true block */ }
if-else else { /* false block */ }
another if false
if (cond1) { ... } else if (cond2) {
else-if Checks multiple conditions ... } else { ... }
Executes based on the switch (variable) { case 1: ...;
switch break; default: ...; }
value of a variable
Examples:
if-else:
int x = 10;
if (x > 0) {
cout << "Positive" << endl;
} else {
cout << "Negative" << endl;
}
switch:
char grade = 'A';
switch (grade) {
case 'A': cout << "Excellent"; break;
case 'B': cout << "Good"; break;
default: cout << "Invalid Grade"; break;
}
3. Loop Control
Used to repeat a set of instructions until a condition is satisfied.
Type Description Syntax
Repeats a block for a fixed for (init; condition; update) {
for /* statements */ }
number of iterations
Repeats while a condition is while (condition) { /* statements
while */ }
true
do- Executes at least once, then do { /* statements */ } while
while repeats if true (condition);
Examples:
for loop:
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
while loop:
int x = 0;
while (x < 5) {
cout << x << endl;
x++;
}
do-while loop:
int x = 0;
do {
cout << x << endl;
x++;
} while (x < 5);
4. Jump Control
Used to alter the normal flow of execution in a program.
Type Description Syntax
break Exits the current loop or switch break;
continue Skips the current iteration of a loop continue;
goto Jumps to a labeled statement goto label;
return Exits from a function return value;
Examples:
break:
for (int i = 0; i < 10; i++) {
if (i == 5) break; // Exit loop when i is 5
cout << i << endl;
}
continue:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // Skip even numbers
cout << i << endl;
}
goto:
int x = 10;
if (x > 0) goto positive;
cout << "Negative" << endl;
positive:
cout << "Positive" << endl;
Array in C++
An array in C++ is a collection of elements of the same data type, stored in
contiguous memory locations. Arrays allow you to store and access multiple
values using a single variable name and an index.
Key Features of Arrays:
1. Fixed Size: The size of an array is defined during its declaration and
cannot be changed later.
2. Homogeneous Data: All elements in an array must be of the same data
type.
3. Random Access: Elements can be accessed directly using their index.
Syntax:
data_type array_name[size];
data_type: Type of elements in the array (e.g., int, float, char).
array_name: Name of the array.
size: Number of elements the array can hold.
Example: Declaring and Using an Array
1. Declaration and Initialization:
int numbers[5] = {10, 20, 30, 40, 50}; // Declare and
initialize
2. Accessing Elements:
You can access elements using the index (starting from 0):
cout << numbers[0]; // Outputs: 10
cout << numbers[4]; // Outputs: 50
3. Updating Elements:
numbers[1] = 25; // Update second element to 25
Example Program
#include <iostream>
using namespace std;
int main() {
// Declare and initialize an array
int marks[5] = {90, 85, 78, 92, 88};
// Access elements using a loop
cout << "Marks: ";
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
// Update an element
marks[2] = 80; // Update the third element
cout << "Updated Marks: ";
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
return 0;
}
Output:
less
Marks: 90 85 78 92 88
Updated Marks: 90 85 80 92 88
Types of Arrays
1. Single-Dimensional Array: Stores data in a linear format.
o Example: int arr[5] = {1, 2, 3, 4, 5};
2. Multi-Dimensional Array: Stores data in a grid or table-like structure
(e.g., matrix).
o Example:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
cout << matrix[1][2]; // Outputs: 6
3. Dynamic Array: Created at runtime using pointers.
o Example:
int* dynamicArray = new int[5];
delete[] dynamicArray; // Free memory
Advantages of Arrays:
Efficient for storing and managing large collections of data.
Direct access to elements using an index.
Limitations:
Fixed size (cannot grow or shrink dynamically).
All elements must be of the same data type.