C Language: "Hello World!"

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

C++ is a popular programming language.

C++ is used to create computer programs, and is one of the most used language in game development.

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 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20.

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.

C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be
reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

Difference between C and C++

C++ was developed as an extension of C, and both languages have almost the same syntax.

The main difference between C and C++ is that C++ support classes and objects, while C does not.

#include <iostream>
using namespace std;

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: 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/print text:

To insert a new line, 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;
}

Another way to insert a new line, is with the endl manipulator:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

Both \n and endl are used to break lines. However, \n is most used.

But what is \n exactly?

The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in a new line.

Examples of other valid escape sequences are:

Escape Sequence Description Try it

\t Creates a horizontal tab Try it

\\ Inserts a backslash character (\) Try it

\" Inserts a double quote character


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

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of the variable (such as x or myName).
The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
cout << myNum;

To declare more than one variable of the same type, use a comma-separated list:

Example

int x = 5, y = 6, z = 50;
cout << x + y + z;

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;

// OK, but not so easy to understand what m actually is


int m = 60;

Constants

When you do not want others (or yourself) to override existing variable values, use the const keyword (this will
declare the variable as "constant", which means unchangeable and read-only):

Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

C++ User Input

You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we print the value
of x:

Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
C++ Data Types

As explained in the Variables chapter, a variable in C++ must be a specified data type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

float vs. double

The precision of a floating point value indicates how many digits the value can have after the decimal point. The
precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.

Boolean Types

A boolean data type is declared with the bool keyword and can only take the values true or false.

When the value is returned, true = 1 and false = 0.

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

Character Types

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or
'c':

Example
char myGrade = 'B';
cout << myGrade;

String Types

The string type is used to store a sequence of characters (text). This is not a built-in type, but it behaves like one in
its most basic usage. String values must be surrounded by double quotes:

Example
string greeting = "Hello";
cout << greeting;

To use strings, you must include an additional header file in the source code, the <string> library:
Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

// Output string value


cout << greeting;

C++ Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it can also be used to
add together a variable and a value, or a variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min

The max(x,y) function can be used to find the highest value of x and y:

Example

cout << max(5, 10);

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in
the <cmath> header file:
Example
// Include the cmath library
#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

C++ Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, C++ has a bool data type, which can take the values true (1) or false (0).

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false:

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

C++ Conditions and If Statements

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
}

ote 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";
}

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to
the else condition and print to the screen "Good evening". If the time was less than 18, the program would print
"Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else
if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and
print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

You might also like