§2024-12-02
¶hello World
- helloWorld.cpp
sudo apt install build-essential -y
#include <iostream>
using namespace std;
// Your first program in C++
int main()
{
cout << "Hello World!" << endl;
return 0;
}
$ g++ -o helloWorld helloWorld.cpp
$ ls -l
total 20
-rwxr-xr-x 1 alexlai alexlai 71080 Dec 2 13:39 helloWorld
-rw-r--r-- 1 alexlai alexlai 144 Dec 2 13:37 helloWorld.cpp
alexlai@n2Bookworm:~/build/cpp-proj$ ./helloWorld
Hello World!
// Online C++ compiler to run C++ program online
#include <iostream>
int main() {
// Write C++ code here
int myAge = 10;
std::cout << "I am " << myAge << " years old.";
return 0;
}
¶
#include<iostream>
#include<string>
using namespace std;
int main() {
string first_name = "John ";
string last_name = "Doe";
string full_name = first_name.append(last_name);
cout << full_name.length() << endl; // 8
cout << full_name.size() << endl; // 8
}#include<iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 1;
}
¶comments
// This is a single line comment
cout << "Hello World!";
/* multiple line comments:
The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
¶C++ Variables
Variables are containers for storing data values.
- int - stores integers (whole numbers), without decimals, such as 123 or -123
- double - stores floating point numbers, with decimals, such as 19.99 or -19.99
- char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
- string - stores text, such as "Hello World". String values are surrounded by double quotes
- bool - stores values with two states: true or false
int myNum = 5; // Integer (whole number without decimals)
// To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50;
// One Value to Multiple Variables
int x, y, z;
x = y = z = 50;
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
¶The general rules for naming variables are:
Names can contain letters, digits and underscores
Names must begin with a letter or an underscore (_)
Names are case-sensitive (myVar and myvar are different variables)
Names cannot contain whitespaces or special characters like !, #, %, etc.
Reserved words (like C++ keywords, such as int) cannot be used as names
¶Constants
When you do not want others (or yourself) to change existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only):
Use UpperCamelCase for enum names. Enum values can be in UPPER_SNAKE_CASE.
const int MY_NUM = 15; // myNum will always be 15
MY_NUM = 10; // error: assignment of read-only variable 'myNum'
When you declare a constant variable, it must be assigned with a value:
const int MINUTES_PER_HOUR;
MINUTES_PER_HOUR = 60; // error <----
const int MINUTES_PER_HOUR = 60; //<-- is OK
¶Short Hand If...Else (Ternary Operator)
variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
¶ C++ Switch Statements
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
¶C++ Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
¶C++ For Loop
// Online C++ compiler to run C++ program online
#include <iostream>
#include <string>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
return 0;
}
¶ Array
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
int main() {
// Write C++ code here
// Create an array of integers
int myNumbers[5] = {10, 20, 30, 40, 50};
// Loop through integers
for (int i : myNumbers) {
cout << i << "\n";
}
return 0;
}
- output
10
20
30
40
50
¶Fixed Size (Arrays) vs. Dynamic Size (Vectors)
string cars[]; // Array size is not specified
// A vector with 3 elements
vector<string> cars = {"Volvo", "BMW", "Ford"};
// Adding another element to the vector
cars.push_back("Tesla");
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Initialize a vector of strings
vector<string> cars = {"Volvo", "BMW", "Ford"};
// Adding another element to the vector
cars.push_back("Tesla");
// Loop through the vector and print each string
for (const string& car : cars) {
cout << car << "\n";
}
return 0;
}
¶ sizeof(Array)
The size of the array in bytes
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result: 20
Why did the result show 20 instead of 5, when the array contains 5 elements? It is because the sizeof() operator returns the size of a type in bytes. You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
To find out how many elements an array has, you have to divide the size of the array by the size of the first element in the array:
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(myNumbers[0]);
cout << getArrayLength;
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(myNumbers[0]); i++) {
cout << myNumbers[i] << "\n";
}
¶Multi-Dimensional Arrays
To declare a multi-dimensional array, define the variable type, specify the name of the array followed by square brackets which specify how many elements the main array has, followed by another set of square brackets which indicates how many elements the sub-arrays have:
string letters[2][4];
¶C++ Structures
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here
// Put data into the first structure
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Put data into the second structure
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
BMW X5 1999
Ford Mustang 1969
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
// Declare a structure named "car" could be inside or above main(), but not behind
struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
BMW X5 1999
Ford Mustang 1969
¶C++ Enums
An enum is a special type that represents a group of constants (unchangeable values). A type that represents a group of constants
enum Level {
LOW,
MEDIUM,
HIGH
};
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
int main() {
enum Level myVar = MEDIUM;
cout << myVar; // Now outputs 50
return 0;
}; //--> 50
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
enum Level {
LOW, // 0
MEDIUM, // 1
HIGH // 2
};
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
// Print the enum variable
cout << myVar;
return 0;
} //--> 1
¶C++ References
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
int main() {
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
return 0;
}
¶ C++ Memory Address
In the example from the previous page, the & operator was used to create a reference variable. But it can also be used to get the memory address of a variable; which is the location of where the variable is stored on the computer.
When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.
To access it, use the & operator, and the result will represent where the variable is stored:
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
int main() {
string food = "Pizza";
cout << &food; // Outputs 0x6dfed4
return 0;
}
¶C++ Pointers
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
int main() {
string food = "Pizza"; // A food variable of type string
string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
return 0;
}
- output
Pizza
0x7ffe29172200
0x7ffe29172200
Tip: There are three ways to declare pointer variables, but the first way is preferred:
- string* mystring; // Preferred
- string *mystring;
- string * mystring;
¶ C++ Dereference
Get Memory Address and Value
We used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator):
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
int main() {
// Write C++ code here
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
return 0;
}
- output
0x7fffb56aad30
Pizza
¶C++ Modify Pointers
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
int main() {
string food = "Pizza";
string* ptr = &food;
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
return 0;
}
- output
Pizza
0x7ffc42c7f720
Pizza
Hamburger
Hamburger
¶C++ Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.
- Syntax
void myFunction() { // void means that the function does not have a return value.
// code to be executed
}
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
// Create a function
// has to bedefined, before it could be called
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
However
// Function declaration
void myFunction(); // it is OK
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
¶C++ Function Parameters
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
¶C++ Default Parameters
You can also use a default parameter value, by using the equals sign (=).
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
¶C++ Multiple Parameters
Inside the function, you can add as many parameters as you want:
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
¶C++ Function Return Values
The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function:
nt myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
¶C++ pass by reference
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
- review
int value = 10;
int *ptr = &value; // &value gets the address of the variable value.
std::cout << ptr; // Outputs the memory address of value.
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
¶C++ Pass Array to a Function
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
- output
10
20
30
40
50
When passing an array to a function, changes to the array in the function affect the original array.
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
myNumbers[4] = myNumbers[0] ;
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
return 0;
}
- output
10
20
30
40
50
10
20
30
40
10
¶Function Overloading
With function overloading, multiple functions can have the same name with different parameters:
Note: Multiple functions can have the same name as long as the number and/or type of parameters are different.
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
nt plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
¶C++ Variable Scope
- error
void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
}
int main() {
myFunction();
// Print the variable x in the main function
cout << x; // out off scope
return 0;
}
¶Global Scope
A variable created outside of a function, is called a global variable and belongs to the global scope.
Global variables are available from within any scope, global and local:
// function will print the local x, and then the code will print the global x:
// Global variable x
int x = 5;
void myFunction() {
// Local variable with the same name as the global variable (x)
int x = 22;
cout << x << "\n"; // Refers to the local variable x
}
int main() {
myFunction();
cout << x; // Refers to the global variable x
return 0;
}
// Global variable x
int x = 5;
void myFunction() {
cout << ++x << "\n"; // Increment the value of x by 1 and print it
}
int main() {
myFunction();
cout << x; // Print the global variable x
return 0;
}
// The value of x is now 6 (no longer 5)
Conclusion
To sum up, use local variables (with good variable names) as much as you can. This will make your code easier to maintain and better to understand. However, you may find global variables when working on existing C++ programs or while collaborating with others. Therefore, it is good to understand how the scope works and how to use it effectively to make sure your code is clear and functional.
¶Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.
A technique of making a function call itself
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
// Function Recursion
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
} // -> output 55