Introductory Notes on C++
1. Introduction to C++
C++ is a powerful, high-performance programming language developed by Bjarne
Stroustrup at Bell Labs in 1979. It is an extension of the C language, adding object-oriented
programming (OOP) features such as classes, objects, inheritance, polymorphism, and
abstraction. C++ is widely used in various domains, including system programming, game
development, embedded systems, high-performance computing, and more, due to its
efficiency, flexibility, and control over system resources.
C++ supports multiple programming paradigms, including procedural, object-oriented, and
generic programming. This versatility allows developers to choose the best approach for a
given problem, making C++ a highly adaptable language. Its performance capabilities are a
key reason for its adoption in applications where speed and resource management are
critical, such as operating systems, database systems, and real-time simulations.
This document aims to provide an introductory overview of C++, covering fundamental
concepts necessary for beginners to grasp the language. We will explore its basic structure,
input/output operations, control flow statements (conditionals and loops), functions,
arrays, and strings, accompanied by practical examples and illustrative diagrams to
enhance understanding.
2. C++ Basics
2.1 Program Structure
A typical C++ program has a well-defined structure that includes several key components.
Understanding this structure is crucial for writing organized and functional code. Below is a
breakdown of the common elements found in a C++ program:
• Preprocessor Directives: These lines begin with a # symbol and are processed before
the actual compilation of the code. They typically include header files that provide
access to predefined functions and classes. For example, #include <iostream> includes
the input/output stream library, which is essential for performing console input and
output operations.
• main() Function: Every C++ program must have a main() function. This is the entry
point of the program, where execution begins. When you run a C++ program, the code
inside the main() function is executed first.
• Comments: Comments are explanatory notes within the code that are ignored by the
compiler. They are used to make the code more readable and understandable for
humans. C++ supports two types of comments:
• Single-line comments: Start with // and continue to the end of the line.
• Multi-line comments: Start with /* and end with */ . They can span multiple lines.
• Statements: These are instructions that perform specific actions. Each statement in C++
typically ends with a semicolon ( ; ).
Here's a simple illustration of a basic C++ program structure:
Plain Text
#include <iostream> // Preprocessor directive: includes the iostream library
/*
This is a multi-line comment.
It explains the purpose of the program.
*/
int main() { // main function: program execution starts here
// This is a single-line comment
std::cout << "Hello, World!"; // Statement: prints "Hello, World!" to the
console
return 0; // Statement: indicates successful program termination
}
An illustrative diagram of the C++ program structure:
2.2 Data Types and Variables
Data types specify the type of data that a variable can hold, such as integers, floating-point
numbers, characters, and more. C++ has a rich set of built-in (primitive) data types and also
allows users to define their own (user-defined) data types.
Common built-in data types include:
• int : Used to store whole numbers (integers) without decimal points. Example: int age =
30;
• float : Used to store single-precision floating-point numbers (numbers with decimal
points). Example: float temperature = 25.5f;
• double : Used to store double-precision floating-point numbers, offering more
precision than float . Example: double pi = 3.14159;
• char : Used to store single characters. Example: char grade = 'A';
• bool : Used to store boolean values, which can be either true or false . Example: bool
is_active = true;
Variables are named storage locations that hold data. Before using a variable, it must be
declared with a specific data type. You can also initialize a variable (assign an initial value)
at the time of declaration.
Plain Text
#include <iostream>
int main() {
// Variable declaration and initialization
int score = 100;
double price = 99.99;
char initial = 'J';
bool game_over = false;
// Displaying variable values
std::cout << "Score: " << score << std::endl;
std::cout << "Price: " << price << std::endl;
std::cout << "Initial: " << initial << std::endl;
std::cout << "Game Over: " << game_over << std::endl;
// Modifying variable values
score = 150;
game_over = true;
std::cout << "New Score: " << score << std::endl;
std::cout << "Game Over: " << game_over << std::endl;
return 0;
}
3. Input and Output
In C++, input and output operations are primarily handled using streams. The iostream
library provides the necessary functionalities for console input and output. The two most
commonly used objects for I/O are std::cin for input and std::cout for output.
• std::cout (Console Output): Used to display output on the console. It is typically used
with the insertion operator ( << ). You can output various data types, including strings,
integers, and floating-point numbers. The std::endl manipulator is used to insert a
newline character and flush the output buffer.
• std::cin (Console Input): Used to read input from the console (keyboard). It is typically
used with the extraction operator ( >> ). When reading input, std::cin automatically
handles type conversion based on the variable it's reading into. For reading entire lines
of text, especially those containing spaces, std::getline(std::cin, variable_name) is often
preferred over std::cin >> variable_name .
Here's an example demonstrating basic input and output operations:
Plain Text
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << name << "! You are " << age << " years old." <<
std::endl;
return 0;
}
An illustrative diagram of the C++ input/output process:
4. Conditional Statements
Conditional statements allow a program to execute different blocks of code based on
whether a certain condition is true or false. C++ provides several types of conditional
statements, including if , if-else , and switch-case .
4.1 if-else Statement
The if statement executes a block of code if a specified condition is true. The if-else
statement extends this by providing an alternative block of code to execute if the condition
is false.
• if : The code inside the if block is executed only when the condition is true.
• else if : You can use else if to test multiple conditions in sequence. If the first if
condition is false, the next else if condition is evaluated, and so on.
• else : The code inside the else block is executed if none of the preceding if or else
if conditions are true.
Here is an example of an if-else statement:
Plain Text
#include <iostream>
int main() {
int number;
std::cout << "Enter an integer: ";
std::cin >> number;
if (number > 0) {
std::cout << "You entered a positive integer." << std::endl;
} else if (number < 0) {
std::cout << "You entered a negative integer." << std::endl;
} else {
std::cout << "You entered zero." << std::endl;
}
return 0;
}
Flowchart for the if-else statement:
4.2 switch-case Statement
The switch-case statement is used to select one of many code blocks to be executed. It
evaluates an expression and compares its value to a series of case labels. When a match is
found, the code block associated with that case is executed.
• switch : The expression inside the switch statement is evaluated once.
• case : The value of the expression is compared with the values of each case . If there is
a match, the associated block of code is executed.
• break : The break statement is used to exit the switch statement. If break is
omitted, execution will continue into the next case .
• default : The default block is executed if no case matches the expression's value.
Here is an example of a switch-case statement:
Plain Text
#include <iostream>
int main() {
int day = 4;
switch (day) {
case 1:
std::cout << "Monday";
break;
case 2:
std::cout << "Tuesday";
break;
case 3:
std::cout << "Wednesday";
break;
case 4:
std::cout << "Thursday";
break;
case 5:
std::cout << "Friday";
break;
case 6:
std::cout << "Saturday";
break;
case 7:
std::cout << "Sunday";
break;
default:
std::cout << "Invalid day";
}
return 0;
}
Flowchart for the switch-case statement:
5. Looping Statements
Looping statements, also known as iteration statements, allow a block of code to be
executed repeatedly as long as a certain condition is met. C++ provides three main types of
loops: for , while , and do-while .
5.1 for Loop
The for loop is used when you know in advance how many times you want to execute a
block of code. It consists of three parts: initialization, condition, and update.
• Initialization: Executed once at the beginning of the loop. It typically declares and
initializes a loop control variable.
• Condition: Evaluated before each iteration. If true, the loop body is executed;
otherwise, the loop terminates.
• Update: Executed after each iteration. It typically updates the loop control variable.
Here is an example of a for loop:
Plain Text
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration " << i << std::endl;
}
return 0;
}
Flowchart for the for loop:
5.2 while Loop
The while loop repeatedly executes a block of code as long as a specified condition is true.
The condition is evaluated before each iteration.
Here is an example of a while loop:
Plain Text
#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
return 0;
}
Flowchart for the while loop:
5.3 do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the loop body is
executed at least once. The condition is evaluated after the first iteration.
Here is an example of a do-while loop:
Plain Text
#include <iostream>
int main() {
int i = 0;
do {
std::cout << "Value of i: " << i << std::endl;
i++;
} while (i < 5);
return 0;
}
Flowchart for the do-while loop:
6. Functions
Functions are blocks of code that perform a specific task. They help in organizing code,
making it more modular, reusable, and easier to understand. Functions can take input
values (arguments or parameters) and can return a value.
6.1 Function Declaration and Definition
• Declaration (Prototype): A function declaration tells the compiler about the function's
name, return type, and parameters. It's like a promise that the function will be defined
later.
• Definition: The function definition provides the actual body of the function, containing
the code that performs the task.
6.2 Calling Functions
To execute the code within a function, you need to call it. When a function is called, the
program control transfers to the function, and after its execution, the control returns to the
point where it was called.
Here is an example demonstrating function declaration, definition, and calling:
Plain Text
#include <iostream>
// Function declaration (prototype)
int add(int a, int b);
int main() {
int num1 = 10;
int num2 = 20;
int sum;
// Calling the add function
sum = add(num1, num2);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Flowchart for a C++ function call:
7. Arrays
An array is a collection of elements of the same data type stored in contiguous memory
locations. Arrays provide a way to store multiple values under a single variable name,
making it easier to manage and manipulate related data. Each element in an array is
accessed using an index, which starts from 0 for the first element.
7.1 Declaring and Initializing Arrays
To declare an array, you specify the data type of its elements, followed by the array name
and its size in square brackets. You can also initialize an array at the time of declaration.
Plain Text
data_type array_name[size];
Examples:
Plain Text
// Declaration of an integer array named 'numbers' with 5 elements
int numbers[5];
// Declaration and initialization of an integer array
int scores[3] = {100, 90, 80};
// Declaration and initialization without specifying size (compiler infers
size)
int grades[] = {85, 92, 78, 95};
7.2 Accessing Array Elements
Array elements are accessed using their index. The index of the first element is 0, the second
is 1, and so on. The last element's index is size - 1 .
Plain Text
#include <iostream>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing elements
std::cout << "First element: " << numbers[0] << std::endl; // Output: 10
std::cout << "Third element: " << numbers[2] << std::endl; // Output: 30
// Modifying an element
numbers[1] = 25;
std::cout << "Modified second element: " << numbers[1] << std::endl; //
Output: 25
// Iterating through an array using a for loop
std::cout << "All elements: ";
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
An illustrative diagram of array memory representation:
8. Strings
In C++, strings are sequences of characters. C++ provides two main ways to handle strings:
C-style character arrays and the std::string class.
8.1 C-style Strings (Character Arrays)
C-style strings are arrays of characters terminated by a null character ( \0 ). They are
inherited from the C language and are handled using character pointers and functions from
the <cstring> header.
Plain Text
#include <iostream>
#include <cstring> // For strlen, strcpy, etc.
int main() {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char message[] = "World"; // Size is automatically determined, includes
null terminator
std::cout << "Greeting: " << greeting << std::endl;
std::cout << "Message: " << message << std::endl;
// Concatenating strings
char combined[12];
strcpy(combined, greeting);
strcat(combined, message);
std::cout << "Combined: " << combined << std::endl;
return 0;
}
8.2 std::string Class
The std::string class, part of the Standard C++ Library ( <string> header), provides a more
convenient and safer way to work with strings. It handles memory management
automatically and offers a rich set of member functions for string manipulation.
Plain Text
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello";
std::string s2 = " C++";
// Concatenation
std::string s3 = s1 + s2;
std::cout << "Concatenated string: " << s3 << std::endl;
// Length of string
std::cout << "Length of s3: " << s3.length() << std::endl;
// Accessing characters
std::cout << "First character of s3: " << s3[0] << std::endl;
// Substring
std::string sub = s3.substr(6, 3); // Start at index 6, length 3
std::cout << "Substring: " << sub << std::endl;
return 0;
}
An illustrative diagram of std::string memory representation: