an introduction to c++ lecture 03: conditions, loops

Post on 10-Dec-2021

7 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

An Introduction to C++

Lecture 03: Conditions, loops & containers

Roger Wolf22. June 2021

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 1:

Conditional statements

1/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The if-directive

● We have sneaked-in conditional statements already in several places throughout the course. Now it is time formally to introduce them:

2/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The if-directive

● We have sneaked-in conditional statements already in several places throughout the course. Now it is time formally to introduce them:

Each if/else statement opens a command block

2/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The if-directive

● We have sneaked-in conditional statements already in several places throughout the course. Now it is time formally to introduce them:

else if requires that preceding conditional statements failed

2/38

Each if/else statement opens a command block

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The if-directive

● We have sneaked-in conditional statements already in several places throughout the course. Now it is time formally to introduce them:

else is the alternative to everything else…

2/38

Each if/else statement opens a command block

else if requires that preceding conditional statements failed

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The if-directive

● We have sneaked-in conditional statements already in several places throughout the course. Now it is time formally to introduce them:

2/38

● Note: in case that if/else is followed by only one single statement the braces “{}” may be omitted.

else is the alternative to everything else…

Each if/else statement opens a command block

else if requires that preceding conditional statements failed

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Examples for conditional statements

● Logical operators that are usually used in conditional statements are: •&&•, •||•, !•, •<•, •>•, •<=•, •>=•, •==•, …

● Logical operator bindings follow the rules of mathematics. In case of doubt use braces “()” to enforce the evaluation order.

3/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Examples for conditional statements

● Note: C(++) performs “lazy evaluation”, i.e. the first failing part in a more complex conditional statement breaks the evaluation.

● Logical operator bindings follow the rules of mathematics. In case of doubt use braces “()” to enforce the evaluation order.

3/38

a<MAXIMUM immediately breaks the condition

● Logical operators that are usually used in conditional statements are: •&&•, •||•, !•, •<•, •>•, •<=•, •>=•, •==•, …

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The switch-directive

● There is a “more convenient” possibility to fulfill relay tasks:

4/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The switch-directive

● There is a “more convenient” possibility to fulfill relay tasks:

● value is interpreted as int (it can be a char though).

● case 1: corresponds to value==1, more complex logical statements are not supported.

● break exits the command block, w/o break it will be continued!

● Note: case 3 and default implement a logical OR.

4/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 2:

What you need to know about loops

5/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Groundhog day

● One of the main arguments to write (scientific) code is to repeat certain processes (most of the time really often… )

● Examples:

● C(++) offers several ways to do this…

● Numerical integration

● Statistical ensemble tests

● Characterization of large data sets

● Manipulation of large lists

● …

6/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

7/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

Conditional (break) statement

7/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

i is first incremented and then printed

Conditional (break) statement

7/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

● The conditional statement in while(…) is accessed first. If it fails the command block will not be entered.

● In this example we count from 1 to 10 (→ try it yourself).

i is first incremented and then printed

Conditional (break) statement

7/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

● The conditional statement in while(…) is accessed first. If it fails the command block will not be entered.

● In this example we count from 10 to 1 (→ try it yourself).

i is first printed and then decremented

8/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

9/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note: the command block will be accessed at least once!

9/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

Does this make a difference for our example?

9/38

● Note: the command block will be accessed at least once!

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note that the command block will be accessed at least once!

What happens in this example?

10/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note that the command block will be accessed at least once!

This is equivalent to i!=0 (i.e. this asks whether the pointer points to a valid element in memory or not)

What happens in this example?

10/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Endless loops

● Note: if you pass a trivially true break statement your loop will run for ever:

This is a trivially fulfilled statement.

11/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Endless loops

If you missed the ++ operator here by incidence you would also create an endless loop.

● Note: if you pass a trivially true break statement your loop will run for ever:

12/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Endless loops

If you missed the ++ operator here by incidence you would also create an endless loop.

● Note: if you pass a trivially true break statement your loop will run for ever:

12/38

A very popular mistake is a break statement like this:

while(i=0){ … }

Will the loop break in this case?

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Endless loops

● An endless loop can also be intended. Usually you then break it explicitly by the keyword break in the command block.

● Note: if you pass a trivially true break statement your loop will run for ever:

13/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Endless loops

● An endless loop can also be intended. Usually you then break it explicitly by the keyword break in the command block.

std::cin is an input stream. It is declared in iostream.h. It expects an input from your keyboard, interprets it as short int and writes it into number.

14/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

A question of style

● The given example is perfectly fine, but it is usually not good style to implement it like this: breaking conditions are not clear from the break statement of the loop. This complicates reading your code.

15/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

A question of style

This is the better solution: the code is shorter and clearer at the same time.

● The given example is perfectly fine, but it is usually not good style to implement it like this: breaking conditions are not clear from the break statement of the loop. This complicates reading your code.

16/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

● The standard way to iterate something is the for(…) loop:

17/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

Initializing statement (before loop starts).

● The standard way to iterate something is the for(…) loop:

17/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

Initializing statement (before loop starts).

Breaking statement.

● The standard way to iterate something is the for(…) loop:

17/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

Operation that can alter the condition of the break statement.

Initializing statement (before loop starts).

Breaking statement.

● The standard way to iterate something is the for(…) loop:

17/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in for(…).

● The standard way to iterate something is the for(…) loop:

18/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in your for loop.

You can leave statements blank.

19/38

● The standard way to iterate something is the for(…) loop:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in your for loop.

You can leave statements blank.

And of course you can nest all kinds of loop statements.

20/38

● The standard way to iterate something is the for(…) loop:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

In this example: loop the elements of inputs.

21/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

Read-only loop.

22/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

If you want to change the elements of inputs.

23/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

If you want to change the elements of inputs.

And if you don’t want to care what types should be iterated declare idx as auto.

24/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keywords: break and continue

● C(++) has several keywords to communicate special cases to the compiler. A few first examples are given in the following. More will occur during the course.

● For all loop statements that we have discussed the keyword break will break the loop. When using continue, the loop will jump to the next iteration (here shown for the for(…) loop).

25/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keywords: break and continue

● C(++) has several keywords to communicate special cases to the compiler. A few first examples are given in the following. More will occur during the course.

Note: You may achieve the same result without the use of the keywords. This might also be the cleaner solution.

25/38

● For all loop statements that we have discussed the keyword break will break the loop. When using continue, the loop will jump to the next iteration (here shown for the for(…) loop).

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Scopes & variables

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

26/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

27/38

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

Scopes & variables

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables

● A variable inside a command block is often called “local”. The opposite is a variable outside any command block, which is called “global”.

● The local variable will loose its validity once the command block is left. The global variable is accessible everywhere in your TU, or throughout your code.

● In well written/designed C++, usually there is no need for global variables. The difficulty of (esp. mutable) global variables, e.g. in C (or even worse FORTRAN) is, that you never now who altered it and in what way in the course of the program.

28/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keyword: static

● Loops provide also an occasion to introduce another keyword: static.

static indicates that the variable should be declared only once. It will be initialized with a value by compile time! This happens in the TU before the linking step.

29/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keyword: static

w/o static

static indicates that the variable should be declared only once. It will be initialized with a value by compile time! This happens in the TU before the linking step.

29/38

This is how the output of the program looks like

● Loops provide also an occasion to introduce another keyword: static.

w/o static

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keyword: static29/38

This is how the output of the program looks like

● Loops provide also an occasion to introduce another keyword: static.

w/o static

w/o staticw/o static

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keyword: static

Note: also here a potentially better solution can actually be achieved w/o the keyword.

29/38

This is how the output of the program looks like

● Loops provide also an occasion to introduce another keyword: static.

w/o static

w/o staticw/o static

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Keyword: static

Note: when used for functions static means that the function is visible only within its TU (→ turned into executable code at compilation time before(!) linking).

30/38

Note: also here a potentially better solution can actually be achieved w/o the keyword.

● Loops provide also an occasion to introduce another keyword: static.

w/o static

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 3:

Container classes

31/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

C++ container classes

● The standard use case for a loop is the iteration of a set of similar elements. C++ provides high performance container classes to hold objects, with varying level of complexity for certain functionalities. E.g.:

● std::array<T> – C++ equivalent to C array, fixed length

● std::vector<T> – dynamically expandable

● std::list<T> – constant time insert/erase operations

● std::stack<T> – FILO adaptation of upper containers

● std::queue<T> – FIFO adaptation of upper containers

● std::set<S, T> – associative array (unique elements only)

● std::map<S, T> – associative array (same elem’s possible)

● A container class is a holder object that stores a collection of other objects.

● All container classes are implemented as class templates (→ see Lecture-08), i.e. whether a std::vector holds int or float (or even a user-defined object) is determined by “argument” during object declaration.

32/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

33/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

33/38

Declaration and initialization w/ <int>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

Declaration and initialization w/ <int>

Add nextValue to end

33/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

Declaration and initialization w/ <int>

Add nextValue to end

Determine size & access elements

33/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

A better way to iterate C++ containers

34/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, …

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

Output

Forward Bidirectional Random Access

35/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, …

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

Output

Forward Bidirectional Random Access

35/38

● The simplest iterator is the built-in pointer.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, …

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

Output

Forward Bidirectional Random Access

35/38

● The simplest iterator is the built-in pointer.

● The C++ standard containers have several iterators as data members that can be accessed by member functions like begin(), end() and rbegin(), rend(), …

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>36/38

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

36/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

36/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists.

std::map<S,T>36/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

36/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

Assign a value to a given key.

36/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

Assign a value to a given key.

How you could use these two functions…

Note: you can learn much more about std::map in one of the next exercises.

37/38

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S,T>

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Summary

● The while(...), do(...), for(…) loop.

● Endless loops.

● First key words break & continue.

● Variable scopes.

● The key word static.

● C++ containers: std::vector<T> and std::map<S,T>.

38/38

● The if-directive.

● The switch-directive.

top related