C++
C++
Libraries
A library in C++ is a collection of precompiled code (functions, classes, or objects) that
you can use in your program to save time and avoid rewriting common functionalities.
C++ Program Structure
#include <iostream>
int main(){
std::cout << “Hello World!”<<std::endl;
std::cout<< “Welcome to C++ Programming World” ;
std:: cin<< “Enter Your Name: ”;
return 0;
}
Explanation
#include <iostream> : is a directive that includes the Input/Output Stream library in
your program, enabling you to use functionalities like std::cout for output and std::cin
for input.
int main(): is the entry point of a C++ program. When the program runs, it starts
execution from the main function. Here's what it does:
1. int part: It means the function returns an integer value to the operating system
after execution. Typically, returning 0 means the program ran successfully.
2. main() part: This is the function name where your program starts. You put your
program’s logic inside the curly braces { }.
std::cout: Used to display output on the console.
std::cin: Used to take input from the user.
std::endl: Moves to a new line and flushes the output buffer.
Namespace:
✅ Namespaces organize code and avoid conflicts.
✅ Use using namespace carefully to avoid accidental name clashes.
✅ Use nested namespaces to structure code in large projects.
✅ Anonymous namespaces help hide implementation details.
✅ Aliases simplify long namespace names.
1 Declaring a Namespace
1️⃣
namespace Math {
int add(int a, int b) {
return a + b;
}
}
namespace Outer {
namespace Inner {
void display() {
std::cout << "Inside Inner Namespace";
}
}
}
Outer::Inner::display(); // Accessing function
Comments
// Comments out a single line
/* … */ Block comments out a block of text
/* … */ Block comments can’t be nested
Functions
A function in C++ is a block of code that performs a specific task and can be reused
multiple times. Function must be defined before it’s use.
Reduces code duplication (write once, use multiple times).
Improves readability and modularity of code.
Can take input (parameters) and return output (return value).
Syntax:
namespace function_name(parameters)
return_type { {
int secretValue = 42; // Can only
// Function body (code to execute) be accessed in this file
}return value; // If return_type is not void
std::cout << secretValue;
}
Example:
Chaining std::cin
std::cin>>a>>b;
String
A string in C++ is a sequence of characters used to store and manipulate text.
To use string we need include the library called string as #include <string>
In C++, there are two main ways to handle strings:
1. C-style strings (char arrays)
2. std::string (Preferred, Modern C++ approach)
C-style Strings (Old way)
C-style strings are character arrays ending with a null terminator \0.
#include <iostream>
int main() {
char str[] = "Hello";
std::cout << str << std::endl;
return 0;
}
1️⃣Getting the Length of a String
We use .length() or .size() to get the number of characters in a string.
#include <iostream>
#include <string>
int main() {
std::string message = "C++ is awesome!";
std::cout << "Length: " << message.length() << std::endl;
std::cout << "Size: " << message.size() << std::endl; // Same as length()
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string word = "Hello";
// Using []
std::cout << "First letter: " << word[0] << std::endl;
// Using .at()
std::cout << "Last letter: " << word.at(word.length() - 1) << std::endl;
return 0;
}
📌 Difference:
word[0] works but does not check bounds.
word.at(0) is safer because it throws an error if the index is out of range.
3️⃣Modifying Strings
We can append, insert, and erase characters in a string.
📌 a) Appending to a String (+= and .append())
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
// Using +=
greeting += ", World!";
// Using .append()
greeting.append(" How are you?");
std::cout << greeting << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
// Using +=
greeting += ", World!";
// Using .append()
greeting.append(" How are you?");
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string sentence = "I love programming!";
// Erase "love " (index 2, length 5)
sentence.erase(2, 5);
std::cout << sentence << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string text = "Programming in C++ is fun fun!";
return 0;
}
left.
#include <iostream>
#include <string>
int main() {
std::string sentence = "The quick brown fox jumps over the lazy dog.";
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string phrase = "I hate Mondays!";
return 0;
}
Execution Model
The C++ execution model defines how a program is compiled, linked, and executed.
Stages of Execution
1. Preprocessing
o Removes comments, expands macros, and includes header files.
2. Compilation
o Converts source code (.cpp) into assembly code.
3. Assembly
o Converts assembly code into machine code (.obj or .o).
4. Linking
o Combines object files and libraries into an executable (.exe).
5. Loading
o Loads the executable into memory for execution.
6. Execution (Runtime)
o CPU executes instructions, manages memory, and handles I/O.
Float
A float is a data type used to store numbers with decimal points or fractional values.
Size
Type Precision Description
(bytes)
float 4 7 decimal places Single-precision floating-
point.
Double-precision
double 8 15 decimal places
floating-point.
long 8, 12, or More than double (platform-
Extended precision.
double 16 dependent)
When we divide the floating point number with 0 then the result will be an infinity
When we divide the floating point 0 with floating point 0 then the result will be
Nan(Not a Number)
Note: When writing floating remember to add suffix to the number (e.g., 9.8f). and also
for long double add suffix
Boolean
Booleans in C++ are represented by the bool type. A bool is either true or false.
C++ supports three boolean operators: ! (NOT), && (AND), and || (OR). You can also
use the alternative versions not, and, and or.
Precedence
The three Boolean operators each have different operator precedence. As a consequence,
they are evaluated in this order:
1. ! Highest precedence
2. && Medium
3. || Low Precedence.
If you want to force a different ordering, you can enclose a Boolean expression in
parentheses (ie. ()), as the parentheses have even higher operator precedence.
std::boolalpha : Changes Boolean output on streams from numeric (1/0) to textual
("true"/"false").
Characters and Text : ASCII Table
char Type:
Represents a single character (typically 1 byte).
Example literal: 'A'
Wide Characters:
wchar_t for wider character sets.
Use L'A' for wide char literals.
Unicode (C++11+):
char16_t and char32_t for UTF-16 and UTF-32.
static_cast<data_type>: Convert an expression from one type to another at compile
time, with type safety.
Auto Keyword in C++
Definition & Purpose
o Introduced in C++11.
o Enables type inference: the compiler deduces a variable's type from its
initializer.
o Simplifies declarations for complex types (e.g., iterators, lambda
expressions).
auto x = 42; // x deduced as int
Assignment Operator
Assignment Operator in C++
Definition:
o The assignment operator (=) assigns the value of one object (right-hand
side) to another (left-hand side).
o It is used for both built-in and user-defined types.
Operations on datatypes
Arithmetic Operations:
Relational Operator
When writing conditional statements, sometimes we need to use different types of
operators to compare values. These operators are called
Preview: Docs C++ supports different types of operators such as arithmetic, relational,
and logical operators.
To have a condition, we need relational operators:
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Relational operators compare the value on the left with the value on the right.
If Statement
An if statement is used to test an expression for truth and execute some code based on
it. Here’s a simple form of the if statement:
Syntax:
if (condition) {
some code
}