After the Python Tutorial I made here, we decided to make a C++ tutorial together! :D
This is the second tutorial on languages in the series.
This cool tutorial will show you the basics of the language, and these basics can also be used in other sorts of languages (with different syntax of course!).
There will also be examples, with comments explaining what each line does.
At the end, there'll be some extra things like ANSI escape codes, little useful programs, and handy links to good websites.
C++ is a general purpose programming language. Created by Bjarne Stroustrup in 1998,
The C++ programming language was initially standardized in 1998 as ISO/IEC 14882:1998... Before the initial standardization in 1998, C++ was developed by Danish computer scientist Bjarne Stroustrup at Bell Labs since 1979 as an extension of the C language; he wanted an efficient and flexible language similar to C that also provided high-level features for program organization.
it is used for many things, such as game development, operating systems, apps, and many more things.
This is Bjarne Stroustrup:
C++ is generally appreciated because it's a very fast and powerful language. It also allows you "to have a lot of control as to how you use computer resources, so in the right hands its speed and ability to cheaply use resources should be able to surpass other languages".
Let's begin!
(general knowledge of programming recommended)
Basics of a C++ program
Here's a simple C++ program to get you started:
#include <iostream>
int main()
{
std::cout << "Hello World!";
}
Let's break it down. First we have the line #include <iostream>. The first part, #include, tells the compiler to include the following header. A header is basically a bunch of code that does something. The header we're including is iostream, which stands for "input/output". This means with the header, we will be able to use some code that allows us to output things to the console, and also take input from the user.
Next we have the line int main(). Notice the curly brackets as well. This is called a function. Almost all code in C++ will be written inside the main function. (We will get more into functions later.)
And finally, we have the line std::cout << "Hello World!";. std::cout uses the << operator to output something to the console. In this case, it'll output Hello World! to the console. std::cout is also part of the header iostream. Without the header, we wouldn't be able to use it.
You many of also noticed Hello World! is in quotation marks. That means it is a string. We'll talk more about those later.
Important: remember to add a semi-colon (;) after each statement (which is usually each line) in C++!
If you run the code, it should print Hello World! to the console. Yay! You just made your first C++ program!
A quick note though. You may have noticed the std:: in front of the cout. Tht is called a namespace. Those are a pretty advance topic so we'll save them for later. But all you need to know is that some things, like cout, belong to the std (standard) namespace. Think of it as grouping code together. But writing std:: is quite labourious, so we can just use one simple line: using namespace std;. If we include that line at the top, the we can simpily write cout instead of std::cout. Like this:
#include <iostream>
using namespace std; // notice we added this line
int main()
{
cout << "Hello World!";
}
Way easier!
Comments
An important part of code is sharing your work with others, or leaving important notes in your code for yourself. We can achieve this using comments. Comments are completely ignored by the compiler. They're just for you, or anyone else, to read.
Comments come in 2 types, singleline, and multiline. Single comments start with a double slash: //, and what ever comes after that is ignored by the compiler. Mulitline comments start with /*, and end with */, and whatever is between those two, are ignored.
For example:
#include <iostream>
using namespace std;
int main()
{
// this is a comment!
// comments are very useful in helping
// others, and yourself, understand your code
// the line below prints out 'Hello World!'
cout << "Hello World!";
// remember the semicolen!
/*
this is a multiline comment!
notice how it takes up multiple lines!
*/
}
Output
Let's revist cout. cout is short for character output. We already saw that it can print strings. What else? Well, it can basically print just about anything.
#include <iostream>
using namespace std;
int main()
{
cout << "This is a string!"; // strings
cout << 7; // integers
cout << 3.14; // decimals (floats)
}
Notice the numbers did not need quotations around them.
We can also use multiple of << to print different values!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello " << "World!";
cout << "I am " << 2 << " years old...";
}
That will print:
Hello World!I am 2 years old...
Hmm... that's not what we wanted. We wanted a new line inbetween the two sentences, like this:
Hello World!
I am 2 years old...
How can we do that? We can use something called std::endl (which is short for "end line"). And remember, since we're have the line using namespace std, we can simpily write endl.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello " << "World!" << endl; // notice the 'endl'
cout << "I am " << 2 << " years old...";
}
Now this will print:
Hello World!
I am 2 years old...
You can also use \n instead of endl, that way you can put more lines in between output lines:
#include <iostream>
using namespace std;
int main()
{
cout << "New line here\nAnd here\nAnd now more lines\n\n\nBye!";
}
Output:
New line here
And here
And now more lines
Bye!
Variables
In code, storing data is very important. We can store different types of data in C++, numbers, words, letters, booleans (more on that later), etc. Each type of data can be stored in a variable, with each variable being a different type depending on what it's storing.
Declaring Variables
In order to declare a variable, you must follow this syntax:
data_type variableName;
or
data_type variableName = value;
// an example variable that contains a name
string name = "Bob";
There are many data types in C++. The main ones being bool (to store booleans), int (to store integers), float (to store decimals), and std::string (to store strings).
Let's first take a look at how we can store numbers.
int main()
{
int number = 10;
}
So in the example, we've created a variable called number, and gave it a value of 10 using the equals sign. Notice how we gave it a type of int, meaning it can only store integers.
Also notice how we don't have #include <iostream> in the code. That's because we are not using cout.
If we wanted to store decimals:
int main()
{
float decimal = 3.14;
}
Notice how the type changed from int to float.
Noe boolean variables are a little special. They can only store the values true or false. That's it.
Now let's try to create a std::string variable. But in order to do so, we first have to include a different header: string.
#include <string>
using namespace std; // notice how 'string' is also part of the 'std' namespace
int main()
{
string name = "squid";
}
Now you might be wondering why string variables are different from the rest. That's because there's actually no way for a computer to store a string value. It's a complex topic, but basically computers can only store 1s and 0s. Booleans can be turned into 0 for false, and 1 for true, and numbers can be turned into their binary representations. But a string cannot be turned into a number that easily, which is why it's different from the rest.
Naming Variables
A few tips for naming variables:
Variables are used to hold things, so you should try to name your variables accordingly. For example, you won't name a variable holding an age "bananas" or a variable holding a name "thingy".
Also, try to use camelCase in variables: if you have several words in the variables, join them together and capitalize the 1st letters (except the 1st word). Like the tip above, this is not needed, but just makes your code more readable, and easier for someone to look at your code.
Don't start a variable name with a number.
No spaces or special characters.
No using keywords (eg: if, cout, cin) as the names.
If you try to follow those tips, not only will your code run smoothly and without errors, but it will look good and you will be able to read the code faster.
Changing Variables
We can also assign variables different values after we declare them, like this:
int main()
{
int number = 10; // number has a value of 10
number = 5; // number now has a value of 5
}
Common math expressions are also supported for ints and floats.
int main()
{
int num = 5;
num = 5 * (8 + 3);
float dec = 3.14 * 2.71;
dec = dec + 1.2;
}
Outputing Variables
Let's try printing it out using cout!
#include <iostream> // and since we outputing things this time, we have to use this header
using namespace std;
int main()
{
int number = 10;
cout << number; // will output 10
number = 5;
cout << number; // will output 5
}
Input
In C++, you can also use std::cin to get input from the user. std::cin is also part of the std namespace, and is short for character input. To use it, you first have to declare a variable to store the information the user will give you. The type of the variable depends on what information you want to collect.
Use std::getline(std::cin,some_string_variable) instead of std::cin >> some_string_variable. It will get the whole line instead of ending with the first space.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter your name\n> "; // prints for user to enter name
string name;
cin >> name; // asks for the input, and store the input in the string variable
cout << name; // prints the name
}
Output:
Enter your name
> Bookie
Bookie
Ditto for int and floats:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter your age\n> ";
int age;
cin >> age; // asks for the input, and stores the input in the int variable
cout << "You are " << age << " years old";
}
Remember, to use cout and cin, you must write #include <iostream>, otherwise, the code won't work.
String Concatenation
What is string concatenation? String concatenation is when you join/link two strings together using the plus operator. For example the concatenation of "Dynamic" and "Squid" is "DynamicSquid" best concatenation everrrr.
So taking the example from above:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter your name\n> "; // prints for user to enter name
string name; // creates a string variable to store user input
cin >> name;
cout << "You're name is " + name; // concatenates "You're name is " and the variable name
}
Output:
Enter your name
> Bookie
You're name is Bookie
Operators
A symbol or function denoting an operation
Basically operators can be used in math.
List of operators:
+ For adding numbers | Eg: 12 + 89 = 101
- For subtracting numbers | Eg: 65 - 5 = 60
* For multiplying numbers | Eg: 12 * 4 = 48
/ For dividing numbers | Eg: 60 / 5 = 12
% Modulo (divides numbers and returns whats left (remainder)) | Eg: 50 % 30 = 20
These operators can be used for decreasing/increasing variables.
Example:
#include <iostream>
using namespace std;
int main()
{
int x = 12;
x = x + 3;
cout << x; // output: 15
}
You may of noticed the line: x = x + 3. We're basically adding 3 to x. Now there's actually a better way to do that, and that is to use +=:
#include <iostream>
using namespace std;
int main()
{
int x = 12;
x += 3; // x = x + 3
cout << x << endl; // output: 15
}
Notice how we used += to add 3 to x. It also works with any operator: /=, *=, etc.
Now a quick little program showing what you have learnt so far:
#include <iostream>
using namespace std;
/*
program to multiply two integers
read the comments to understand the code
*/
int main()
{
// 2 variables holding numbers 1 and 2
int number1;
int number2;
cout << "Welcome to a program to multiply 2 numbers!\nEnter first number\n> ";
cin >> number1; // asks user for 1st number
cout << "Enter second number\n> ";
cin >> number2; // asks user for 2nd number
int answer = number1 * number2; // makes a variable called answer which is the product of number1 and number2
cout << number1 << " times " << number2 << " = " << answer; // outputs the result
}
Output:
Welcome to a program to multiply 2 numbers!
Enter first number
> 12
Enter second number
> 3
12 times 3 = 36
Comparison Operators
Comparsion operators are for, well, comparing things. They return a boolean value, true or false.
List of comparison operators:
== equal to | Eg: 7 == 7
!= not equal to | Eg: 7 != 8
> bigger than | Eg: 12 > 8
< smaller than | Eg: 7 < 9
>= bigger than or equal to | Eg: 19 >= 19
<= smaller than or equal to | Eg: 1 <= 4
The first two operators can work on any type, as long as it is the same. The rest can only work on numbers.
int main()
{
bool isEqualTo1 = "squid" == "smart"; // false - the two strings are not the same
bool isEqualTo2 = 5 == 5; // true - 5 is equal to 5
bool isGreaterThan = 5 > 6; // false - 5 is not greater than 6
}
These operators are mainly used in conditionals, which is what the next part is talking about!
Conditionals
Conditionals (or statements) allow you to control program flow. That means only do this if that happened, and only do that if this happened.
This is useful for when handling user input. For example is the user enters their age, and it greater than, say, 18, then we can make the program do a certain thing, otherwise, the program can do something else. There are three types of conditionals, if, else if, and else.
if
The if statement takes in a boolean expression, and if that expression is true, then it executes the follow code, otherwise, it just skips it.
#include <iostream>
using namespace std;
int main()
{
cout << "How old are you?\n> ";
int age; // declares variable called age (integer)
cin >> age; // input to get user's age
if (age > 17) // if what the user responded is greater than 17
{
// this code will only run if the user's age is greater than 17
cout << "You are older than 17";
}
}
Output:
How old are you?
> 19
You are older than 17
else if
An else if statement is used with an if statement, and it will only run if the if statement is false.
Taking the program from above, let's add the some else if so that if the user enters other values, the program can output stuff back:
#include <iostream>
using namespace std;
int main()
{
cout << "How old are you?\n> ";
int age; // declares variable called age (integer)
cin >> age; // input to get user's age
if (age > 17) // if what the user responded is greater than 17
{
// this code will only run if the user's age is greater than 17:
cout << "You are older than 17";
}
else if (age < 17)
{
// this code will only run if the user's age is lesser than 17:
cout << "You are younger than 17";
}
}
Output:
How old are you?
> 16
You are younger than 17
Note: remember it's else if not elif! elif is the same thing, except it's used in Python. It will get a little time to get used to it, but you will soon avoid those errors!
else
else is the final of the 2 conditionals; it is used if any of the conditions of the above are not met. Let's make a new program to demonstrate the user of else:
#include <iostream>
#include <string> // remember this because we have strings!
using namespace std;
int main()
{
string adminPassword = "CheezyPassword"; //puts the admin password in a variable (str)
cout << "Enter password\n> ";
string userPassword;
cin >> userPassword; // input to ask user to enter the password
if (adminPassword == userPassword) // will only run if the user enters the correct password
{
cout << "Welcome, Admin!"; // a welcome message, only to the admin
}
else // if the user enters anything different from the password
{
cout << "Wrong password!"; // outputs "Wrong password!"
}
}
Output:
Enter password
> CheezyPassword
Welcome, Admin!
Another output:
Enter password
> idk
Wrong password!
You can also chain together multiple statements (provided that they are in the right order)!
#include <iostream>
using namespace std;
int main()
{
int age = 10;
if (age < 18)
{
cout << "You are under 18";
}
else if (age == 18)
{
cout << "You are 18";
}
else if (age > 18 && age < 200)
{
cout << "You are about 18 but under 200";
}
else
{
cout << "Wow you are very old";
}
}
Notice that we used &&; that's basically like the and keyword, it checks if multiple expressions are met. In this case, else if (age > 18 && age < 200) checks if age is bigger than 18 and age is smaller than 200.
Arrays
Arays are used to store several values of the same type in one place. To declare an array:
#include <iostream>
using namespace std;
int main()
{
// int array holding 5 ints:
int numbers[5] = {1, 5, 6, 10, 200};
// bool array holding three types:
bool booleans[3] = {true, false, true};
}
Breaking it up, first we declare the data type of the array: for this one it's an int. Next, we put the name of the array. The brackets ([]) next to the name of the array contain a number; that number is how many values are inside that array. Next, an equal (=) sign. Finally, we put the values of the array in curly braquets ({}), seperated by commas (,).
Now to output one of the items of the array, we can access it through indexing. Indexes start at 0, meaning that (in the above example) the item 1 has an index of 0, the item 5 will have an index of 2, item 6 will have an index of 2, etc.
We can also make an array containing strings; also here are some shoutouts:
#include <isotream>
#include <string> //because we are putting strings in the array.
using namespace std;
int main()
{
string names[5] = {"Coder100", "CodingCactus", "SixBeeps", "VulcanWM", "HahaYes"};
}
So now to output it, we use cout, and then the name of the list.
#include <iostream>
using namespace std;
int main()
{
// array holding 5 ints:
int numbers[5] = {1, 5, 6, 10, 200};
// indexes: 0 1 2 3 4
// to print the array:
cout << numbers[0];
// will output the item at index 0 = 1
cout << numbers[4];
// will output the item at index 4 = 200
}
Loops
In order to repeat stuff, you can use loops. There are two main types of loops, for and while loops. Let's take a look at while loops.
while Loops
They follow this syntax:
while (condition is true)
{
// do something
} // notice that they also use curly braquets
A more detailed example with a while loop:
#include <iostream>
using namespace std;
int main()
{
int x = 0; // making a variable called x containing 0
while (x < 5) // while x is smaller than 5
{
cout << x << ' '; // will output x (and an empty string for space)
x += 1; // increments (adds one to) x
}
}
Output:
0 1 2 3 4
As the comments say, first we have a int variable called x containing the value of 5. Next, out while loops that says while x (0) is smaller than 5. In that loop, we output the current value of x, and we also add ' ' just for some space in between the values of x. Finally, an important part, we add 1 to x so that the loop will "update". This is called incrementing.
Notice how it never reached 5 because once x because 5, it loop stopped.
for Loops
For loops are similar, but are a little more complicated. They follow this syntax:
for (variable; condition; increment)
{
// do stuff
}
Like this:
#include <iostream>
using namespace std;
int main()
{
for (int x = 0; x < 5; x++) // will run for 5 times
{
cout << x << ' '; // will output x (and an empty string for space)
}
}
Output:
0 1 2 3 4
As you can see, the program does exactly the same as the above one.
So basically, we created a variable inside the loop, gave it a condition, and then incremented the variable.
Let's break for (int x = 0; x < 5; x++) down:
In the for loop, we first have a variable (int) named x which has a initial value 0. Then, after a semi-colen (;), we give it a condition x < 5 which like in the while loops means that the for loop will run as long as x is smaller than 5. Then we have another semi-colen, and the final part is when we increment x with x++. Also:
Notice how it's much cleaner than the code in the while loop, we managed to cut down 3 lines of code in 1 line; we cut down some code.
A for loop is especially handy when it comes to dealing with arrays. We can loop through the array to output each item one by one.
#include <iostream>
using namespace std;
int main()
{
int arr[3] = {1, 2, 3}; // making an array holding 3 items
// when looping through an array, we like to call the variable 'i' but you can call it what you want.
for (int i = 0; i < 3; i++) // notice the for loop
{
cout << arr[i] << ' '; // outputs the item
}
}
Output:
1 2 3
Functions
Functions are used for holding specific blocks of code that can be used several times in your code. The main() that you see in the code is also a function, but it is mandatory to run the code.
Functions are defined outside the main() function. Here's how to make a simple function that asks for the user's name and outputs a message:
#include <iostream>
#include <string>
using namespace std;
void name() // define the function. remember the double parenthesis
{
string userName; // make a variable called userName
cout << "Enter your name\n>";
cin >> userName; // asks user for input
cout << "Hello " << userName << "!"; // outputs a message
}
int main() // in the main
{
name(); // call the function
}
Output:
Enter your name
>amazing squid and bookie
Hello amazing squid and bookie!
The cool thing about functions is that it can be called as many times as you want. Remember to define the function before the main() function!
Now about parameters. Parameters are sort of like variables in the function; they contain information that is passed down to the function so that it can use it. Parameters are put in the parenthesis of the function. Let's modify the function from above to include parameters:
#include <iostream>
#include <string>
using namespace std;
void name(string userName) // define the function. parameter inside the parenthesis, with data type before.
{
cout << "Hello " << userName << "!\n"; // outputs a message to each person, with the \n to make a new line
}
int main() // in the main
{
name("Bobby"); // call the function several times with different arguments
name("Alice");
name("Eraser");
}
Output:
Hello Bobby!
Hello Alice!
Hello Eraser!
As you can see, we've called the functions 3 times with different arguments. So the parameter userName is passed onto the functions where "Bobby", "Alice", and "Eraser" are the arguments.
Headers
Headers are basically a bunch of code that does something. When we include a header in the top of our code, we will be able to use some code. For example #include <iostream> allows us to output things to the console, and also take input from the user.
Random Numbers
We can have random in our programs by having these headers:
#include <iostream> // for input/output
#include <cstdlib> // for srand
#include <ctime> // time
using namespace std;
int main ()
{
srand(time(0)); // to initialize the random seed
int randNumber = rand() % 10 + 1; // generates a random number in a variable called randNumber
cout << randNumber << endl; // outputs that random number
}
Possible Output:
7
So first we have the headers. The second and third ones are new: #include <cstdlib> for the randoms seed and #include <ctime> for generating a different value every time. Next, we have srand(time(0)); to generate a new value every time the code runs.
Next this: int randNumber = rand() % 10;. First there's a variable that we create called randNumber that is an int. Next we have rand() % 10 + 1. The % is the modulo operator. Remember from the operators part: the modulo operator divides numbers and returns whats left (the remainder). For example: 50 % 30 = 20. So you when we do % 10, it means that we have 9 possible outcomes: 1, 2, 3, 4, 5, 6, 7, 8, 9. If you wanted 10 to be in the possible outcomes, just do % 11.
And in the final part of the code, cout << randNumber << endl;, this prints the random number generated, with the endl so that whatever is next is not stuck together.
As you can see, generating numbers in C++ is a bit harder than in Python.
We can also use this to pick a random index number to randomly select an item out of an array (using a previous one), like so:
#include <iostream> // for input/output
#include <string> // for strings
#include <cstdlib> // for srand
#include <ctime> // time
using namespace std;
int main ()
{
srand(time(0)); // to initialize the random
string names[5] = {"Coder100", "CodingCactus", "SixBeeps", "VulcanWM", "HahaYes"}; // an array holding 5 values
int randIndex = rand() % 5; // generates a random number in a variable called randIndex
cout << names[randIndex] << " codes!" << endl; // outputs random array item with a message
}
Possible Output:
SixBeeps codes!
The code is largly the same as the random number generator, except that we've added the array names and we've changed the output. We generate a random number between 1 and 5 (because there are 5 possible items). Then we just output an item of the array using index accessing. Since the index number is random, we will have a random output!
Math
There's also a header for math! It's called cmath, and it provides some common functions to aid with mathematical calculations.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// absolute value
cout << abs(-5) << endl;
// max and min values
cout << max(2, 3) << " " << min(5, 7) << endl;
// exponent (3 to the power of 6)
cout << pow(3, 6) << endl;
}
Output:
5
3 5
729
Because the absolute value of -5 is 5, max of 2 and 3 is 3, min of 5 and 7 is 5, and 3^6 = 729.
time
We can use time in out C++ programs to wait a certain number of milliseconds, then carry on with the program. We'll be using #include <chrono> and #include <thread>:
#include <iostream>
#include <chrono> // for the sleep
#include <thread> // also for the sleep
using namespace std;
int main()
{
cout << "Hello! Next message in 2 seconds!\n\n";
this_thread::sleep_for(std::chrono::seconds(2)); // waits 2 seconds (2 seconds)
cout << "2 seconds later, we're back!";
}
Output:
Hello! Next message in 2 seconds!
2 seconds later, we're back!
And in between those two messages, there is 2 seconds that pass. Remember to precise how long to wait in milliseconds, 1 second = 1000 milliseconds.
Though I think that it is important to point out that adding more libs(more #include's) in a program will make it slower because that is also compiled.
Here will be some small useful programs that you can use in your programs:
Countdown program
A countdown program that counts down from a number that the user enters. We're also going to be using the sleep from the previous program to wait 1 second between each count, like a real program:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main()
{
int countdownFrom; // where the count starts
cout << "Countdown from where?\n";
cin >> countdownFrom; // gets input from the user
while (countdownFrom > -1) // while loop to run until the countdown reaches 0
{
this_thread::sleep_for(std::chrono::seconds(1)); // waits 1 second between each number
cout << "We're at " << countdownFrom << "!\n"; // displays what number the program is at
countdownFrom -= 1; // takes 1 away from the count
}
}
Output:
Countdown from where?
13
We're at 13!
We're at 12!
We're at 11!
We're at 10!
We're at 9!
We're at 8!
We're at 7!
We're at 6!
We're at 5!
We're at 4!
We're at 3!
We're at 2!
We're at 1!
We're at 0!
And in between each We're at [number] the program waits one second.
Calculator Program
#include <iostream>
using namespace std;
int main()
{
while (true)
{
cout << "Enter an operator (+, -, *, /):";
char op;
cin >> op; // asks user which operator
cout << "Enter your first number: ";
float num1;
cin >> num1; // asks user for 1st number
cout << "Enter your second number: ";
float num2;
cin >> num2; // asks user for 2nd number
cout << "The result is: ";
// conditionals
if (op == '+') // if the operator is +
{
cout << num1 + num2 << endl;
}
else if (op == '-') // if the operator is -
{
cout << num1 - num2 << endl;
}
else if (op == '*') // if the operator is *
{
cout << num1 * num2 << endl;
}
else if (op == '/') // if the operator is /
{
cout << num1 / num2 << endl;
}
}
}
Possible output:
Enter an operator (+, -, *, /):/
Enter your first number: 10
Enter your second number: 2.5
The result is: 4
Enter an operator (+, -, *, /):-
Enter your first number: 25
Enter your second number: 6
The result is: 19
Enter an operator (+, -, *, /):
And it will always keep on going due to the while (true) loop.
Slowprint
Slowprint is very useful in your programs, it's for outputting chars one by one, each seperated by a number of seconds you can set.
#include <iostream>
#include <string>
#include <thread> // for the slowprint
#include <chrono> // for the time (also for slowprint)
using namespace std;
void sp(const string& message, unsigned int millis_per_char=30) // putting the slowprint in a function so we can use it when we need to
{
for (const char c : message) // for loop
{
// outputs the letter
cout << c << flush;
// sleeps for a set period of milliseonds (30 in this case)
this_thread::sleep_for(chrono::milliseconds(millis_per_char));
}
}
int main(int argc, char ** argv) // need those for the slowprint to work
{
// will output these messages slowprinted
sp("Hello World!\n\n");
sp("This is being outputted 1 char at a time with an interval of 30 milliseconds!");
}
Output:
Hello World!
This is being outputted 1 char at a time with an interval of 30 milliseconds!
So the code for the slowprint is kinda complicated, so we won't really go on it much. But basically, we put the slowprint in a function, this is so we can use it whenever we want/need to. We use a for loop so that it loops through every character (char) in the message, and we output that char. Next, the program waits for a period of milliseconds, 30 in this case, that we can set in the function arguments.
Then in the main() function, we also have some arguments. And finally, we use sp("message here") to slowprint what we want. Again, the code is more complicated, but feel free to copy this useful slowprint and use it in your programs!
ANSI Escapes Codes
Now you might be wondering, how can I change the colour of the console text? Squids can chnage colour, so why can't the console? Well you actually can!
There's something called an ANSI code. It let's you specify what colour your text should be! You can use it like this:
cout << "\033[COLOUR_CODEm" << "This text will be coloured!";
Notice how it begins with \033[, and ends with m. Here are the colour codes, for coloring text and the background of the text:
Notice how it's only a number. So for example, if you want red text, you would do something like this:
cout << "\033[31m" << "This text is red" << endl;
Output:
Or if we want a background of bright cyan:
cout << "\033[106m" << "This text has a background of bright cyan" << endl;
Output:
We can also mix and match them! Here's a fun combo using bright yellow background, green background, blue text, and bright magenta text. We'll also use reset to reset the color back to the default (no background color and white plain text):
cout << "\033[103m" << "\033[34m" << "Wow" << "\033[0m" << " back to default" << "\033[102m" << "\033[95m" << " So cool!" << "\033[0m" << endl;
Output:
you can also specify RGB values for ansi escape sequences this can be done with \033[38;2;<r>;<g>;<b>m you can also set the RGB of the background using \033[48;2;<r>;<g>;<b>m (ive used ansi escape sequences alot)
Well, that's about all! You've mastered the basics of C++. These concepts (conditionals, variables, functions, etc.) can be applied to other languages too.
Your journey only begins here, keep learning and have fun coding!
Howdy y'all!
Welcome to a C++ Tutorial, made by *drumroll please...
@DynamicSquid and @Bookie0!
After the Python Tutorial I made here, we decided to make a C++ tutorial together! :D
This is the second tutorial on languages in the series.
This cool tutorial will show you the basics of the language, and these basics can also be used in other sorts of languages (with different syntax of course!).
There will also be examples, with comments explaining what each line does.
At the end, there'll be some extra things like
ANSI
escape codes, little useful programs, and handy links to good websites.Now let's start!
We shall be covering...
Hello World
: Short History of C++- Declaring Variables
- Naming Variables
- Changing Variables
- Outputing Variable
-
if
-
else if
-
else
-
for
Loops-
while
LoopsANSI
Escape CodesGoodbye World!
: EndHello World
: Short History of C++C++ is a general purpose programming language. Created by Bjarne Stroustrup in 1998,
~ @xxxpertHacker (Wikipedia)
it is used for many things, such as game development, operating systems, apps, and many more things.
This is Bjarne Stroustrup:
C++ is generally appreciated because it's a very fast and powerful language. It also allows you "to have a lot of control as to how you use computer resources, so in the right hands its speed and ability to cheaply use resources should be able to surpass other languages".
Let's begin!
(general knowledge of programming recommended)
Basics of a C++ program
Here's a simple C++ program to get you started:
Let's break it down. First we have the line
#include <iostream>
. The first part,#include
, tells the compiler to include the following header. A header is basically a bunch of code that does something. The header we're including isiostream
, which stands for "input/output". This means with the header, we will be able to use some code that allows us to output things to the console, and also take input from the user.Next we have the line
int main()
. Notice the curly brackets as well. This is called a function. Almost all code in C++ will be written inside themain
function. (We will get more into functions later.)And finally, we have the line
std::cout << "Hello World!";
.std::cout
uses the<<
operator to output something to the console. In this case, it'll outputHello World!
to the console.std::cout
is also part of the headeriostream
. Without the header, we wouldn't be able to use it.You many of also noticed
Hello World!
is in quotation marks. That means it is a string. We'll talk more about those later.Important: remember to add a semi-colon (;) after each statement (which is usually each line) in C++!
~ @fuzzyastrocat
If you run the code, it should print
Hello World!
to the console. Yay! You just made your first C++ program!A quick note though. You may have noticed the
std::
in front of thecout
. Tht is called a namespace. Those are a pretty advance topic so we'll save them for later. But all you need to know is that some things, likecout
, belong to thestd
(standard) namespace. Think of it as grouping code together. But writingstd::
is quite labourious, so we can just use one simple line:using namespace std;
. If we include that line at the top, the we can simpily writecout
instead ofstd::cout
. Like this:Way easier!
Comments
An important part of code is sharing your work with others, or leaving important notes in your code for yourself. We can achieve this using comments. Comments are completely ignored by the compiler. They're just for you, or anyone else, to read.
Comments come in 2 types, singleline, and multiline. Single comments start with a double slash:
//
, and what ever comes after that is ignored by the compiler. Mulitline comments start with/*
, and end with*/
, and whatever is between those two, are ignored.For example:
Output
Let's revist
cout
.cout
is short for character output. We already saw that it can print strings. What else? Well, it can basically print just about anything.Notice the numbers did not need quotations around them.
We can also use multiple of
<<
to print different values!That will print:
Hmm... that's not what we wanted. We wanted a new line inbetween the two sentences, like this:
How can we do that? We can use something called
std::endl
(which is short for "end line"). And remember, since we're have the lineusing namespace std
, we can simpily writeendl
.Now this will print:
You can also use
\n
instead ofendl
, that way you can put more lines in between output lines:Output:
Variables
In code, storing data is very important. We can store different types of data in C++, numbers, words, letters, booleans (more on that later), etc. Each type of data can be stored in a variable, with each variable being a different type depending on what it's storing.
Declaring Variables
In order to declare a variable, you must follow this syntax:
There are many data types in C++. The main ones being
bool
(to store booleans),int
(to store integers),float
(to store decimals), andstd::string
(to store strings).Let's first take a look at how we can store numbers.
So in the example, we've created a variable called
number
, and gave it a value of10
using the equals sign. Notice how we gave it a type ofint
, meaning it can only store integers.Also notice how we don't have
#include <iostream>
in the code. That's because we are not usingcout
.If we wanted to store decimals:
Notice how the type changed from
int
tofloat
.Noe boolean variables are a little special. They can only store the values
true
orfalse
. That's it.Now let's try to create a
std::string
variable. But in order to do so, we first have to include a different header:string
.Now you might be wondering why string variables are different from the rest. That's because there's actually no way for a computer to store a string value. It's a complex topic, but basically computers can only store 1s and 0s. Booleans can be turned into 0 for false, and 1 for true, and numbers can be turned into their binary representations. But a string cannot be turned into a number that easily, which is why it's different from the rest.
Naming Variables
A few tips for naming variables:
Variables are used to hold things, so you should try to name your variables accordingly. For example, you won't name a variable holding an age "bananas" or a variable holding a name "thingy".
Also, try to use camelCase in variables: if you have several words in the variables, join them together and capitalize the 1st letters (except the 1st word). Like the tip above, this is not needed, but just makes your code more readable, and easier for someone to look at your code.
Don't start a variable name with a number.
No spaces or special characters.
No using keywords (eg:
if
,cout
,cin
) as the names.If you try to follow those tips, not only will your code run smoothly and without errors, but it will look good and you will be able to read the code faster.
Changing Variables
We can also assign variables different values after we declare them, like this:
Common math expressions are also supported for
int
s andfloat
s.Outputing Variables
Let's try printing it out using
cout
!Input
In C++, you can also use
std::cin
to get input from the user.std::cin
is also part of thestd
namespace, and is short for character input. To use it, you first have to declare a variable to store the information the user will give you. The type of the variable depends on what information you want to collect.~ @programmeruser
Output:
Ditto for
int
andfloats
:Remember, to use
cout
andcin
, you must write#include <iostream>
, otherwise, the code won't work.String Concatenation
What is string concatenation? String concatenation is when you join/link two strings together using the plus operator. For example the concatenation of "Dynamic" and "Squid" is "DynamicSquid"
best concatenation everrrr.So taking the example from above:
Output:
Operators
A symbol or function denoting an operation
Basically operators can be used in math.
List of operators:
+
For adding numbers | Eg: 12 + 89 = 101-
For subtracting numbers | Eg: 65 - 5 = 60*
For multiplying numbers | Eg: 12 * 4 = 48/
For dividing numbers | Eg: 60 / 5 = 12%
Modulo (divides numbers and returns whats left (remainder)) | Eg: 50 % 30 = 20These operators can be used for decreasing/increasing variables.
Example:
You may of noticed the line:
x = x + 3
. We're basically adding 3 tox
. Now there's actually a better way to do that, and that is to use+=
:Notice how we used
+=
to add 3 tox
. It also works with any operator:/=
,*=
, etc.Now a quick little program showing what you have learnt so far:
Output:
Comparison Operators
Comparsion operators are for, well, comparing things. They return a boolean value,
true
orfalse
.List of comparison operators:
==
equal to | Eg: 7 == 7!=
not equal to | Eg: 7 != 8>
bigger than | Eg: 12 > 8<
smaller than | Eg: 7 < 9>=
bigger than or equal to | Eg: 19 >= 19<=
smaller than or equal to | Eg: 1 <= 4The first two operators can work on any type, as long as it is the same. The rest can only work on numbers.
These operators are mainly used in conditionals, which is what the next part is talking about!
Conditionals
Conditionals (or statements) allow you to control program flow. That means only do this if that happened, and only do that if this happened.
This is useful for when handling user input. For example is the user enters their age, and it greater than, say,
18
, then we can make the program do a certain thing, otherwise, the program can do something else. There are three types of conditionals,if
,else if
, andelse
.if
The
if
statement takes in a boolean expression, and if that expression istrue
, then it executes the follow code, otherwise, it just skips it.Output:
else if
An
else if
statement is used with anif
statement, and it will only run if theif
statement is false.Taking the program from above, let's add the some
else if
so that if the user enters other values, the program can output stuff back:Output:
Note: remember it's
else if
notelif
!elif
is the same thing, except it's used in Python. It will get a little time to get used to it, but you will soon avoid those errors!else
else
is the final of the 2 conditionals; it is used if any of the conditions of the above are not met. Let's make a new program to demonstrate the user ofelse
:Output:
Another output:
You can also chain together multiple statements (provided that they are in the right order)!
Notice that we used
&&
; that's basically like theand
keyword, it checks if multiple expressions are met. In this case,else if (age > 18 && age < 200)
checks ifage
is bigger than18
andage
is smaller than200
.Arrays
Arays are used to store several values of the same type in one place. To declare an array:
Breaking it up, first we declare the data type of the array: for this one it's an
int
. Next, we put the name of the array. The brackets ([]
) next to the name of the array contain a number; that number is how many values are inside that array. Next, an equal (=
) sign. Finally, we put the values of the array in curly braquets ({}
), seperated by commas (,
).Now to output one of the items of the array, we can access it through indexing. Indexes start at 0, meaning that (in the above example) the item
1
has an index of0
, the item5
will have an index of2
, item6
will have an index of2
, etc.We can also make an array containing
strings
; also here are some shoutouts:So now to output it, we use
cout
, and then the name of the list.Loops
In order to repeat stuff, you can use loops. There are two main types of loops,
for
andwhile
loops. Let's take a look at while loops.while
LoopsThey follow this syntax:
A more detailed example with a
while
loop:Output:
As the comments say, first we have a
int
variable calledx
containing the value of 5. Next, outwhile
loops that says whilex
(0) is smaller than 5. In that loop, we output the current value ofx
, and we also add' '
just for some space in between the values ofx
. Finally, an important part, we add 1 tox
so that the loop will "update". This is called incrementing.Notice how it never reached 5 because once
x
because 5, it loop stopped.for
LoopsFor loops are similar, but are a little more complicated. They follow this syntax:
Like this:
Output:
As you can see, the program does exactly the same as the above one.
So basically, we created a variable inside the loop, gave it a condition, and then incremented the variable.
Let's break
for (int x = 0; x < 5; x++)
down:In the
for
loop, we first have a variable (int
) namedx
which has a initial value 0. Then, after a semi-colen (;
), we give it a conditionx < 5
which like in thewhile
loops means that thefor
loop will run as long asx
is smaller than 5. Then we have another semi-colen, and the final part is when we incrementx
withx++
. Also:Notice how it's much cleaner than the code in the
while
loop, we managed to cut down 3 lines of code in 1 line; we cut down some code.A
for
loop is especially handy when it comes to dealing with arrays. We can loop through the array to output each item one by one.Output:
Functions
Functions are used for holding specific blocks of code that can be used several times in your code. The
main()
that you see in the code is also a function, but it is mandatory to run the code.Functions are defined outside the
main()
function. Here's how to make a simple function that asks for the user's name and outputs a message:Output:
The cool thing about functions is that it can be called as many times as you want. Remember to define the function before the
main()
function!Now about parameters. Parameters are sort of like variables in the function; they contain information that is passed down to the function so that it can use it. Parameters are put in the parenthesis of the function. Let's modify the function from above to include parameters:
Output:
As you can see, we've called the functions 3 times with different arguments. So the parameter
userName
is passed onto the functions where "Bobby", "Alice", and "Eraser" are the arguments.Headers
Headers are basically a bunch of code that does something. When we include a header in the top of our code, we will be able to use some code. For example
#include <iostream>
allows us to output things to the console, and also take input from the user.Random Numbers
We can have random in our programs by having these headers:
Possible Output:
So first we have the headers. The second and third ones are new:
#include <cstdlib>
for the randoms seed and#include <ctime>
for generating a different value every time. Next, we havesrand(time(0));
to generate a new value every time the code runs.Next this:
int randNumber = rand() % 10;
. First there's a variable that we create calledrandNumber
that is anint
. Next we haverand() % 10 + 1
. The%
is the modulo operator. Remember from the operators part: the modulo operator divides numbers and returns whats left (the remainder). For example: 50 % 30 = 20. So you when we do% 10
, it means that we have 9 possible outcomes:1, 2, 3, 4, 5, 6, 7, 8, 9.
If you wanted 10 to be in the possible outcomes, just do% 11
.And in the final part of the code,
cout << randNumber << endl;
, this prints the random number generated, with theendl
so that whatever is next is not stuck together.As you can see, generating numbers in C++ is a bit harder than in Python.
We can also use this to pick a random index number to randomly select an item out of an array (using a previous one), like so:
Possible Output:
The code is largly the same as the random number generator, except that we've added the array
names
and we've changed the output. We generate a random number between 1 and 5 (because there are 5 possible items). Then we just output an item of the array using index accessing. Since the index number is random, we will have a random output!Math
There's also a header for math! It's called
cmath
, and it provides some common functions to aid with mathematical calculations.Output:
Because the absolute value of
-5
is5
, max of2
and3
is3
, min of5
and7
is5
, and3^6 = 729
.time
We can use time in out C++ programs to wait a certain number of milliseconds, then carry on with the program. We'll be using
#include <chrono>
and#include <thread>
:Output:
And in between those two messages, there is 2 seconds that pass. Remember to precise how long to wait in milliseconds, 1 second = 1000 milliseconds.
~ @EpicGmer007
Note:
~ @fuzzyastrocat
Small programs
Here will be some small useful programs that you can use in your programs:
Countdown program
A countdown program that counts down from a number that the user enters. We're also going to be using the
sleep
from the previous program to wait 1 second between each count, like a real program:Output:
And in between each
We're at [number]
the program waits one second.Calculator Program
Possible output:
And it will always keep on going due to the
while (true)
loop.Slowprint
Slowprint is very useful in your programs, it's for outputting chars one by one, each seperated by a number of seconds you can set.
Output:
So the code for the slowprint is kinda complicated, so we won't really go on it much. But basically, we put the slowprint in a function, this is so we can use it whenever we want/need to. We use a
for
loop so that it loops through every character (char
) in the message, and we output thatchar
. Next, the program waits for a period of milliseconds, 30 in this case, that we can set in the function arguments.Then in the
main()
function, we also have some arguments. And finally, we usesp("message here")
to slowprint what we want. Again, the code is more complicated, but feel free to copy this useful slowprint and use it in your programs!ANSI
Escapes CodesNow you might be wondering, how can I change the colour of the console text? Squids can chnage colour, so why can't the console? Well you actually can!
There's something called an
ANSI
code. It let's you specify what colour your text should be! You can use it like this:Notice how it begins with
\033[
, and ends withm
. Here are the colour codes, for coloring text and the background of the text:Notice how it's only a number. So for example, if you want red text, you would do something like this:
Output:
Or if we want a background of bright cyan:
Output:
We can also mix and match them! Here's a fun combo using bright yellow background, green background, blue text, and bright magenta text. We'll also use reset to reset the color back to the default (no background color and white plain text):
Output:
~ from @Nettakrim
~ from @CodeLongAndPros
You can also
\t
for making tabs in C++:Output:
And for clearing the screen, use this
ANSI
escape code to clear the console screen:Output:
(Nothing as the console screen is cleared lol!)
Links
Here are some good links for tutorials to learn or improve your C++:
And some videos, ranging from 1 hour to 9 hours:
Our sources come from those link above, as well as Stackoverflow.
And if you're interested in finding a C++ book, you can check out a list here.
If you want some ideas for projects, check these out:
If you need more ideas, you can just google on the internet "C++ program/game ideas"; here are some results:
Goodbye World!
: EndWell, that's about all! You've mastered the basics of C++. These concepts (conditionals, variables, functions, etc.) can be applied to other languages too.
Your journey only begins here, keep learning and have fun coding!
From @DynamicSquid and @Bookie0, good luck and have fun!!!
and stay safe! ;)
@Coder100 this is cpp not js