introduction to high-level language programming chapter 7

76
Introduction to High- Introduction to High- Level Language Level Language Programming Programming Chapter 7 Chapter 7

Post on 18-Dec-2015

233 views

Category:

Documents


1 download

TRANSCRIPT

Introduction to High-Level Introduction to High-Level Language ProgrammingLanguage Programming

Chapter 7Chapter 7

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 2

Pseudo-code vs. AssemblyPseudo-code vs. Assembly

Set sum to 0Set i to 1While i 5 do Get value for N Add N to sum Increase value of i by 1End loopPrint the value of sum

.BEGIN -- Sum 5 numbersLoop: LOAD Five

COMPARE iJUMPGT DoneIN NLOAD sumADD NSTORE sumINCREMENT iJUMP Loop

Done: OUT sumHALT

Five: .DATA 5i: .DATA 1sum: .DATA 0N: .DATA 0.END

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 3

Disadvantages of Disadvantages of AssemblyAssembly

• The programmer must manage movement of The programmer must manage movement of data items between memory locations and the data items between memory locations and the ALU.ALU.

• Programmer must take a “microscopic” view of a Programmer must take a “microscopic” view of a task, breaking it down to manipulate individual task, breaking it down to manipulate individual memory locations.memory locations.

• Assembly language is machine-specific.Assembly language is machine-specific.• Statements are not English-like (Pseudo-code)Statements are not English-like (Pseudo-code)

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 4

Pseudo-code vs. High-level Pseudo-code vs. High-level ProgramsPrograms

Set sum to 0Set i to 1While i 5 do Get value for N Add N to sum Increase value of i by 1End loopPrint the value of sum

Wouldn’t it be nice if we Wouldn’t it be nice if we could instead write could instead write our program in a our program in a language more similar language more similar to a pseudo-code?to a pseudo-code?

void main() { int i, sum, N; sum = 0; i = 1; while ( i <= 5 ) { cin >> N; sum = sum + N;

i = i + 1; } cout << sum;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 5

High-level Programming High-level Programming LanguagesLanguages

• The programmer need not manage the details of the The programmer need not manage the details of the movement of data items between memory and ALU.movement of data items between memory and ALU.– Doesn’t even have know there is a register in the ALU for Doesn’t even have know there is a register in the ALU for

performing arithmetic.performing arithmetic.• The programmer has more macroscopic view of a task, The programmer has more macroscopic view of a task,

using less primitive building blocksusing less primitive building blocks– E.g. doesn’t work with individual memory locations anymore.E.g. doesn’t work with individual memory locations anymore.

• High-level languages are portable.High-level languages are portable.– Same program can run on different architectures.Same program can run on different architectures.

• More English (pseudo-code) like!More English (pseudo-code) like!

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 6

Program TranslationProgram Translation

LOADSTORE

0101A=B+C

Compiler Assembler

010110010110

Linker Loader

01011001

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 7

The CThe C++++ Programming Programming LanguageLanguage

• We will use (a subset of) the We will use (a subset of) the C++C++ programming programming language to introduce you to programming in a language to introduce you to programming in a high-level language.high-level language.

• Although the syntax differ from one programming Although the syntax differ from one programming language to the next, the basic concepts apply language to the next, the basic concepts apply to all (most) high-level languages.to all (most) high-level languages.

• C++ is an object-oriented language C++ is an object-oriented language – although we will not learn about that in this coursealthough we will not learn about that in this course– but you can learn all about it in CMPUT114 !but you can learn all about it in CMPUT114 !

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 8

Example CExample C++++ Program Program

// Program Numerology. This program gets the user’s favorite// number and prints a greeting.

#include <iostream.h>

void main(){ int your_number;

cout << “Please enter your favorite number:”; cin >> your_number; cout << endl; cout << “Your favorite number is “ << your_number << “.” << endl; cout << “That is a nice number.” << endl;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 9

General CGeneral C++++ Program Program StructureStructure

Prologue comment [optional]Include directives [optional]Functions [optional]Main function{ Declarations [optional] Body}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 10

Structure of Example Structure of Example ProgramProgram

// This program gets the user’s favorite // number and prints a greeting.

#include <iostream.h>

void main(){ int your_number;

cout << “Please enter your favorite number:”; cin >> your_number; cout << endl; cout << “Your favorite number is “ << … cout << “That is a nice number.” << endl;}

Prologue commentInclude directivesFunctionsMain function{ Declarations Body}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 11

Virtual Data Storage (Data Virtual Data Storage (Data items)items)

• One improvement of a high-level language is to One improvement of a high-level language is to make data manipulation easier.make data manipulation easier.– J:J: .DATA.DATA -1 -- tedious in an assembly!-1 -- tedious in an assembly!– LOAD J and STORE JLOAD J and STORE J

• Instead of working with individual memory Instead of working with individual memory locations (as in assembly), we work with more locations (as in assembly), we work with more abstraction in form of abstraction in form of data itemsdata items..

• In the program we give English like names to In the program we give English like names to data items to data items to identifyidentify them.them.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 12

IdentifiersIdentifiers

• Names in programs are called Names in programs are called identifiersidentifiers..

• An identifier can consist of any combination of letters, An identifier can consist of any combination of letters, digits, and _ , except:digits, and _ , except:– cannot start with a digitcannot start with a digit– cannot be same name as a C++ keyword.cannot be same name as a C++ keyword.

• Should try to use descriptive namesShould try to use descriptive names

• Identifier are case-sensitive, for example Identifier are case-sensitive, for example – aa and and AA do refer to different data items do refer to different data items

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 13

Example of identifiersExample of identifiers• Legitimate names:Legitimate names:

– cmput101, My1stCar cmput101, My1stCar – A, b A, b – Your_Guess, Number_Of_HomerunsYour_Guess, Number_Of_Homeruns– A_speling_mistakeA_speling_mistake

• Not legitimate names (Why?)Not legitimate names (Why?)– 1stCar1stCar– int int – Iwin!Iwin!– arrrgg@#!#tarrrgg@#!#t

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 14

Data itemsData items• Store data used in program:Store data used in program:

– read in from user ( Get / In …)read in from user ( Get / In …)– constants used in program ( N: .DATA 5)constants used in program ( N: .DATA 5)

• A data item can be declared either as a A data item can be declared either as a constantconstant or a or a variablevariable..– ConstantsConstants are initialized with a value, but their value are initialized with a value, but their value

cannotcannot be changed after that. be changed after that.– The value of a The value of a variablevariable can be changed as needed. can be changed as needed.

• The keyword The keyword constconst in the declaration indicates in the declaration indicates that the data item is a constant.that the data item is a constant.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 15

Declaration of data items.Declaration of data items.

• We need to We need to declaredeclare data items in our program data items in our program prior to using them.prior to using them.

• The declaration tells:The declaration tells:– whether the data item is a whether the data item is a constantconstant or a or a

variablevariable..– the the identifieridentifier that will be used in the program to that will be used in the program to

name the data item.name the data item.– the the data typedata type for the data item. for the data item.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 16

Standard Data Types in Standard Data Types in C++C++

• Following are examples of predefined data types Following are examples of predefined data types used in C++:used in C++:– There are more basic data types.There are more basic data types.– Programmers can create their own types.Programmers can create their own types.

int an integer number (e.g. 10, -5).double a real number (e.g. 3.1415, 2.1).char a character (e.g. ‘a’, ‘C’).

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 17

ExampleExample

void main(){ // Declaring a constant. const double PI = 3.1416;

// Single variable declared at a time. int my_number; double GPA; char initial_letter;

// Can declare many data-items of the same type together. int height, base;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 18

ExampleExamplevoid main(){ // Declaring constants const int MIN_VALUE = 0; const int MAX_VALUE; // Error

MIN_VALUE = 45; // Error

cout << “MIN_VALUE is now “ << MIN_VALUE;

}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 19

Statement TypesStatement Types

• Three different kind of statements:Three different kind of statements:– Input/Output (I/O) Statements Input/Output (I/O) Statements – Assignment StatementsAssignment Statements– Control StatementsControl Statements

• Notes:Notes:– An executable statement ends with a ; (semi-colon).An executable statement ends with a ; (semi-colon).

• Can split one statement between lines!– Comments: // Indicates that the rest of the line is a Comments: // Indicates that the rest of the line is a

comment.comment.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 20

Input/Output StatementsInput/Output Statements

• In algorithms: In algorithms: – Get value of AGet value of A– Print value of APrint value of A

• In assembly:In assembly:– IN AIN A– OUT AOUT A

• In C++:In C++:– cin >> A;cin >> A;– cout << A;cout << A;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 21

Input StatementInput Statement

• The input statement reads a value from the The input statement reads a value from the input stream (keyboard) into a variableinput stream (keyboard) into a variable

• Upon entering the input statement the Upon entering the input statement the program stops and waits for the user to enter program stops and waits for the user to enter a value, e.g.a value, e.g.

The variable The variable your_numberyour_number now contains the now contains the value 24value 24

cin >> your_number;

24 <enter>

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 22

Output StatementOutput Statement

• The output statement writes a value of a The output statement writes a value of a variable(s) to the output stream (screen)variable(s) to the output stream (screen)

• We can write more than one value at a time:We can write more than one value at a time:

cout << your_number;

cout << “Your number is ” << your_number << endl;

Your number is 24

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 23

Special considerationsSpecial considerations

• We need to include the compiler directiveWe need to include the compiler directive

to tell in which library the to tell in which library the cincin and and coutcout commands are.commands are.

• When printing text we enclose it within “ “, e.g. When printing text we enclose it within “ “, e.g. – cout << “My lucky number is: ” << endl; cout << “My lucky number is: ” << endl; – endlendl forces a line-break on the screen forces a line-break on the screen

#include <iostream.h>

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 24

Example program using Example program using I/OI/O

• Let us look at our example program againLet us look at our example program again// Example Program Using I/O. #include <iostream.h>

void main(){ int your_number;

cout << “Please enter your favorite number:”; cin >> your_number; cout << endl; cout << “Your favorite number is “ << your_number << endl; cout << “That is a nice number.” << endl;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 25

Output when we run the Output when we run the programprogram

Please enter your favorite number:

2

Your favorite number is 24That is a nice number.

4 <enter>

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 26

The Assignment StatementThe Assignment Statement

• The assignment statement assigns a value to a The assignment statement assigns a value to a program variable.program variable.

• General format in C++:General format in C++:

The expression to the right gets evaluated, and The expression to the right gets evaluated, and the result is written into the memory location the result is written into the memory location referenced to by the variable.referenced to by the variable.

<variable> = <expression>;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 27

Examples of assignmentsExamples of assignmentsvoid main(){ int A, B, C; int my_number, your_number, our_number;

A = 0; B = -2; C = (A-B) / B + (2*B) ; ... my_number = 5; your_number = 3; our_number = my_number + your_number; ...}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 28

Arithmetic Operations in Arithmetic Operations in ExpressionsExpressions

AdditionAddition ++ C = A + B;C = A + B;

SubtractionSubtraction -- C = A – B;C = A – B;

MultiplicationMultiplication ** C = A * B;C = A * B;

DivisionDivision // C = A / B;C = A / B;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 29

A Practice ProblemA Practice Problem

Write a program that calculates the area of a triangle, Write a program that calculates the area of a triangle, given its height and base.given its height and base.

heightheight

basebase

A = (height x base) / 2A = (height x base) / 2

Get values for height and baseSet value of area to (height*base)/2Print value of area

Write the algorithm in pseudo-code:Write the algorithm in pseudo-code:

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 30

// This program calculates the area of a triangle, given its // height and base.#include <iostream.h>void main() { double area, height, base;

cout << “Enter the height of the triangle:”; cin >> height; cout << “Enter the base of the triangle:”; cin >> base;

area = (height * base) / 2; // Note parentheses!

cout << “ The area of the triangle is “ << area << endl;}

CC++++ code code

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 31

Running Our ProgramRunning Our Program

Enter the height of the triangle: 2

The area of the triangle is 4

Enter the base of the triangle: 4

Enter the height of the triangle: 10

The area of the triangle is 25

Enter the base of the triangle: 5

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 32

Control Flow StatementsControl Flow Statements

• We have three types of a control flow in a We have three types of a control flow in a program:program:

–SequentialSequential

–ConditionalConditional

–LoopingLooping

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 33

Sequential Flow of ControlSequential Flow of Control

• The default case.The default case.• No special commands needed.No special commands needed.

S3

S2

S1

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 34

Example:Sequential Flow Example:Sequential Flow in C++in C++

// An example of sequential flow.

#include <iostream.h>

void main(){ int your_number;

cout << “Please enter a number:”; cin >> your_number; cout << “Your number is “ << your_number << “.” << endl;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 35

Example Program OutputExample Program Output

Please enter a number: 2

Your number is 2.

Please enter a number: 5

Your number is 5.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 36

Conditional Flow of ControlConditional Flow of Control

• Begins with evaluating a Begins with evaluating a Boolean Boolean condition.condition.

• If condition is If condition is true,true, then execute then execute statement S1.statement S1.

• Otherwise, if condition is Otherwise, if condition is false,false, execute statement S2.execute statement S2.

• In both cases, statement S3 is In both cases, statement S3 is executed next.executed next.

S3

S2

true false

S1

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 37

If-else Statement in CIf-else Statement in C++++

if ( <boolean expression> )<statement-1>;

else<statement-2>;

if ( <boolean expression> )<statement-1>;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 38

Example: Example: Conditional Flow Conditional Flow in Cin C++++

// An example of conditional flow.#include <iostream.h>void main(){

const int lucky_number = 8; int your_number;

cout << “Please guess my lucky number:”; cin >> your_number; cout << “Your number is “ << your_number << “.” << endl; if ( your_number == lucky_number ) // boolean expression cout << “You win!”; else cout << “You lose!”;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 39

Example Program OutputExample Program Output

Please, guess my lucky number: 2

You lose!

Please, guess my lucky number: 8

You win!

Your number is 2.

Your number is 8.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 40

Multi-way If-else Multi-way If-else StatementStatement

if ( <condition> )...

else if ( <condition> ) ...

else if ( <condition> ) ...

else...

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 41

Boolean Conditions Boolean Conditions (Expressions)(Expressions)

• Expression can be either Expression can be either truetrue or or falsefalse..

ExpressionExpression A=0; B=1;A=0; B=1; A=1; B=2;A=1; B=2;

A == 0A == 0

A != BA != B

(A+1) < B(A+1) < B

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 42

C++ Comparison C++ Comparison OperatorsOperators

The same value asThe same value as ==== 2 == 52 == 5 falsefalse

Less thanLess than << 2 < 52 < 5 truetrue

Less than or equal toLess than or equal to <=<= 5 <= 55 <= 5 truetrue

Greater thanGreater than >> 2 > 52 > 5 falsefalse

Greater than or equal toGreater than or equal to >=>= 2 >= 52 >= 5 falsefalse

Not the same value asNot the same value as !=!= 2 != 52 != 5 truetrue

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 43

Examples: Comparison Examples: Comparison OperatorsOperators

if ( your_number == 8 ) cout << “You win!”; else cout << “You lose!”;

if ( your_weight_lbs > your_ideal_weight_lbs ) cout << “You need to diet!”; else cout << “More ice-cream?”;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 44

CC++++ Boolean Operators Boolean Operators

• Boolean operators can be used to make more Boolean operators can be used to make more complex Boolean expressions.complex Boolean expressions.

ANDAND &&&& (2<5) && (2>7)(2<5) && (2>7) falsefalse

OROR |||| (2<5) || (2>7)(2<5) || (2>7) truetrue

NOTNOT !! !(2==5)!(2==5) truetrue

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 45

Examples: Boolean Examples: Boolean OperatorsOperators

if ( (your_number > 5) && (your_number<8) ) cout << “You win!”; else cout << “You lose!”;

if ( (your_weight < your_lower_limit_weight ) || (your_weight > your_upper_limit_weight) ) cout << “See your doctor about your weight.”; else cout << “You are in a good shape.”;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 46

Compound StatementsCompound Statements

• What if we want to execute more than one What if we want to execute more than one statement within a if-statement?statement within a if-statement?– We can group arbitrary many statements together by We can group arbitrary many statements together by

enclosing them within { }.enclosing them within { }.

{{ <statement-1>; <statement-1>; <statement-2>; <statement-2>;} }

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 47

Example: Compound Example: Compound statementsstatements

if ( (your_number > 5) && (your_number<8) ) { cout << “You win!”; cout << “Guess you got lucky!”; } else { cout << “You lose!”; cout << “You’ll never guess the right number!”; }

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 48

// Example program using a compound if-else statement.#include <iostream.h>void main() {

int your_number, my_number;

cout << “Please enter a positive number:”; cin >> your_number;

if ( your_number >= 0 ) // need to use a compound form { my_number = 2 * your_number; cout << “My number is “ << my_number; }

else // not necessary to use a compound form. {

cout << “Sorry, your number is negative!” << endl; }}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 49

Looping Flow of Control Looping Flow of Control (while)(while)

• Begins with evaluating a Begins with evaluating a Boolean Boolean conditioncondition..

• While condition is While condition is truetrue execute execute statement statement S1S1 and then re-evaluate and then re-evaluate Boolean conditionBoolean condition. Repeat until .... Repeat until ...

• ... condition is ... condition is falsefalse,, then go to then go to statement statement S2S2..S2

true

false

S1

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 50

While-loop Statement in While-loop Statement in CC++++

while ( <Boolean expression> ) {

<statement-1>;...

<statement-n>;}

while ( <Boolean expression> ) <statement-1>;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 51

Examples of while loopsExamples of while loops

while ( i <= 5 ) {

cout << "Enter a grade: ";cin >> grade;total = total + grade;i = i + 1;

}

while ( M >= 1 ) M = M - 2;

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 52

What does this program What does this program print out?print out?

// What is the output?#include <iostream.h>void main() {

int number; number = 1; while ( number > 0 ) cout << number << endl; number = number - 1;

cout << number;}

// What is the output?#include <iostream.h>void main() {

int number; number = 1; while ( number > 0 ) { cout << number << endl; number = number - 1; } cout << number;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 53

// Example #1: Use of the while statement.// The user guesses the program’s lucky number!#include <iostream.h>void main() {

const int lucky_number = 8; int your_number ;

cout << "Please, guess my lucky number: "; cin >> your_number;

while ( your_number != lucky_number ) {

cout << "Sorry, enter another number: "; cin >> your_number; }

cout << "You guessed " << lucky_number << ", my lucky number!";}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 54

Example #1: Program Example #1: Program OutputOutput

Please, guess my lucky number: 2

Sorry, enter another number: 6

Sorry, enter another number: 9

Sorry, enter another number: 8

You guessed 8, my lucky number!

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 55

// Example #2: Use of the while-statement.// The user enters a number, and the program divides // the number in half while it is greater or equal to one, // printing out all the intermediate results.#include <iostream.h>

void main() { int number;

cout << "Enter a number: "; cin >> number;

while ( number >= 1 ) { cout << number << endl; number = number / 2; }}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 56

Example #2: Program Example #2: Program OutputOutput

Enter a number: 40

20

10

5

2

1

40

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 57

// Example #3: Use of the while statement.// The program determines if a given number is odd or even.#include <iostream.h>void main() {

int number ;

cout << "Enter a positive number: "; cin >> number;

while ( number >= 1 ) {

number = number - 2; }

if ( number == 0 ) cout << "The number is even."; else cout << "The number is odd.";}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 58

Example #3: Program Example #3: Program OutputOutput

Enter a positive number: 4

The number is even.

Enter a positive number: 7

The number is odd.

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 59

Practice Problem 1Practice Problem 1• Write a program that calculates the user's GPA. Before entering Write a program that calculates the user's GPA. Before entering

the grades the user first enters how many grades there are.the grades the user first enters how many grades there are.

Get a value for N, the number of coursesSet the value of total to 0Set the value of i to 1While i N do Get a value for grade Set total to ( total + grade ) Increase the value of i by 1End loopSet the value of GPA to ( total / N )Print the value of GPA

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 60

// Example #4: This program calculates GPA.#include <iostream.h>void main() {

int i, N; double grade, GPA, total;

total = 0.0; cout << "Enter the number of courses taken: "; cin >> N; i = 1; while ( i <= N ) { cout << "Enter a grade: "; cin >> grade; total = total + grade; i = i + 1; } GPA = total / N; cout << "The GPA is " << GPA << endl;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 61

Practice Problem 1: Practice Problem 1: Program OutputProgram Output

Enter the number of courses taken: 5

Enter a grade: 5

Enter a grade: 7

Enter a grade: 8

Enter a grade: 5

Enter a grade: 8

The GPA is 6.6

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 62

Practice Problem 2 Practice Problem 2 (take one)(take one)

• Write a program that reads in 5 integers and Write a program that reads in 5 integers and prints out the numbers that are larger than the prints out the numbers that are larger than the last number entered (i.e. the fifth number).last number entered (i.e. the fifth number).

Get values for N1, N2, ..., N5

Set i to 1While i 5 do If Ni > N5 then

Print Ni

Increase i by 1End loop

• How do we write this algorithm in C++?How do we write this algorithm in C++?

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 63

The Array Data TypeThe Array Data Type• An An arrayarray groups together a collection of data groups together a collection of data

items of the same type, e.g.items of the same type, e.g.

• In a C++ program we: In a C++ program we: – Specify the Specify the sizesize of the array when we declare it. of the array when we declare it.– Use an index in the range Use an index in the range 0, ..., size-10, ..., size-1 to refer to to refer to

individual elements in the array.individual elements in the array.

55 66 11 99 44 55 33 88 1010 55

00 11 22 33 44 55 66 77 88 99

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 64

Arrays in C++Arrays in C++#include <iostream.h>void main() {

int grade[10]; // Declaring an array of 10 integers. int i;

grade[0] = 9; grade[1] = 6; ... grade[9] = 8;

i = 0; // Note: indexing range is from 0 ... 9 while ( i < 10 ) { cout << grade[ i ] << endl; i = i + 1; }}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 65

Arrays in C++Arrays in C++// This program reads in 5 integers and stores them in an array.#include <iostream.h>

void main(){ const int MAX = 5; // The number of integers to read in. int a[MAX]; int n, i;

i = 0; while ( i < MAX ) { cout << "Enter a number: "; cin >> n; // Note: Why not cin >> a[ i ] ? Limitation in lab-software! a[ i ] = n; i = i + 1; }}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 66

Practice Problem 2 Practice Problem 2 (take two)(take two)

Get values for N1, N2, ..., N5

Set i to 1While i 5 do If Ni > N5 then

Print Ni

Increase i by 1End loop

• Write a program that reads in 5 integers and Write a program that reads in 5 integers and prints out the numbers that are larger than the prints out the numbers that are larger than the last number entered (i.e. the fifth number).last number entered (i.e. the fifth number).

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 67

#include <iostream.h>void main() { const int MAX = 5; // Number of values to read in. int i, n, N[MAX];

// Read in the integers; use a loop! cout << "Enter the numbers: " << endl; i = 0; while ( i < MAX ) { cin >> n; N[ i ] = n; ++i; // Note: same as i = i + 1; }

// Print out the numbers that are larger than the last (fifth) number. cout << "Larger than last:"; i = 0; // Remember to reset i while ( i < MAX-1 ) { // Note: MAX-1 ! if ( N[ i ] > N[ MAX-1 ] ) cout << " " << N[ i ]; i = i + 1; }}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 68

Enter the numbers:2

5

18

4

5Larger than last: 8

Practice Problem 2: Practice Problem 2: Program OutputProgram Output

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 69

Repeat LoopsRepeat Loops• What if we use a Repeat loop in the algorithm?What if we use a Repeat loop in the algorithm?

Get values for N1, N2, ..., N5

Set i to 1Repeat until i 5 do If Ni > N5 then

Print Ni

Increase i by 1End loop

• How do we code Repeat loops in C++?How do we code Repeat loops in C++?

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 70

Repeat vs. WhileRepeat vs. While

• We can always rewrite a Repeat as a While loopWe can always rewrite a Repeat as a While loop– C++ has a loop similar to Repeat, but we will not look C++ has a loop similar to Repeat, but we will not look

at that in this course.at that in this course.

Get values for N1, N2, ..., N5

Set i to 1While i 5 do If Ni > N5 then Print Ni

Increase i by 1 End loop

Get values for N1, N2, ..., N5

Set i to 1Repeat until i 5 do If Ni > N5 then Print Ni

Increase i by 1 End loop

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 71

Elements Correctness and Elements Correctness and StyleStyle

• Important to make our programs correct:Important to make our programs correct:– Logically correct Logically correct (do what supposed to do)(do what supposed to do)– Syntactically correct Syntactically correct (so can compile)(so can compile)

• Also, important to make them readable (why?): Also, important to make them readable (why?): – No more than one statement in each line.No more than one statement in each line.– Proper indentation.Proper indentation.– Descriptive identifier names.Descriptive identifier names.– Documentation ( comments ).Documentation ( comments ).

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 72

What does this program What does this program do?do?

#include <iostream.h> void main() { int x; int q10; x=1; cout << "Enter a number: "; cin >> q10; while ( q10 > 1 ) { x = x * q10; q10 = q10 - 1; } cout << x; }

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 73

Continued … Continued … One statement One statement each lineeach line

#include <iostream.h>void main() {

int x;int q10;

x=1;cout << "Enter a number: ";cin >> q10;

while ( q10 > 1 ) {

x = x * q10;q10 = q10 - 1; }

cout << x;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 74

Continued … Continued … Proper Proper indentationindentation

#include <iostream.h>void main() {

int x; int q10;

x = 1; cout << "Enter a number: "; cin >> q10;

while ( q10 > 1 ) { x = x * q10; q10 = q10 - 1; } cout << x;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 75

Continued … Continued … Descriptive Descriptive identifier namesidentifier names

#include <iostream.h>void main() {

int factorial; int n;

factorial = 1; cout << "Enter a number: "; cin >> n;

while ( n > 1 ) {

factorial = factorial * n; n = n - 1; }

cout << factorial;}

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson 76

Continued … Continued … Documentation Documentation added.added.// Given a number n the program outputs n factorial, e.g.

// n! = n * (n-1) * (n-2) * … * 2 * 1#include <iostream.h>void main() { int factorial; int n;

factorial = 1; // 0! = 1 cout << "Enter a number: "; cin >> n;

while ( n > 1 ) { factorial = factorial * n; n = n - 1; } cout << factorial;}