C++ Introduction
C++ Introduction
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 5 major times in 2011, 2014, 2017, 2020, and 2023 to
C++11, C++14, C++17, C++20, and C++23.
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input
and output objects, such as cout (used in line 5). Header files add functionality to
C++ programs.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
Don't worry if you don't understand how #include <iostream> and using
namespace std works. Just think of it as something that (almost) always appears in
your program.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more
readable.
Line 4: Another thing that always appear in a C++ program is int main(). This is
called a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion
operator (<<) to output/print text. In our example, it will output "Hello World!".
Note: C++ is case-sensitive: "cout" and "Cout" has different meaning.
Note: Every C++ statement ends with a semicolon ;.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the
code more readable.
Line 6: return 0; ends the main function.
Line 7: Do not forget to add the closing curly bracket } to actually end the main
function
Omitting Namespace
You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:
Example
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values and print
text.
Just remember to surround the text with double quotes (""):
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
int main() {
cout << 3;
return 0;
}
New Lines
To insert a new line in your output, you can use the \n character:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can
also be used to prevent execution when testing alternative code. Comments can
be singled-lined or multi-lined.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
cout << "Hello World!";
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for
example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes
string - stores text, such as "Hello World". String values are surrounded by
double quotes
bool - stores values with two states: true or false
C++ Identifiers
All C++ variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Example
// Good
int minutesPerHour = 60;
Exercise
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from
mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different
decisions.
C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is
true
Use else to specify a block of code to be executed, if the same condition is
false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C++ code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate
an error.
In the example below, we test two values to find out if 20 is greater than 18.
If the condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Try it Yourself »
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords are optional, and will be described later in
this chapter
The example below uses the weekday number to calculate the weekday
name:
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
C++ Loops
Loops can execute a block of code as long as a specified condition is
reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
C++ While Loop
The while loop loops through a block of code as long as a specified
condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
C++ "Hello World!" Program
// Your First C++ Program
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
int main() {
// prints sum
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}
int main() {
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Example 1: Swap Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
return 0;
}
return 0;
}