0% found this document useful (0 votes)
56 views

Index: Glossary

The document provides an overview of basic C++ concepts including: - C++ is a general-purpose programming language used to create computer programs like applications and games. It was derived from C. - A simple "Hello World" program is presented that demonstrates including headers, namespaces, the main function, and output streams. - Comments can be added to code to explain its purpose and are ignored by the compiler. Single-line comments begin with // and multi-line comments begin and end with /* and */.

Uploaded by

Stefano Izzo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Index: Glossary

The document provides an overview of basic C++ concepts including: - C++ is a general-purpose programming language used to create computer programs like applications and games. It was derived from C. - A simple "Hello World" program is presented that demonstrates including headers, namespaces, the main function, and output streams. - Comments can be added to code to explain its purpose and are ignored by the compiler. Single-line comments begin with // and multi-line comments begin and end with /* and */.

Uploaded by

Stefano Izzo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

INDEX

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

Let's break down the parts of the code.


#include <iostream>
C++ offers various headers, each of which contains information needed for programs to work properly. This
particular program calls for the header <iostream>.
The number sign (#) at the beginning of a line targets the compiler's pre-processor. In this case, #include tells the
pre-processor to include the <iostream> header.
The <iostream> header defines the standard stream objects that input and output data.
The C++ compiler ignores blank lines.
In general, blank lines serve to improve the code's readability and structure.
Whitespace, such as spaces, tabs, and newlines, is also ignored, although it is used to enhance the program's visual
attractiveness.
In our code, the line using namespace std; tells the compiler to use the std (standard) namespace.
The std namespace includes features of the C++ Standard Library.
Program execution begins with the main function, int main().
Curly brackets { } indicate the beginning and end of a function, which can also be called the function's body. The
information inside the brackets indicates what the function does when executed.
The entry point of every C++ program is main(), irrespective of what the program does.
The next line, cout << "Hello world!"; results in the display of "Hello world!" to the screen.
In C++, streams are used to perform input and output operations.
In most program environments, the standard default output destination is the screen. In C++, cout is the stream
object used to access it.
cout is used in combination with the insertion operator. Write the insertion operator as << to insert the data that
comes after it into the stream that comes before.
In C++, the semicolon is used to terminate a statement. Each statement must end with a semicolon. It indicates the
end of one logical expression.
A block is a set of logically connected statements, surrounded by opening and closing curly braces.
You can have multiple statements on a single line, as long as you remember to end each statement with a
semicolon. Failing to do so will result in an error.
The last instruction in the program is the return statement. The line return 0; terminates the main() function and
causes it to return the value 0 to the calling process. A non-zero value (usually of 1) signals abnormal termination.
If the return statement is left off, the C++ compiler implicitly inserts "return 0;" to the end of the main() function.

Getting the tools


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.
You need both of the following components to build C++ programs.
1. Integrated Development Environment (IDE): Provides tools for writing source code. Any text editor can be used
as an IDE.
2. Compiler: Compiles source code into the final executable program. There are a number of C++ compilers available.
The most frequently used and free available compiler is the GNU C/C++ compiler.
Various C++ IDEs and compilers are available. We'll use a free tool called Code::Blocks, which includes both an IDE
and a compiler, and is available for Windows, Linux and MacOS.
To download Code::Blocks, go to http://www.codeblocks.org/, Click the Downloads link, and choose "Download the
binary release".
Choose your OS and download the setup file, which includes the C++ compiler (For Windows, it's the one with
mingw in the name).
Make sure to install the version that includes the compiler.
To create a project, open Code::Blocks and click "Create a new project" (or File->New->Project).
This will open a dialog of project templates. Choose Console application and click Go.

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.

Make sure the Compiler is selected, and click Finish.


GNU GCC is one of the popular compilers available for Code::Blocks.
On the left sidebar, expand Sources. You'll see your project, along with its source files. Code::Blocks automatically
created a main.cpp file that includes a basic Hello World program (C++ source files have .cpp, .cp or .c extensions).

Click on the "Build and Run" icon in the toolbar to compile and run the program.

A console window will open and display program output.

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.

The new line character \n can be used as an alternative to endl.


The backslash (\) is called an escape character, and indicates a "special" character.

#include <iostream>
using namespace std;

int main()
{
cout << "Hello world! \n";
cout << "I love programming!";
return 0;
}

Result:

Two newline characters placed together result in a blank line.

#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 */

/* C++ comments can


span multiple lines
*/

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.

/* Comment out printing of Hello world!


cout << "Hello world!"; // prints Hello world!
*/

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

Use the + operator to add two numbers.


Let's create a program to calculate and print the sum of two integers.

#include <iostream>
using namespace std;

int main()
{
int a = 30;
int b = 12;
int sum = a + b;

cout << sum;

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.

Working with variables


You have the option to assign a value to the variable at the time you declare the variable or to declare it and assign a
value later.
You can also change the value of a variable.
Some examples:
int a;
int b = 42;

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

CONDITIONALS AND LOOPS


The if statement
The if statement is used to execute some code if a condition is true.
Syntax:
if (condition) {
//statements
}
The condition specifies which expression is to be evaluated. If the condition is true, the statements in the curly
brackets are executed.
If the condition is false, the statements are simply ignored, and the program continues to run after the if statements
body.
Use relational operators to evaluate conditions.

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

// Outputs "a is greater than b"

The else statement


An if statement can be followed by an optional else statement, which executes when the condition is false.
Syntax:
if (condition) {
//statements
}
else {
//statements
}
The compiler will test the condition:
- If it evaluates to true, then the code inside the if statement will be executed.
- If it evaluates to false, then the code inside the else statement will be executed.
When only one statement is used inside the if/else, then the curly braces can be omitted.
For example:
int mark = 90;

if (mark < 50) {


cout << "You failed." << endl;
}
else {
cout << "You passed." << endl;
}

// Outputs "You passed."

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;

if (mark < 50) {


cout << "You failed." << endl;
cout << "Sorry" << endl;
}
else {
cout << "Congratulations!" << endl;
cout << "You passed." << endl;
cout << "You are awesome!" << endl;
}

/* Outputs
Congratulations!
You passed.
You are awesome!
*/

You can also include, or nest, if statements within another if statement.


For example:
int mark = 100;

if (mark >= 50) {


cout << "You passed." << endl;
if (mark == 100) {
cout <<"Perfect!" << endl;
}
}
else {
cout << "You failed." << endl;
}

/*Outputs
You passed.
Perfect!
*/

C++ provides the option of nesting an unlimited number of if/else statements.


For example:
int age = 18;
if (age > 14) {
if(age >= 18) {
cout << "Adult";
}
else {
cout << "Teenager";
}
}
else {
if (age > 0) {
cout << "Child";
}
else {
cout << "Something's wrong";
}
}

Remember that all else statements must have corresponding if statements.


The while loop
A loop repeatedly executes a set of statements until a particular condition is satisfied.
A while loop statement repeatedly executes a target statement as long as a given condition remains true.
Syntax: while (condition) {
statement(s);
}
The loop iterates while the condition is true.
At the point when the condition becomes false, program control is shifted to the line that immediately follows the
loop.
The loop's body is the block of statements within curly braces.
For example:
int num = 1;
while (num < 6) {
cout << "Number: " << num << endl;
num = num + 1;
}

/* 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;

while (num <= 5) {


cin >> number;
num++;
}
The above code asks for user input 5 times, and each time saves the input in the number variable.
Now let's modify our code to calculate the sum of the numbers the user has entered.
int num = 1;
int number;
int total = 0;

while (num <= 5) {


cin >> number;
total += number;
num++;
}
cout << total << endl;
The code above adds the number entered by the user to the total variable with each loop iteration.
Once the loop stops executing, the value of total is printed. This value is the sum of all of the numbers the user
entered.
Note that the variable total has an initial value of 0.
The for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that executes a specific number
of times.
Syntax:
for ( init; condition; increment ) {
statement(s);
}
The init step is executed first, and does not repeat.
Next, the condition is evaluated, and the body of the loop is executed if the condition is true.
In the next step, the increment statement updates the loop control variable.
Then, the loop's body repeats itself, only stopping when the condition becomes false.
For example:
for (int x = 1; x < 10; x++) {
// some code
}
The init and increment statements may be left out, if not needed, but remember that the semicolons are
mandatory.
The example below uses a for loop to print numbers from 0 to 9.
for (int a = 0; a < 10; a++) {
cout << a << endl;
}

/* 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

You might also like