Index: Glossary
Index: Glossary
BASIC CONCEPTS
What is C++
Hello, World!
Getting the tools
Printing a text
Comments
Variables
Working with variables
More on variables
Basic arithmetic
Assignment and increment operators
CONDITIONAL AND LOOPS
The if statement
The else statement
The while loop
Using a while loop
The for loop
The dowhile loop
The switch statement
Logical operators
DATA TYPES, ARRAYS, POINTERS
Introduction to data types
Int, float, double
String, char, bool
Variable naming rules
Arrays
Using arrays in loop
Arrays in calculations
Multi-dimensional arrays
Introduction to pointers
More on pointers
Dynamic memory
The sizeof() operator
FUNCTIONS
Introduction to functions
Function parameters
Functions with multiple parameters
The rand() function
Default arguments
Function overloading
Recursion
Passing arrays to functions
Pass by reference with pointers
CLASSES AND OBJECTS
What is an object
What is a class
Example of a class
Abstraction
Encapsulation Example of encapsulation
Constructors
MORE ON CLASSES
INHERITANCE & POLYMORPHISM
TEMPLATES, EXCEPTIONS AND FILES
GLOSSARY
<iostream> defines the standard stream objects that input and output data
character a single letter or symbol
cin used to read from the standard input device, which is usually the keyboard
cout used to write output to the standard output, usually the screen
endl writes a new line to output
int used to declare an integer value
integer whole number
BASIC CONCEPTS
What is C++
C++ is a general-purpose programming language.
C++ is used to create computer programs. Anything from art applications, music players and even video games!
C++ was derived from C, and is largely based on it.
Hello, World!
A C++ program is a collection of commands or statements.
Below is a simple code that has "Hello world!" as its output.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!";
return 0;
}
Go through the wizard, making sure that C++ is selected as the language.
Give your project a name and specify a folder to save it to.
Click on the "Build and Run" icon in the toolbar to compile and run the program.
Congratulations! You just compiled and ran your first C++ program!
You can run, save, and share your C++ codes on our Code Playground, without installing any additional software.
Reference this lesson if you need to install the software on your computer.
Printing a text
You can add multiple insertion operators after cout.
cout << "This " << "is " << "awesome!";
Result:
The cout operator does not insert a line break at the end of the output.
One way to print two lines is to use the endl manipulator, which will put in a line break.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
cout << "I love programming!";
return 0;
}
The endl manipulator moves down to a new line to print the second text.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world! \n";
cout << "I love programming!";
return 0;
}
Result:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world! \n\n";
cout << "I love programming!";
return 0;
}
Result:
Using a single cout statement with as many instances of \n as your program requires will print out multiple lines of
text.
#include <iostream>
using namespace std;
int main()
{
cout << " Hello \n world! \n I \n love \n programming!";
return 0;
}
Result:
Comments
Comments are explanatory statements that you can include in the C++ code to explain what the code is doing.
The compiler ignores everything that appears in the comment, so none of that information shows in the result.
A comment beginning with two slashes (//) is called a single-line comment. The slashes tell the compiler to ignore
everything that follows, until the end of the line.
For example:
#include <iostream>
using namespace std;
int main()
{
// prints "Hello world"
cout << "Hello world!";
return 0;
}
When the above code is compiled, it will ignore the // prints "Hello world" statement and will produce the following
result:
Comments that require multiple lines begin with /* and end with */
You can place them on the same line or insert one or more lines between them.
/* This is a comment */
Comments can be written anywhere, and can be repeated any number of times throughout the code.
Within a comment marked with /* and */, // characters have no special meaning, and vice versa. This allows you to
"nest" one comment type within the other.
Adding comments to your code is a good practice. It facilitates a clear understanding of the code for you and for
others who read it.
Variables
Creating a variable reserves a memory location, or a space in memory for storing values. The compiler requires that
you provide a data type for each variable you declare.
C++ offer a rich assortment of built-in as well as user defined data types.
Integer, a built-in type, represents a whole number value. Define integer using the keyword int.
C++ requires that you specify the type and the identifier for each variable defined.
An identifier is a name for a variable, function, class, module, or any other user-defined item. An identifier starts
with a letter (A-Z or a-z) or an underscore (_), followed by additional letters, underscores, and digits (0 to 9).
For example, define a variable called myVariable that can hold integer values as follows:
int myVariable = 10;
Now, let's assign a value to the variable and print it.
#include <iostream>
using namespace std;
int main()
{
int myVariable = 10;
cout << myVariable;
return 0;
}
// Outputs 10
The C++ programming language is case-sensitive, so myVariable and myvariable are two different
identifiers.
Define all variables with a name and a data type before using them in a program. In cases in which you have multiple
variables of the same type, it's possible to define them in one declaration, separating them with commas.int a, b;
// defines two variables of type int
A variable can be assigned a value, and can be used to perform operations.
For example, we can create an additional variable called sum, and add two variables together.
int a = 30;
int b = 15;
int sum = a + b;
// Now sum equals 45
#include <iostream>
using namespace std;
int main()
{
int a = 30;
int b = 12;
int sum = a + b;
return 0;
}
//Outputs 42
Always keep in mind that all variables must be defined with a name and a data type before they can be used.
a = 10;
b = 3;
To enable the user to input a value, use cin in combination with the extraction operator (>>). The variable containing
the extracted data follows the operator.
The following example shows how to accept user input and store it in the num variable:
int num;
cin >> num;
As with cout, extractions on cin can be chained to request more than one input in a single statement: cin >> a >> b;
The following program prompts the user to input a number and stores it in the variable a:
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Please enter a number \n";
cin >> a;
return 0;
}
When the program runs, it displays the message "Please enter a number", and then waits for the user to enter a
number and press Enter, or Return.
The entered number is stored in the variable a.
The program will wait for as long as the user needs to type in a number.
You can accept user input multiple times throughout the program:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
return 0;
}
Let's create a program that accepts the input of two numbers and prints their sum.
#include <iostream>
using namespace std;
int main()
{
int a, b;
int sum;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
sum = a + b;
cout << "Sum is: " << sum << endl;
return 0;
}
More on variables
Specifying the data type is required just once, at the time when the variable is declared.
After that, the variable may be used without referring to the data type.
int a;
a = 10;
Specifying the data type for a given variable more than once results in a syntax error.
A variable's value may be changed as many times as necessary throughout the program.
For example:
int a = 100;
a = 50;
cout << a;
// Outputs 50
Basic arithmetic
C++ supports these arithmetic operators.
The addition operator adds its operands together.
int x = 40 + 60;
cout << x;
// Outputs 100
The subtraction operator subtracts one operand from the other.
int x = 100 - 60;
cout << x;
//Outputs 40
The multiplication operator multiplies its operands.
int x = 5 * 6;
cout << x;
//Outputs 30
The division operator divides the first operand by the second. Any remainder is dropped in order to return an integer
value.
Example:
int x = 10 / 3;
cout << x;
// Outputs 3
If one or both of the operands are floating point values, the division operator performs floating point division.
Dividing by 0 will crash your program.
The modulus operator (%) is informally known as the remainder operator because it returns the remainder after an
integer division.
For example:
int x = 25 % 7;
cout << x;
// Outputs 4
Operator precedence determines the grouping of terms in an expression, which affects how an expression is
evaluated. Certain operators take higher precedence over others; for example, the multiplication operator has higher
precedence over the addition operator.
For example:
int x = 5+2*2;
cout << x;
// Outputs 9
The program above evaluates 2*2 first, and then adds the result to 5.
As in mathematics, using parentheses alters operator precedence.
int x = (5 + 2) *2;
cout << x;
// Outputs 14
Parentheses force the operations to have higher precedence. If there are parenthetical expressions nested within
one another, the expression within the innermost parentheses is evaluated first.
If none of the expressions are in parentheses, multiplicative (multiplication, division, modulus) operators will be
evaluated before additive (addition, subtraction) operators.
Assignment operators
The simple assignment operator (=) assigns the right side to the left side.
C++ provides shorthand operators that have the capability of performing an operation and an assignment at the
same time.
For example:
int x = 10;
x += 4; // equivalent to x = x + 4
x -= 5; // equivalent to x = x 5
The same shorthand syntax applies to the multiplication, division, and modulus operators.
x *= 3; // equivalent to x = x * 3
x /= 2; // equivalent to x = x / 2
x %= 4; // equivalent to x = x % 4
The increment operator is used to increase an integer's value by one, and is a commonly used C++ operator.
x++; //equivalent to x = x + 1
For example:
int x = 11;
x++;
cout << x;
//Outputs 12
The increment operator has two forms, prefix and postfix.
++x; //prefix
x++; //postfix
Prefix increments the value, and then proceeds with the expression.
Postfix evaluates the expression and then performs the incrementing.
Prefix example:
x = 5;
y = ++x;
// x is 6, y is 6
Postfix example:
x = 5;
y = x++;
// x is 6, y is 5
The prefix example increments the value of x, and then assigns it to y.
The postfix example assigns the value of x to y, and then increments it.
The decrement operator (--) works in much the same way as the increment operator, but instead of increasing the
value, it decreases it by one.
--x; // prefix
x--; // postfix
For example:
if (7 > 4) {
cout << "Yes";
}
// Outputs "Yes"
The if statement evaluates the condition (7>4), finds it to be true, and then executes the cout statement.
If we change the greater operator to a less than operator (7<4), the statement will not be executed and nothing will
be printed out.
A condition specified in an if statement does not require a semicolon.
Additional relational operators:
Example:
if (10 == 10) {
cout << "Yes";
}
// Outputs "Yes"
The not equal to operator evaluates the operands, determines whether or not they are equal. If the operands are not
equal, the condition is evaluated to true.
For example:
if (10 != 10) {
cout << "Yes";
}
The above condition evaluates to false and the block of code is not executed.
You can use relational operators to compare variables in the if statement.
For example:
int a = 55;
int b = 33;
if (a > b) {
cout << "a is greater than b";
}
In all previous examples only one statement was used inside the if/else statement, but you may include as many
statements as you want.
For example:
int mark = 90;
/* Outputs
Congratulations!
You passed.
You are awesome!
*/
/*Outputs
You passed.
Perfect!
*/
/* Outputs
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
*/
The example above declares a variable equal to 1 (int num = 1).
The while loop checks the condition (num < 6), and executes the statements in its body, which increment the value
of num by one each time the loop runs.
After the 5th iteration, num becomes 6, and the condition is evaluated to false, and the loop stops running.
The increment value can be changed. If changed, the number of times the loop is run will change, as well.
int num = 1;
while (num < 6) {
cout << "Number: " << num << endl;
num = num + 3;
}
/* Outputs
Number: 1
Number: 4
*/
Without a statement that eventually evaluates the loop condition to false, the loop will continue indefinitely.
Using a while loop
The increment or decrement operators can be used to change values in the loop.
For example:
int num = 1;
while (num < 6) {
cout << "Number: " << num << endl;
num++;
}
/* Outputs
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
*/
num++ is equivalent to num = num + 1.
A loop can be used to obtain multiple inputs from the user.
Let's create a program that allows the user to enter a number 5 times, each time storing the input in a variable.
int num = 1;
int number;
/* Outputs
0
1
2
3
4
5
6
7
8
9
*/
In the init step, we declared a variable a and set it to equal 0.
a < 10 is the condition.
After each iteration, the a++ increment statement is executed.
When a increments to 10, the condition evaluates to false, and the loop stops.
It's possible to change the increment statement.
for (int a = 0; a < 50; a+=10) {
cout << a << endl;
}
/* Outputs
0
10
20
30
40
*/
You can also use decrement in the statement.
for (int a = 10; a >= 0; a -= 3) {
cout << a << endl;
}
/* Outputs
10
7
4
1
*/
When using the for loop, don't forget the semicolon after the init and condition statements.
The dowhile loop
The switch statement
Logical operators