Algorithms and C++orion.lnu.se/pub/education/course/1DV433/ht16/steg/01/...Algorithms and C++ A...

19
1DV433 –Structured programming with C++ © 2013 Anne Norling Algorithms and C++ A brief introduction to programming-logical thinking …

Transcript of Algorithms and C++orion.lnu.se/pub/education/course/1DV433/ht16/steg/01/...Algorithms and C++ A...

1DV433 –Structured programming with C++

© 2013 Anne Norling

Algorithms and C++

A brief introduction to programming-logical thinking …

1DV433 –Structured programming with C++

© 2013 Anne Norling

Problemsolving

1DV433 –Structured programming with C++

© 2013 Anne Norling

Solve problems

1. First, understand the problem and structure it in some abstract model.

WHAT shouldbe solved?

HOW should weproceed?

NOW we solve the problem

2. Then create a suitable algorithm for problem.

3. Finally, we use the algorithm in order to solve the problem.

In order to solve a problem we must:

1DV433 –Structured programming with C++

© 2013 Anne Norling

Algorithm…?

1DV433 –Structured programming with C++

© 2013 Anne Norling

”… a method to solve problems in a number of simple steps, with an indication of the order in which they should be performed.”

The concept of algorithm• We can explain the concept of algorithm as:

There is a difference between an algorithm and a program!A program is a series of coded instructions that controls the operations

of a computer or other machine. The program is a description ofthe algorithm in a way that the computer can understand.

Illustrated in a flowchart

1DV433 –Structured programming with C++

© 2013 Anne Norling

The programming language

• The computer is basically STUPID!(?)

• An amount of detailed instructions are needed to carry out any meaningful things, which is the task of the programming language.

But a simple task?

• Someone else still has to do the job, defining how a problem should be solved – in what order, on what conditions an in what extent.

That’s the programmer's job!

BUT - It was worse in the past …!

1DV433 –Structured programming with C++

© 2013 Anne Norling

Machine language• By that time (40's?) programming was just about a language

computers can understand - machine language

– ie. machine instructions, grouped as binary numbers, (bits = 0's and 1's), 8, 16, or 32 at a time.

• No matter that we now (to all programmer's happiness?) are using high-level languages, computer work basically deals about moving around the 1's and 0's!

• Thus we need to give it solution models based on small, small steps

1011 0100 0000 0010 0000 0000 0000 00101011 0010 0000 0010 0000 0000 0010 10100000 0000 0010 1010 0000 0000 0010 1010

That is….

1DV433 –Structured programming with C++

© 2013 Anne Norling

Algorithms solve problems• We use algorithms to provide computer with methods to solve

problems

• Concept: The computer can only perform ONE small instruction at a time, why the algorithm must solve problems in very small steps

• Mostly drawn graphically as flowcharts on lower levels of programming structures. (In larger context, other techniques used.)

• Based on: given conditions leads to a certain outcome:

An algorithm should cover all conditions of a particular type (all possible input)

Input Execute task Output

1DV433 –Structured programming with C++

© 2013 Anne Norling

Structure• A program flow is built upon three basic parts:

Sequence Selection Iteration

• All flowcharts only have one ”entrance”:

and one ”exit”:

• The grafical representation in between => control structures of statements, controlling flow of the program

Start

End

1 2 3

1DV433 –Structured programming with C++

© 2013 Anne Norling

Notation• For the graphical notation the following components are used:

Sequence - a sequence of instructions(something is performed)

Selection – a choice, depending on processed input

- if result of statement is TRUE, follow left flow(”if -statements”)

- else the right flow (”else -statements”)

Iteration - repetition of moments - a given number of times (”for- loops”), alt.- until stop condition is reached (”while- loops”)

1Read variable-value

Print variable-value or text

Variable ← value

2if

TRUEelseFALSE

condition

3FALSE

TRUE

whilecondition

1DV433 –Structured programming with C++

© 2013 Anne Norling

The algorithm ”hair wash”• In the interpretation of a flow

chart, you begin by start.

• The flow is followed downwards, step by step, along the arrows.

• A rectangle indicates that the instruction inside the rectangle shall be performed

• A diamond indicates that a choice of route is made. In the diamond is given a statement , which in a certain situation is true or false.

start

shower hair

whilehair

is dirtyrepeat

rub in schampo

rinse hair

ifsun is shining

let hair drynaturally

use the drier

end

TRUE FALSE

TRUE

FALSE

1DV433 –Structured programming with C++

© 2013 Anne Norling

Example - sequenceCreate an algorithm that reads two numbers from user,summarizes them and prints the result on screen.

value1: value2: sum:

1. Initialize variables. ”Clean up” former junk value withzero. (In many cases unnecessary but learn to ALWAYS do it. This will save you some troubleshooting – it´s a common cause of failure!)

2. Read the value to one variable at a time3. Perform the operation4. Print the result

// C++-programint value1 = 0;int value2 = 0; int sum = 0;cout << ”Value 1: ”; cin >> value1;cout << ”Value 2: ”;cin >> value2;sum = value1 + value2;cout << sum;

Start

Read value1

sum ← value1+ value2

End

Print sum

Read value2

value1 ← 0

value2 ← 0

sum ← 0

Problem:

Variables:

Workflow:

“=“ is equivalent to “←” in flowchart. We “assign” result from operation to variable “sum”, where value will be stored.

We”define” the variables to usein our program. Initialize themwith 0-value.

”Read” the valueprinted by user. Will be ”stored” in variable.

Prompt the user to input a value

1DV433 –Structured programming with C++

© 2013 Anne Norling

Example selection - one alternative

If a value from user > 0, print it doubled.

nr:

1. Initialize variabel2. Read the variable3. Set the condition (nr > 0) and check it4. IF (condition) is TRUE, perform instructions

on the left side5. IF (condition) is FALSE – do nothing

// Program language:int nr = 0;cin >> nr;

if (nr > 0) {

nr = 2 * nr;cout << nr;

}

Problem:

Variables:

ifTRUE FALSE

Print nr

Start

Read nr

nr ← 0

nr ← 2 * nr

End

nr > 0

Workflow:

1DV433 –Structured programming with C++

© 2013 Anne Norling

Example selection - two alternatives

Decide and print if a number is odd or even

value:

1. Initialize and 2. Read variable3. IF (condition) TRUE, perform instruction on the

left side4. ELSE perform instruction to the right

Problem:

Variables:

TRUE FALSE

Print ”odd”

End

Start

Read nr

nr ← 0

nr % 2 == 0

Print ”even”

elseif

Workflow:

// Program language:int nr = 0;cin >> nr;

if (nr % 2 == 0){cout << ”Number is even”;

}else{cout << ”Number is odd”;

}… this will happen

ELSE…

IF condition was true…

… this is performed

"%" is the modulus operator, which provides us with the remainder from an integer division

1DV433 –Structured programming with C++

© 2013 Anne Norling

Selection – more options

If several conditions are to be tested, thesefollows as selection boxes on the right side (that is where previousconditions are FALSE). An unlimited number of statements can be nested.

End

Print ”negative”

value < 0

Start

Read value

value> 0

Print ”zero”Print ”positive”

TRUEif

FALSEelse

TRUEif

FALSEelse

// Program language:cin >> value;

if ( value < 0 ){cout << ”negative”;

}else if ( value > 0 ){cout << ”positive”;

}else{cout << ”zero”;

}

(ELSE - IF this is true)

(ELSE…)

Nested statements:

(IF this is true)

1DV433 –Structured programming with C++

© 2013 Anne Norling

Iteration, for-loop

• In a for-loop one or more statements should be repeated a certain number of times => we know the number of ”turns”

Basic rule:

1. Startvalue of counter2. Repetition depends on counter -

it shall be in the3. Enumeration of counter

FALSE

TRUE

assignment

Start

End

control

completion

calculation

enumeration

Repetition box:

1DV433 –Structured programming with C++

© 2013 Anne Norling

Example for-loopSum 100 numbers (= we know the number of ”turns”)

turns: nr: sum:

1. Startvalue of counter (and initialize variables)2. Repetition depends on counter:

Set condition (turns < 100) and check3. WHILE (condition) TRUE: enumerate counter +

other instr. When condition becomes FALSE, exit loop

turns ← turns +1

Start

turns ← 0

sum ← 0

End

whileturns < 100

Print sum

Read nr

sum ← sum + nr

nr ← 0

int nr, sum, turns; nr = sum = 0;

for (turns = 0; turns < 100; turns++){cin >> nr;sum = sum + nr;

}cout << sum;

1.

Problem:

Variables:

Workflow:

turns ← 0

2.

whileturns < 100

3.

turns ← turns +1

1DV433 –Structured programming with C++

© 2013 Anne Norling

Iteration, while-loop

• In a while-loop one or more statements should be repeateduntil a condition is fulfilled => we stop on a ”signal”

Basic rule:

1. Read first value2. Control if signal is given

it shall be in the 3. Read next value

FALSE

TRUE

Read x

Start

End

signal

completion

calculation

Read x

Repetition box:

1DV433 –Structured programming with C++

© 2013 Anne Norling

Example while-loopCalculate average score on an exam, stop input

with value –1 (we stop on a ”signal”)

sum: nrOfStud: score:

1. Read first value (and initialize variables)2. Control if signal is given:

Set condition (score != -1) and check3. WHILE (condition) TRUE: Read next value (etc.)

Problem:

Variables:

int sum = 0, nrOfStud = 0, score = 0;

cin >> score;

while (score!= -1){sum = sum + score;nrOfStud = nrOfStud + 1; cin >> score;

}if (nrOfStud != 0)

cout << sum / nrOfStud;

FALSE

TRUE

Print sum/nrOfStud

End

sum ← sum + score

Read score

whilescore != -1

Start

Read score

nrOfStud ← 0

sum ← 0

nrOfStud ← nrOfStud +1

ifnrOfStud != 0

Workflow:

1.

Read score

2.

NOTE – do not forgetDo always read a first value

before a controlcan be done here!

whilescore != -1

NOTE – scanning of next value shall be made at the end of repetition,Otherwise no operations will be performed for first read value !

3.Read score

“!=“ is equivalent to “not equal to”. We compare left and right operand to let a “true” or “false” result decide whether or not to continue loop (ie execute statements in block)