Learn to Code via Tutorials on Repl.it!

← Back to all posts
[2] C++ Made EZ!!!
Bookie0 (6154)

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++
  • Basics of a C++ program
  • Key Terms (like output, input, console, etc.)
  • Comments
  • Output
  • Data Types
  • Variables
    - Declaring Variables
    - Naming Variables
    - Changing Variables
    - Outputing Variable
  • Input
  • Concatenation
  • Operators
  • Comparison Operators
  • Conditionals
    - if
    - else if
    - else
  • Arrays
  • Loops
    - for Loops
    - while Loops
  • Functions
  • Headers
  • Small Programs and Useful Stuff
  • ANSI Escape Codes
  • Links (sources, extras, tutorials)
  • Goodbye World!: End

Hello World: Short History of C++

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.

~ @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:

#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++!

~ @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 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.

int main()
{
	bool boolean1 = true;
	bool boolean2 = false;
}

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.

~ @programmeruser

#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.

~ @EpicGmer007

Note:

If you mean make it compile slower, then yes. But if you mean make it run slower, then no, that's not necessarily true.

~ @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:

#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)

~ from @Nettakrim

Only if the teletype supports true (24 bit) color.

~ from @CodeLongAndPros

You can also \t for making tabs in C++:

cout << "Hello\tWorld!" << endl;

Output:

Hello   World!

And for clearing the screen, use this ANSI escape code to clear the console screen:

cout << "This text won't appear as the console will be cleared!" << endl;
cout << "\033[2J" << endl;

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:

  • pacman
  • battleship
  • choice making game
  • quiz (like harry potter quiz, math quiz, star wars quiz)
  • personality quiz (like which house are you in HP, are you a nerd/jock/popular/idiot etc)
  • tic tac toe
  • uno
  • dice rolling game
  • name/place/idea/story generator
  • text based adventure game
  • simulator (Life sim, cooking sim, teacher sim, fighting sim, etc.)
  • hotel managment game
  • game like Among Us
  • game like Scribble
  • typing test
  • tycoon game (idle factory game, idle miner game, idle city game)
  • ascii art/animation
  • board game (monopoly, uno, risk, game of life, etc)

If you need more ideas, you can just google on the internet "C++ program/game ideas"; here are some results:


Goodbye World!: End

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!

From @DynamicSquid and @Bookie0, good luck and have fun!!!

and stay safe! ;)
Comments
hotnewtop
xxpertHacker (920)

@Bookie0 @DynamicSquid Personal suggestion: how about doing the one thing that no C++ tutorials seem to ever do on Repl.it: explain the difference between statements and expressions, actually explaining where and why semi-colons are needed? It's up to the two of you, of course, but no other C++ tutorial seems to do it, and there's a lot of exceptions if you explain it poorly.

DynamicSquid (4782)

@xxpertHacker oh interesting, might create a separate tutorial for that

zplusfour (901)

@xxpertHacker also bookie wrote ur username wrong

Chewyblockguy (9)

@xxpertHacker a semicolon in most programming languages just tells the computer that there is no more to the script and the next script will be a different statement.

xxpertHacker (920)

@Chewyblockguy Well... usually programming languages aren't composed of scripts...

I'd say that they simply terminate the statement, but then, what qualifies as a statement? Where wouldn't you put a semi-colon? Why not? Of course, I'd have no problem with understanding the differences, but beginners sure don't.

KrazyOrange (27)

Great tutorial! I actually might try some coding in C++ because of this! Maybe make a sequel with more stuff, I really enjoyed this.

Bookie0 (6154)

Thanks! :) good luck! @KrazyOrange idk if a sequel will be made, that’s about all I know with C++, but I’ll be making more tutorials on other Languages/math concepts :)

KrazyOrange (27)

Ooh more tutorials would be great!
@Bookie0

CyanCoding (2172)

Dang, this is super awesome! Love the C++ tutorial!

Bookie0 (6154)

@CyanCoding thank you! also yay you're back on repl.it!!

HahaYes (1861)

Wow this looks super cool. Also why does it look like two different people wrote it, feels like it isn't always Bookie writing

HahaYes (1861)

@Bookie0 Hmm this is really good, we should do C. C rules the world

Bookie0 (6154)

@HahaYes lol idk C tho and I thought you loved C++?

firefish (935)

@HahaYes Oh god. The war's re-started.

firefish (935)

@HahaYes Oh god. The war's re-started.

firefish (935)

@HahaYes Oh god. The war's re-started.

TsunamiOrSumth (555)

Wow! You must have put a lot of time and effort into typing this! Good job!

Nettakrim (691)

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)

Araujocoding (2)

@DynamicSquid and @Bookie0, can I translate for portuguese?

Bookie0 (6154)

@Araujocoding if you want lol ¯\_(ツ)_/¯

Whippingdot (610)

I am not tryina be mean but, there is a typo!!!

😁😁

ThisUserTaken (242)

kewl even though I haven't looked at the tutorial even but just judging on your previous tutorial. rip this has more cycles than my 1 month old tutorial rip.

DynamicSquid (4782)

Just curious, can you guys tell which parts were written by Bookie and which parts were written by me?

Bookie0 (6154)

@DynamicSquid lol easy:

Bookie: something (like trash lol)
Squid: the code, great voice, super jokes, everything good lmfao

(jk)

idk if we can really see the differences, but I guess if one studies the posts we each made and finds out a style, one will be able to find out differences lol ;)

elipie (366)

Suggestion ;)

#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;
    }
		}
}

Could add an else statement for an invalid op.
like:

}else{
  cout << "invalid op :(";
}
fuzzyastrocat (1532)

Nice, this definitely looks like you put a good amount of effort into it! (Though I'll always like C better than C++ :D)

A few things I'd modify though:

Important: remember to add a semi-colen (;) after each line in C++!

This isn't necessarily true. It might confuse someone trying to write a for-loop:

for(int i = 0; i < 10; i ++){ ;

Which is obviously incorrect. I'd rewrite it to say

Important: remember to add a semi-colon (;) after each statement (which is usually each line) in C++!

Also,

No using keywords (eg: if, cout, cin) as the names.

While if can't be used as a variable name, it's perfectly valid to overwrite cout or cin. Even though this isn't good practice and doesn't serve much practical use, I think it's important to make a distinction between keywords and already-defined variable names (variables defined in the headers you've included).

Once again, nice work!

Bookie0 (6154)

@fuzzyastrocat Wow ok thanks for the feedback! :D

A few things I'd modify though:
Important: remember to add a semi-colon (;) after each line in C++!
This isn't necessarily true. It might confuse someone trying to write a for-loop:

Funny tho, when I was rereading the tutorial I saw that and made note of it, and was going to precise it, but forgot. thanks for the reminder!

and for the keywords, didn't know that, I'll also add it. I thought it was like python lol, where you can't use keywords!

thank you again!

fuzzyastrocat (1532)

@Bookie0 Heh, good to know we think alike :D

Well, it is like python, you can't use keywords. You can't assign a variable to the name if or while. But cout and cin aren't keywords, they're just regular old variables defined in the iostream header.

Bookie0 (6154)

@fuzzyastrocat

lol,

well the more you know! :)

xxpertHacker (920)

@fuzzyastrocat

for(int i = 0; i < 10; i ++){ ;

If you think that's bad, think of C++'s old handing bracket style (which I actually still like):

for ( ushort i = 0; i < 10; ++i );
{;
    std::wcout << i << L'\n';
};
fuzzyastrocat (1532)

@xxpertHacker Your example doesn't work in (modern?) C++ since the ; is a null-statement which gets counted as the body of the for-loop.

However, I actually kinda like that style too, since it's consistent. You need to have some consistency — whether that's statements or every line, but not a weird mix.

xxpertHacker (920)

@fuzzyastrocat

Your example doesn't work in (modern?) C++ since the ; is a null-statement which gets counted as the body of the for-loop.

Lmao, yes, that's the point! If you just place a semi-colon after every line, that's what happens, it won't compile since i isn't defined.

CodeLongAndPros (1598)

That feeling when D is better than C++

firefish (935)

@CodeLongAndPros That feeling when Rust is better than D

elipie (366)

@firefish that feeling when python is worse than Rust

zplusfour (901)

@elipie that feeling when Go collect garbage code (like rust or D)
Edit:

CodeLongAndPros (1598)

@ZDev1 "If you don't have garbage collection you can't have a garbage collection error"— Dennis Ritchie, 1964

FlaminHotValdez (611)

awesome c++ tuto finally python is so cliche lol. Also you missed c++ vectors(me practicing for USACO getting pissed off) and sets and maps and...let's not go down that road.

Baconman321 (1092)

HOW DARE YOU SIMPLIFY THE COMPLEXITY OF C++!!!
LOL XD

Baconman321 (1092)

@Bookie0 It is literally compiled right into ASM.

programmeruser (580)

I'm not trying to criticize your tutorial, but I find it strange that my tutorial only got 15 upvotes, while yours got 46 upvotes despite being shorter.

And by "longer" I mean "more in depth."

Bookie0 (6154)

@programmeruser what tutorial? also upvotes don't count..

programmeruser (580)

@Bookie0 https://repl.it/talk/learn/Full-C-Tutorial/77227
Also, I don't care about upvotes, I just find it a little strange.

Bookie0 (6154)

@programmeruser i guess it's "quality, not quantity". Also not sure, but I think we released out tutorial before yours, so maybe they just saw ours first (not sure tho) ;)

CFPS (0)

Using the command "using namespace std;" is very, very bad practise

AJDevelopment (137)

Output: SixBeeps codes
Coder100, CodingCactus, VulcanWM, and HahaYes: the big sad

(edit: no amount of bothering will get me to add @ in front of the names)

AJDevelopment (137)

@Bookie0 why is it that whenever i comment something you reply with

lol

Bookie0 (6154)

@AJDevelopment it's like the language tics; uh, like, so, umm.

lol and lmao are just very common ¯\_(ツ)_/¯ :)

adsarebbbad (215)

how do i print a function with a return statement? for example,

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!\n";
  cout << sum(1, 5);
}

int sum(int x, int y) {
  return x + y;
}

but this doesn't work

Bookie0 (6154)

@adsarebbbad hum for functions you need void before, check out the section on functions for more! ;)

adsarebbbad (215)

oh wait i put the function after the declaration nvm @Bookie0

ebp11 (41)

Wait... ez? ee-zed? I think that ez (in the name of the post) needs to be changed to easy.

Bookie0 (6154)

@ebp11 ez = ee-zee = easy lol
z pronounced american way :)

RoyalCoder1234 (35)

Finally I can learn C++. Never could have understand C++ before seeing this tutorial. Thanks a lot!

Bookie0 (6154)

lol yey! Glad that it could help you! :) @RoyalCoder1234

programmeruser (580)

@Bookie0 decent tutorial. One thing: Use std::getline(std::cin,some_string_variable) instead of std::cin >> some_string_variable. It'll get the whole line instead of ending with the first space. And you should've gone over pointers and references too.

Bookie0 (6154)

@programmeruser decent comment. Thanks for the suggestion tho, I'll add it! :)

xxpertHacker (920)

The ANSI section doesn't have anything to do with C++ :/ ANSI sequences are language-independent, and don't work on Windows.

Bookie0 (6154)

@xxpertHacker yea we just put ANSI escape codes to style color, but for example \n and \t can also be used in python.

and don't work on Windows.

use mac smh lol!

xxpertHacker (920)

@Bookie0 I don't use Windows at all, but it exists, so it shows that ANSI codes are not portable, and have nothing to do with C++, because they would work on Windows.

...but for example \n and \t can also be used in python.

These are just escape characters, \e, \x1b, and \033 are all escape codes, and they all mean the value of the Esc key, but it is only by coincidence that it was the character used for ANSI colors, it has nothing to do with C++, since you can do it in server-side ECMAScript, Python, C, Rust, C++, Java, etc.

xxpertHacker (920)

@Bookie0 Also, I noticed the switch statement wasn't mentioned in this, the "Calculator Program" is a good place to have used it.

Bookie0 (6154)

@xxpertHacker yea, I know they have nothing to do with C++, but I'm just showing them how to use them

xxpertHacker (920)

@programmeruser Have to agree with that, "at least it's not Windows"

xxpertHacker (920)

Created by Bjarne Stroustrup in 1998...

As one who intricately knows everything about C++ better than the back of my hand, I am very iffe about seeing that "1998," maybe that's when it was standardized?

Update: Looking at what Wikipedia says on this:

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.

Oh, yup, I was spot on; might want to update that?

Whippingdot (610)

Maybe I could help?

I have two ideas for the tutorial, so maybe you could add them??:

1. /n

The first idea I had that you could add is when outputting strings to the console using cout, instead of using

>> endl;

at the ending, you can use /n at the end of the string or whenever you want to enter a new line. I said this because it is a quicker way to do start a new line/end a line.

2. References and Pointers

Also maybe you could teach about references and pointers. I know this tutorial is not meant to teach everything about C++ cause there is a lot but these are important. They can be very useful for beginners. The only thing is pointers are pretty confusing (for me included) so you don't have to talk about them.

Note

And just a last note, when adding code using Markdown, can't you type C++ after the `s so it changes the color of the code based on the C++ library. Like:

cout << "This text won't appear colored based on C++" << endl;

can become:

cout << "This text will appear colored based on C++!" << endl;
Whippingdot (610)

Man, I have been writing and editing this post for almost half an hour!

Bookie0 (6154)

@Whippingdot hi, thx for the suggestions, I already had \n in the tutorial
also yea I forgot to add Cpp after the 3 `s

Whippingdot (610)

I searched it on the page but couldn't fine the \n brookie, oh, I must have put /n. Sry. @Bookie0

EpicGamer007 (1693)

I think it would be good if you added a section where it says why prefer C++ over other languages, if I saw this tutorial right now and was a beginner, I personally would not "switch" to C++ because I do not know how C++ is going to make me a better programmer and I do not see where are it's use cases. (It is still good don't get me wrong, your tutorials are always high quality and way better than mine lol)

Edit: I reread it and u say where it is used but I still do not see why it is better than other programming languages in some cases. @DynamicSquid ? can you answer? (Yes, I really am interested)

EpicGamer007 (1693)

This feels longer than my tutorial for some reason 😕

Bookie0 (6154)

lol I think yours is longer¯\_(ツ)_/¯@EpicGamer007

elipie (366)

remeber i said you should learn c++ on discord!! Yay you are super good now! give credit me plz lol You have gotten so good since I said that! What course did u take?

Bookie0 (6154)

@elipie Lol thanks!
can't remember the course tho, think it was something with Lavner

elipie (366)

@Bookie0 cool. To be able to write this tutorial, that means you have really grown overtime!

Bookie0 (6154)

lol yea, important to remember I did it with @DynamicSquid
:)) @elipie

elipie (366)

@Bookie0 yeah. still though :)

elipie (366)

@Bookie0 you wanna make a tutorial with me (idk what to do it on)

elipie (366)

@Bookie0 exactly lol, now I gotta go to class :( i inv u to a repl then we can decide there. lel

Bookie0 (6154)

@elipie sure, also what did u say your name was on discord?

elipie (366)

@Bookie0 KingElij6#6261 i think, unless I changed it, im probs gonna change it back to elipie

firefish (935)

@Bookie0 I'll make a tutorial with you... maybe on Rust