41
C++ Tutorial Online Programming Tutorials and Learning Toolkits Web Site Front-end Development By Craig Freeman

C++ Tutorial

Embed Size (px)

DESCRIPTION

C++ Tutorial by Craig Freeman

Citation preview

Page 1: C++ Tutorial

C++ Tutorial

Online Programming Tutorials and Learning Toolkits Web Site

Front-end Development

By Craig Freeman

Page 2: C++ Tutorial

Introduction

Welcome to a tutorial on programming in C++. In this tutorial you will be learning the basics of coding in this language including; The #include directive, Inputs, Outputs, Functions, Variables declaration, Assignment and Data Types.

Page 3: C++ Tutorial

Introduction Continued

This tutorial will also focus on key concepts such as:

Selection Iteration Data structure Functions, parameters and return values

Page 4: C++ Tutorial

Preparation

Before beginning these tutorials please ensure that you have CodeBlocks installed on your PC. If you do not then please use the link bellow to download and install CodeBlocks. If you experience any issues please use the helpful information found on the site.

http://www.codeblocks.org/downloads/26

Page 5: C++ Tutorial

The #include directive

The include directive is a method of calling libraries. These libraries are found in the pre-processor directive and added before compiling the program. These libraries tell the compiler how to make sense of the program you have written so that it can be successfully run.

Page 6: C++ Tutorial

The #include directive continued The library added using #include <iostream>

tells the compiler to include the iostream standard file which tells it how to handle inputs and outputs.

Another example of a library which can be added is #include <cstdlib> which among other things allows the use of a system(“pause”) which is a command to pause a running program until a user input is made.

Page 7: C++ Tutorial

The #include directive continued To test this for yourself please download

the programOne folder below and run the project file in CodeBlocks

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 8: C++ Tutorial

Using namespace std Using namespace std is a using directive which

tells the compiler how to logically group code. This means that all namespace std entities become global namespace and this means you won't have to use the std:: for them. In other words this code makes it so std:: does not have to be used constantly.

An example of this in use can be seen in programTwo using the link below.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 9: C++ Tutorial

The main() function A function is a section of code which is run. In

essence it is the holder of the main part of the code which you want to create.

You can have multiple functions in one file however the default function which is run first is always main(). An example of this in use can be seen in programThree of the link below.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 10: C++ Tutorial

The main() function continued

In programThree it can be seen that within the main function a second function is being called. This second function prints hello world. In this way the main function is accessed first but still produces the hello world line.

Page 11: C++ Tutorial

Inputs and 0utputs

Inputs and outputs require std:: at the front of each command, however using namespace std this is not necessary.

An output is made using cout code which is written as: cout << “what you want to output” << endl;

Page 12: C++ Tutorial

Inputs and 0utputs continued An input is performed very similarly. The

command starts with cin instead and uses >> instead of << because instead of sending something out it is taking something in. An example of this could be cin >> input;

It is very simple to use and examples of both can be seen in programFour of the following link: https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 13: C++ Tutorial

Variable Declaration and Assignment Looking at programFour again the code

– ‘string input;’ can be found on line 9. This is an example of variable declaration. Variable declaration is the method of declaring new variables for use in a program. For example a variable named Number could be declared and used later to perform a calculation.

Page 14: C++ Tutorial

Variable Declaration and Assignment continued Declaring a variable does not assign a value to it and

most often when performing calculations or functions a variable with a value is necessary. For instance a calculator needs input from a user and this input is sent to variables.

Values can be assigned to variables in two ways. The first involves assigning a value at the same time as declaring the variable, and the second is inputting a value within a function. This can be seen on the following link within programFive.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 15: C++ Tutorial

logical/arithmetic operators Operators represent specific actions and

are very useful in programming. A logical operator is used to logically combine and compare Boolean conditions or expressions. A few examples of logical operators can be seen below.

Operator Meaning

&& AND

! NOT

|| OR

Page 16: C++ Tutorial

logical/arithmetic operators continued The AND logical operator can be used when making a selection

by telling the statement that it must be both statements.

The OR operator can be used in the same way except that it can be either statements

And the NOT operator would mean that the next step of the program should only be done if the result being measured is not the same as the argument in the condition.

Some of these can be seen in action within programSix found within the below folder.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 17: C++ Tutorial

logical/arithmetic operators continued programSix was built to prove the following

statement: “The maximum value for a unsigned int is

greater than the maximum value for a signed int and the minimum value for a int is less than the minimum value for an short int or an unsigned int.”

It does this by declaring all of the relevant values and then using an if statement to find out if this is true or false using logical operators.

Page 18: C++ Tutorial

logical/arithmetic operators continued Arithmetical operators are much like

logical operators but use mathematical methods. Examples of arithmetic operators can be seen below.

Operator Meaning

+ addition

- subtraction

* multiplication

+= Is equal to itself plus another variable. E.g. 4+=3+1 is another way of writing 4=4+3+1

Page 19: C++ Tutorial

logical/arithmetic operators continued programSeven found on the following

link shows how these operators work in each calculation near the end.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 20: C++ Tutorial

Data Types

Beginner programmers can confuse data types with variables because they are so closely related. Data types are the kind of data the variable can store. For instance integers can only store whole numbers whereas strings can store letters.

A table of different data types can be seen below.

Page 21: C++ Tutorial

Data Types continuedData Type Value

int Whole numbers

floating point Figures with decimal values

string Text, an array of chars

char Single characters of text

boolean True or false

Page 22: C++ Tutorial

Selection

Selection is used to determine how a program should run. One example could be a program outputting a yes if a value is lower than 100 or a false if a value is above 100.

Types of selection include if/else and switches

Page 23: C++ Tutorial

Selection continued - if/else If statements work by using arguments to measure

variables and make decisions based on them.

An example of an if/else statement might be:

If (selection=true)

{

Cout<<“True”<<endl;

}

Else if

{

Cout <<“false”<<endl;

}

Page 24: C++ Tutorial

Selection continued - if/else In this scenario selection=true has been used

as the argument to determine how the selection should be made. If the variable selection is true then the first if statement is used and if it not true then the else selection takes over and outputs ‘false’.

An example of an if/else selection in use can be seen in programSeven through the link: https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 25: C++ Tutorial

Selection continued - Switches

Switches work by making a selection from a list of possible cases. This selection is made by comparing a variable to a list of values. An example of this might be:

Switch(selection)

{

Case ‘a’:

cout<<“a”<<endl;

break;

Case ‘b’:

cout<<“b”<<endl;

break;

}

One important thing to note with switches is the break used at the end of each case, as can be seen above. Without a break to ‘break out’ of the selection the program will carry through all the cases below it. For instance without a break in case a, case b would be carried out next even though it was not meant to be.

Page 26: C++ Tutorial

Selection continued - Switches

In that example selection is the variable being used in the argument and case a is selected if that is the variable value or case b if that is. To see a switch in action please refer to programEight in the following folder.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 27: C++ Tutorial

Selection continued - Switches

When using switches you often rely on user input and this can lead to problems. With switches you can make inputs to a char data type variable however if the user enters several keystrokes instead of one then the program will register this as 3 separate entry and try to go through the menu 3 times. Something which is not very useful.

If the user also inputs an invalid entry then it will cause the program to crash. All of which leads me to my next slide.

Page 28: C++ Tutorial

Selection continued - Switches

Switches can be made much more efficient by using error validation techniques. One of these techniques is to simply setup a default case at the end, much like can be seen below.

default:

cout << "\nCharacter entered was not an option\n" << endl;

break;

Page 29: C++ Tutorial

Selection continued - Switches Another method of validation could be input validation. To do this I usually use a

relatively simple if/else statement as can be seen below.

//input validation

if (input.length() == 1)

{

//If the input length is 1 then 'input' which is string is run as an array and the first letter is passed to select as its value

select = input[0];

}

else

{

cout << "\nCharacter entered was not an option\n" << endl;

//If the validation fails then restart the function

main();

}

To see this code in use please see programEightPartTwo on the following link: https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 30: C++ Tutorial

Iteration

Iteration refers to the use of loops. There are two kinds of loops; while loops and for loops.

While loops are the simpler of the two and so I will be starting with them.

Page 31: C++ Tutorial

Iteration continued A while loop is a way of telling the compiler ‘do this while this

argument is true’ and using code like this:

While(argument)

{

Possible changes to argument

}

A good example of this in use can be found by looking at part one or part two of programEight. You can see that there is actually a while loop around almost everything but the variable declarations.

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 32: C++ Tutorial

Iteration continued A for loop is a little more complex. Essentially they

work the same as while loops however within the argument brackets you can declare variable value, setup an argument for looping and increment the variable value.

An increment is a way of controlling how many times a loop is done. If you want something to be performed 4 times then you can increment a variable equal to 0 by 1 each loop until it reaches 4. The loop argument can then be to stop the loop when the variable reaches 4. In this way a loop can be made 3 times to give a total of 4 cycles. An example of this can be seen on the following slide.

Page 33: C++ Tutorial

Iteration continued

For (increment=0; increment<5; increment++)

{

cout << “you have looped ” << increment << “times” << endl;

}

This simple for loop uses an increment to loop and to output how many loops have been done each time. To see this in use please use programNine in the following link:

https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 34: C++ Tutorial

Data structure The term data structure refers to how data is organised into a

related group. Examples of data structures could be arrays, records or tables but for C++ programming arrays are what I will be focusing on.

Arrays work by listing a series of values as below.

int array1[N] = {3,6,9,4,7,4,2,2,4,2};

In this case the array1 has been declared as a series of integers which are declared within squiggly brackets. The N value in this case represents a number and this number corresponds to the array value. For instance if N=0 then the array result would be 3 and if N=2 then the array result would be 9.

This method is very useful for grouping series of data. An example of that could be students grades. To see an example of that in a program please open programTen in https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 35: C++ Tutorial

Functions A function is essentially a block of code which

can be given a name and called from anywhere. Functions are a good way of reusing code which speeds up coding considerably.

You declare a function by writing a variable type, void in the case below as it is not returning anything, and writing a function name followed by two brackets. An example of this can be seen on the next slide.

Page 36: C++ Tutorial

Functions continued

void hello()

{

cout << “Hello World” << endl;

}

//The function is then called within another function like this

hello();

Page 37: C++ Tutorial

Functions continued One very important aspect to note with using functions

is that the main() function is always called first as standard by the compiler and so it is worth bearing in mind that this should be the main function where applicable.

() these brackets are always needed and are used to pass values into a function. The values inside are called function paramaters. You do not have to use them however but to pass values for variables from one function to another without using global variables they are necessary. The { brackets are always needed to hold the actual code of the function.

Page 38: C++ Tutorial

Functions continued Function parameters are necessary to send values of

variables from one function to another. Without them global variables would be necessary and this is bad practice as with many functions writing and reading to them it can become very confusing as to what is actually happening. An example of what this might look like can be seen below.

int Num1AndNum2(int num1, int num2)

{

return num1 + num2;

}

int Sum = Num1AndNum2(5, 9);

Page 39: C++ Tutorial

Functions continued Return values are a method of returning a value of a function so that is can be

used in another function. An example of this could be as below.

using namespace std;

int calculate(int num1,int num2)

{

int calculate;

calculate = num1+num2;

return calculate;

}

int main()

{

cout << calculate(4,5) << endl;

cout << calculate(98,52) << endl;

system("pause");

}

This program can be seen within programEleven in https://drive.google.com/folderview?id=0B7EEqo1krfWPLWJUZXc5RC1tdUU&usp=sharing

Page 40: C++ Tutorial

Quiz

A quiz to test your knowledge. Answers found on next slide.

1. What is a function? 2. What is an #include directive? 3. What s the difference between a

variable and an assignment? 4. What is an iteration?

Page 41: C++ Tutorial

Answers 1. A function is a grouping of code accessible

anywhere in a program which is used for reusable code as it can be called again and again.

2. An #include directive is a way of accessing a library which tells the compiler how to handle things

3. A variable is a declared entity to store values. Assignment is the storing of said values

4. An iteration is a loop