Sie sind auf Seite 1von 7

Basics of computation

Iteration, Selection, Function, and Vector


Selection
how to select between two alternative actions

Iteration
how to iterate over a series of values
Function
how a particular sub-computation can be named and
specified separately as a function.
Vector
how to use the vector type to hold sequences of values. To
be able to perform more realistic computations.

Expressions

You already know most of this


Note:

int length = 20;

You know how to do arithmetic


d = a+b*c
You know how to select
if this is true, do that; otherwise do something else
You know how to iterate
do this until you are finished
do that 100 times
You know to do functions
go ask Google and bring back the answer
hey Google, calculate this for me and send me the answer

// the simplest expression: a literal (here, 20)


// (here used to initialize a variable)

int width = 40;


int area = length*width;

// a multiplication

When needed, we can use parentheses to group expressions


int average = ( length + width ) /2;

// addition and division

=> int average = length/2 + width/2;


> int average = length + width /2;

What I will show you today is mostly just vocabulary and


syntax for what you already know

This error is logical and cannot be found by the compiler.


you know the mathematical definition of an average, but the compiler doesn't.
3

Operators

Operators

Expressions are made out of operators and operands


Operators specify what is to be done, (*,+, -,etc)
Operands specify the data for the operators to work with (a, b, c,etc)

Boolean type: bool


(true and false)
Equality operators: = = (equal), != (not equal)
Logical operators: && (and), || (or), ! (not)
Relational operators: < (less than), > (greater than), <=, >=
Integer types: short, int, long

a * b + c /d

arithmetic operators: +, -, *, /, % (remainder)

Floating-point types: e.g., float, double

Operators

10

(e.g., 12.45 and 1.234e3)

arithmetic operators: +, -, *, /

11

Concise Operators

a += c

means

a = a+c

a *= scale

means

a = a*scale

++a

means
or

a += 1
a = a+1

Conversions
2.5/2 = ?
is a double divided by an int
is a Floating-point division or integer division?
5/2 = ?
is an int divided by an int

12

14

Conversions

Quiz

The rule here is:

double d = 2.5;
int i = 2;

- if an operator has an operand of type double


- we use f loating-point arithmetic yielding a double result;
-

free upgrade!

double d2 = d/i;
int i2 = d/i;

- otherwise
- we use integer arithmetic yielding an int result
(Integer division throws away the remainder)

then, d2 = ?
i2= ?
15

Selection

Selection

Sometimes we must select between alternatives. In C++, that is


done using either an if-statement or a switch-statement

E.g, suppose we want to identify the larger of two values. We


can do this with an if statement

The syntax is
if (condition)
statement1
else
statement2

16

if (a<b)
// Note: No semicolon here
cout<<"max is "<< b<<\n;
else
// Note: No semicolon here
cout<<"max is "<< a<<\n;

// if the condition is true, do statement1


// if not, do statement2

You are making selection decision all the time!

E.g, Cross the street at a traffic light, you had to wait for the light to tum
green

if (traffic_light ==green )
go();
else
wait();
18

19

Selection

Selection

When you have more than two choices:


if(expression)
statement
else if(expression)
statement
else
statement

Switch-statement
comparison of a value against constants
a statement is chosen

//1st alternative

//2nd alternative
//3rd alternative

each case is terminated by a break.

the statement identified by the default


label is chosen

if(traffic_light == green)
walk();
else if(traffic_light == yellow)
run();
else
wait();

if the value equals the constant in a case label

if the value doesn't match any of the case labels


You don't have to provide a default if you are certain
that you have listed every alternative

char c;
cin>>c;
switch(c)
{
case y:
//.
break;
case n:
//
break;
default:
//
break;
}

20

Selection

21

Selection
string s;
cin>>s;
switch(s)
{
case no:
//.
break;
case yes:
//
break;
default:
//
break;
}

Error!
The value on which we switch must be of
an integer, char, or enumeration type.

22

Selection

23

Iteration
We rarely do something only once. Therefore,

programming languages provide convenient ways of


doing something several times.
Repetition or iteration
int i=0;
While(i<100)
{
cout<<++i;
}

24

25

Iteration (while loop)

Iteration (for loop)

A while loop takes


A loop variable (control variable);
Initialize the control variable;
A termination criterion;
Increment the control variable;
Something to do for each iteration;

for loop
You can collect all the control information in one
place, at the top, where its easy to see.

here: i
here: int i = 0
here: if i<100 is false, terminate
here: ++i
here: cout <<

for (initialize; condition ; increment )


controlled statement
for (int i = 0; i<100; ++i)
{
cout << i << '\t;
}

int i=0;
While(i<100)
{
cout<<++i;
}

or
int i = 0;
for ( ; i<100 ; ++i)
or
int i = 0;
for ( ; i++<100 ; )

26

27

Functions

Iteration with Function

what was square(i)?

// calculate and print a table of squares 0-99:


int main()
{
int i = 0;
while (i<100)
{
cout << i << '\t' << square(i) << '\n';
++i ;
}
}

cout << i << '\t' << square(i) << '\n';

Why we use functions?


We define a function because it
is logically separate

/*
The worlds first real program running on a stored-program computer
(David Wheeler, Cambridge, May 6, 1949)
(No, it wasnt actually written in C++ J.)

makes the program text clearer (by naming the computation)

is useful and reusable in more than one place in our program

eases testing, distribution of labor, and maintenance

*/
28

29

Control Flow

Functions
Our function

int main()

int square(int x)
{
return x*x;
}

int square(int x)

i=0;

return x * x;

while (i<100)

is an example of

Return_type function_name ( Parameter list )


// (type name, etc.)
{
// use each parameter in code
return some_value;
// of Return_type
}

cout << i << '\t << square(i) << '\n';


++i ;
}
}
30

31

Another Example

Control Flow

Earlier we looked at code to find the larger of two values. Here is a

function that compares the two values and returns the larger value.

int main()
{
i=0;

int square(int x)

int max(int a, int b) // this function takes 2 parameters

{
if (a<b)
return b;
return x * x;

while (i<100)

else
return a;

}
int x = max(7, 9);
int y = max(19, -27);
int z = max(20, 20);

cout << i <<'\t << square(i) << '\n';

i<100

i==100
++i;

// x becomes 9
// y becomes 19
// z becomes 20

32

33

Exercise
words
E.g.,
Input:

Stroustrup/Programming

Write a program to detect the repeated (adjacent)

Vector
If we have a collection of data to work on.
We can store this data in a vector
The most useful, simplest ways of storing a collection

data
E.g. a list of student ID, a list of student grades, etc.

The cat cat jumped to the the bridge

A vector holds a sequence of elements


Ouput:

that you can access by an index

Repeated word: cat


Repeated word: the

Indices for a vector start with 0 and increase by 1


34

36

Vector

Vector

a vector doesn't just store its elements, it also stores its

Wrong element type

size
to make a vector we need to specify:
the type of element

A default value

The element type comes after vector in angle brackets <T>

the initial number of elements

comes after the name in parentheses ()

Or.specify another
vector<int> v(10,-3);

37

The size of a vector can be obtained by


size()
38

Growing a vector

Growing a vector
start a vector empty and grow it to its desired size
Using a member function of vector push_back(element);
vector<int> v;
// start off empty
v.push_back(1);
// add an element with the value 1
// v[0] = 1
v.push_back(4);
// add an element with the value 4
// v[1] = 4
v.push_back(3);
// add an element with the value 3
// v[2] = 3

Size
(Empty vector)

v:

v:

v:

v:

39

// read some temperatures into a vector:


int main()
{
vector<double> temps;
// declare a vector of type double to store
// temperatures like 62.4
double temp;
// a variable for a single temperature value
while (cin>>temp)
// cin reads a value and stores it in temp
temps.push_back(temp); // store the value of temp in the vector
// do something
}
// cin>>temp will return true until we reach the end of file or encounter
// something that isnt a double: like the word end
40

Example(3)

Example(3)

int main()
// compute mean (average) temperatures:
{
vector<double> temps;
// temperatures in Fahrenheit, e.g. 64.6
double temp;
while (cin>>temp)
temps.push_back(temp); // read and put into vector

int main()
// compute mean (average) temperatures:
{
vector<double> temps;
// temperatures in Fahrenheit, e.g. 64.6
double temp;
while (cin>>temp)
temps.push_back(temp); // read and put into vector

double mean = 0;
//implement your code here.

double sum = 0;
for (int i = 0; i < temps.size(); ++i)
sum += temps[i]; // sums temperatures

cout << Mean temperature: << mean << endl;

cout << "Mean temperature: " << sum/temps.size() << endl;


}

}
41

Example(3)

42

Vector

int main()
// compute median temperatures:
{
vector<double> temps;
// temperatures in Fahrenheit, e.g. 64.6
double temp;
while (cin>>temp)
temps.push_back(temp); // read and put into vector

is similar to an array in C and other languages


Difference:
you need not specify the size of a vector in advance

you can add as many elements as you like

Other useful properties

sort(temps.begin(), temps.end());
//sorting the contained numbers from small to large. A STL algorithm
cout << "Median temperature: " << temps[temps.size()/2] << endl;

http://www.cplusplus.com/reference/stl/vector/

43

44

Example(4) - list words


/*
read a bunch of strings into a vector,
sort them into alphabetical order (a, b, c, d,., x, y, z,...),
and print the strings from the vector to see what we have.
*/
int main()
{
vector<string> words;
string s;
while (cin>>s && s != "quit") // && means AND
words.push_back(s);
sort(words.begin(), words.end()); // sort the words we read
//sort() is also a generic algorithm function of the STL
}

for (int i=0; i<words.size(); ++i)


cout<<words[i]<< "\n";

46

Das könnte Ihnen auch gefallen