More on functions - CS319: Scientific Computing (with...

35
CS319: Scientific Computing (with C++) More on functions Week 3: 9am and 4pm , 29 Jan 2020 Source: http://xkcdsw.com/1105 1 Output Manipulators 2 Input 3 Flow of control: if-blocks 4 Loops 5 Functions void functions 6 Pass-by-value 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise operators CS319 — More on functions 1/35

Transcript of More on functions - CS319: Scientific Computing (with...

Page 1: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

CS319: Scientific Computing (with C++)

More on functionsWeek 3: 9am and 4pm, 29 Jan 2020

Source: http://xkcdsw.com/1105

1 Output Manipulators2 Input3 Flow of control: if-blocks4 Loops5 Functions

void functions6 Pass-by-value7 Function overloading8 A detailed example9 Default values10 Bitwise operators

CS319 — More on functions 1/35

Page 2: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Output Manipulators endl

As well as passing variable names and strings to the output stream, wecan also pass manipulators to change how variable values are displayed.Some manipulators (e.g., setw) require that iomanip is included.

I endl print a new line (and flush)

01Manipulators.cpp

8 #include <iomanip >

10 int main()

{

12 int i, fib [12];

fib [0]=1; fib [1]=1;

std::cout << "\n\nWithout the setw manipulator" << std::endl;

16 for (i=2; i<12; i++)

{

18 fib[i] = fib[i-1] + fib[i-2];

std::cout << "Entry " << i << " in the " <<

20 "Fibonacci Sequence is " << fib[i] << std::endl;

}

CS319 — More on functions 2/35

Page 3: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Output Manipulators setw

I setw(n) will the width of a field to n. Useful for tabulating data.

01Manipulators.cpp

22 std::cout << "\n\nWith the setw manipulator" << std::endl;

for (i=2; i<12; i++)

24 {

fib[i] = fib[i-1] + fib[i-2];

26 std::cout << "Entry " << std::setw (2) << i << " in the " <<

"Fibonacci Sequence is " << std::setw (3) << fib[i] << std::endl;

28 }

return (0);

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Other useful manipulators:

I setfill

I setprecision

I fixed and scientific

I dec, hex, oct

CS319 — More on functions 3/35

Page 4: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Input

In C++, the object cin is used to take input from the standard inputstream (usually, this is the keyboard). It is a name for the C onsoleIN put.

In conjunction with the operator >> (called the get from or extractionoperator), it assigns data from input stream to the named variable.

(Later we will see that cin is an object, with more sophisticateduses/methods than is going to be shown here. However, we will deferthis discussion until we have studied something of objects and classes).

CS319 — More on functions 4/35

Page 5: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Input

02Input.cpp

6 #include <iostream >

#include <iomanip > // needed for setprecision

using namespace std;

int main()

12 {

const double StirlingToEuro =1.17703; // Correct 22/01/2020

14 double Stirling;

cout << "Input amount in Stirling: ";

16 cin >> Stirling;

cout << "That is worth " << Stirling*StirlingToEuro <<

18 " Euros\n";

cout << "That is worth " << fixed << setprecision (2) <<

20 "\u20AC" << Stirling*StirlingToEuro << endl;

return (0);

22 }

CS319 — More on functions 5/35

Page 6: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

if statements are used to conditionally execute part of your code.

Structure (i):

if ( exprn )

{

statements to execute if exprn evaluates as

non-zero

}

else

{

statements if exprn evaluates as 0

}

CS319 — More on functions 6/35

Page 7: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

The argument to if() is a logical expression.

ExampleI x == 8

I m == ’5’

I y <= 1

I y != x

I y > 0

More complicated examples can be constructed using

I AND &&

and

I OR ||.

CS319 — More on functions 7/35

Page 8: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

03EvenOdd.cpp

#include <iostream >

int main(void)

12 {

int Number;

std::cout << "Please enter an integrer: ";

16 std::cin >> Number;

18 if ( (Number %2) == 0)

std::cout << "That is an even number." << std::endl;

20 else

std::cout << "That number is odd." << std::endl;

return (0);

24 }

CS319 — More on functions 8/35

Page 9: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

More complicated examples are possible:

Structure (ii):

if ( exp1 )

{statements to execute if exp1 is “true”

}else if (exp2 )

{statements run if exp1 is “false” but exp2 is “true”

}else

{“catch all” statements if neither exp1 or exp2 true.

}

CS319 — More on functions 9/35

Page 10: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

04Grades.cpp

10 int main(void)

{

12 int NumberGrade;

char LetterGrade;

std::cout << "Please enter the grade (percentage ): ";

16 std::cin >> NumberGrade;

18 if ( NumberGrade >= 70 )

LetterGrade = ’A’;

20 else if ( NumberGrade >= 60 )

LetterGrade = ’B’;

22 else if ( NumberGrade >= 50 )

LetterGrade = ’C’;

24 else if ( NumberGrade >= 40 )

LetterGrade = ’D’;

26 else

LetterGrade = ’E’;

std::cout << "A score of " << NumberGrade << "% cooresponds to a "

30 << LetterGrade << "." << std::endl;

}

CS319 — More on functions 10/35

Page 11: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Flow of control: if-blocks

The other main flow-of-control structures are the ?: operator, andswitch ... case structures.

Example (How to use ?: with std::cout)

Exercise 2.1Find out how switch... case construct works, and write a programthat uses it.

CS319 — More on functions 11/35

Page 12: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Loops for loops

We meet a for-loop briefly in the Fibonacci example. The mostcommonly used loop structure is for

for(initial value; test condition; step)

{// code to execute inside loop

}

Example: 05CountDown.cpp

10 int main(void)

{

12 int i;

14 for (i=10; i>=1; i--)

std::cout << i << "... ";

std::cout << "Zero!\n";

return (0);

20 }

CS319 — More on functions 12/35

Page 13: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Loops for loops

The other two common forms of loop in C++ are

I while loops

I do ... while loops

Exercise 2.2Rewrite the count down example above using a

1. while loop.

2. do ... while loop.

CS319 — More on functions 13/35

Page 14: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions

A good understanding of functions, and their uses, is of primeimportance.

Some functions return/compute a single value. However, many importantfunctions return more than one value, or modify one of its ownarguments.

For that reason, we need to understand the difference betweencall-by-value and call-by-reference (←− later).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Every C++ program has at least one function: main()

Example#include <iostream>

int main(void )

{

/* Stuff goes here */

return(0);

}

CS319 — More on functions 14/35

Page 15: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions

Each function consists of two main parts:

I Function “header” or prototype which gives the function’sI return value data type, or void if there is none, andI parameter list data types or void if there are none.

The prototype is often given near the start of the file, before themain() section.Important: The prototype should be written before thefunction—perhaps when the program is begin specified.

I Function definition. Begins with the function names, parameter listand return type, followed by the body of the function containedwithin curly brackets.

CS319 — More on functions 15/35

Page 16: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions

Format:ReturnType FnName ( param1, param2, ...)

{statements

}

I ReturnType is the data type of the data returned by the function.

I FnName the identifier by which the function is called.

I Param1, ... consists ofI the data type of the parameterI the name of the parameter will have in the function. It acts within

the function as a local variable.

I the statements that form the function’s body, contained with braces{...}.

CS319 — More on functions 16/35

Page 17: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions E.g, Prime?

06IsComposite.cpp

bool IsComposite(int i)

30 {

int k;

32 for (k=2; k<i; k++)

if ( (i%k) == 0)

34 return(true);

36 // If we get to here, then i has no divisors between 2 and i-1

return(false);

38 }

CS319 — More on functions 17/35

Page 18: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions E.g, Prime?

Calling the IsComposite function:

06IsComposite.cpp

12 int main(void )

{

14 int i;

16 std::cout << "Enter a natural number: ";

std::cin >> i;

std::cout << i << " is a " <<

20 (IsComposite(i) ? "composite":"prime") << " number."

<< std::endl;

return (0);

24 }

CS319 — More on functions 18/35

Page 19: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions void functions

Most functions will return some value. In rare situations, they don’t, andso have a void argument list.

07Kth.cpp

#include <iostream >

void Kth(int i);

int main(void )

14 {

int i;

std::cout << "Enter a natural number: ";

18 std::cin >> i;

20 std::cout << "That is the ";

Kth(i);

22 std::cout << " number." << std::endl;

24 return (0);

}

CS319 — More on functions 19/35

Page 20: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Functions void functions

07Kth.cpp (continued)

26 // FUNCTION KTH

// ARGUMENT: single integer

28 // RETURN VALUE: void (does not return a value)

// WHAT: if input is 1, displays 1st, if input is 2, displays 2nd,

30 // etc.

void Kth(int i)

32 {

std::cout << i;

34 i = i%100;

if ( ((i%10) == 1) && (i != 11))

36 std::cout << "st";

else if ( ((i%10) == 2) && (i != 12))

38 std::cout << "nd";

else if ( ((i%10) == 3) && (i != 13))

40 std::cout << "rd";

else

42 std::cout << "th";

}

CS319 — More on functions 20/35

Page 21: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Pass-by-value

In C++ we need to distinguish between

I a variable

I the value stored in it.

The classic example is function that

I takes two integer inputs, a and b;

I after calling the function, the values of a and b are swapped.

CS319 — More on functions 21/35

Page 22: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Pass-by-value

08SwapByValue.cpp

4 #include <iostream >

void Swap(int a, int b);

int main(void )

8 {

int a, b;

std::cout << "Enter two integers: ";

12 std::cin >> a >> b;

14 std::cout << "Before Swap: a=" << a << ", b=" << b

<< std::endl;

16 Swap(a,b);

std::cout << "After Swap: a=" << a << ", b=" << b

18 << std::endl;

return (0);

20 }

CS319 — More on functions 22/35

Page 23: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Pass-by-value

void Swap(int x, int y)

{

int tmp;

tmp=x;

x=y;

y=tmp;

}

This won’t work.We have passed only the values storedin the variables a and b. In the swap

function these values are copied to localvariables x and y . Although the localvariables are swapped, they remainedunchanged in the calling function.

What we really wanted to do here was to use Pass-By-Reference wherewe modify the contents of the memory space referred to by a and b. Thisis easily done...

...we just change the declaration and prototype from

void Swap(int x, int y) // Pass by value

to

void Swap(int &x, int &y) // Pass by Ref

the pass-by-reference is used.CS319 — More on functions 23/35

Page 24: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Function overloading

C++ has certain features of polymorphism – for example, where twodifferent functions can have the same name, so long as they havedifferent argument lists.

This is called function overloading.

As a simple example, we’ll write two functions with the same name: onethat swaps the values of a pair of ints, and that other that swaps a pairof floats. (Later in the course, we’ll see how to do this withtemplates.)

09Swaps.cpp

#include <iostream >

// We have two function prototypes!

10 void Swap(int &a, int &b);

void Swap(float &a, float &b);

CS319 — More on functions 24/35

Page 25: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Function overloading

09Swaps.cpp (continued)

int main(void)

14 {

int a, b;

16 float c, d;

18 std::cout << "Enter two integers: ";

std::cin >> a >> b;

20 std::cout << "Enter two floats: ";

std::cin >> c >> d;

std::cout << "a=" << a << ", b=" << b <<

24 ", c=" << c << ", d=" << d << std::endl;

std::cout << "Swapping ...." << std::endl;

Swap(a,b);

28 Swap(c,d);

30 std::cout << "a=" << a << ", b=" << b <<

", c=" << c << ", d=" << d << std::endl;

return (0);

34 }

CS319 — More on functions 25/35

Page 26: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Function overloading

09Swaps.cpp (continued)

void Swap(int &a, int &b)

40 {

int tmp;

tmp=a;

44 a=b;

b=tmp;

46 }

48 void Swap(float &a, float &b)

{

50 float tmp;

52 tmp=a;

a=b;

54 b=tmp;

}

CS319 — More on functions 26/35

Page 27: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Function overloading

What does the compiler take into account to distinguishbetween overloaded functions?

C++ takes the following into account:

I Type of arguments. So void Sort(int, int) is different fromvoid Sort(char, char).

I The number of arguments. So int Add(int a, int b) isdifferent from int Add(int a, int b, int c).

But not

I Return values. For example, we cannot have two functionsint Convert(int) and float Convert(int)

since they have the same argument list.

I user-defined types (using typedef) that are in fact the same. See,for example, 10OverloadedConvert.cpp.

CS319 — More on functions 27/35

Page 28: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

A detailed example

In the following example, we combine two features of C++ functions:

I Pass-by-reference,

I Overloading,

We’ll write two functions, both called Sort:

I Sort(int &a, int &b) – sort two integers in ascending order.

I Sort(int list[], int n) – sort the elements of a list of length n.

The program will make a list of length 8 of random numbers between 0and 39, and then sort them using bubble sort.

(See notes from lecture for full description).

CS319 — More on functions 28/35

Page 29: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

A detailed example

11Sort.cpp (i)

#include <iostream >

6 #include <stdlib.h>

8 const int N=8;

10 void Sort(int &a, int &b);

void Sort(int list[], int length );

12 void PrintList(int x[], int n);

CS319 — More on functions 29/35

Page 30: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

A detailed example

11Sort.cpp (ii)

14 int main(void )

{

16 int i, x[N];

18 for (i=0; i<N; i++)

x[i]=rand ()%40;

std::cout << "The list is:\t\t";

22 PrintList(x, N);

std::cout << "Sorting ..." << std::endl;

Sort(x,N);

std::cout << "The sorted list is:\t";

28 PrintList(x, N);

return (0);

30 }

CS319 — More on functions 30/35

Page 31: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

A detailed example

11Sort.cpp (iii)

32 // Arguments: two integers

// return value: void

34 // Does: Sorts a and b so that a<=b.

void Sort(int &a, int &b)

36 {

if (a>b)

38 {

int tmp;

40 tmp=a; a=b; b=tmp;

}

42 }

44 // Arguments: an integer array and its length

// return value: void

46 // Does: Sorts the 1st n elements of x

void Sort(int x[], int n)

48 {

int i, k;

50 for (i=n-1; i>1; i--)

for (k=0; k<i; k++)

52 Sort(x[k], x[k+1]);

}

CS319 — More on functions 31/35

Page 32: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

A detailed example

62 void PrintList(int x[], int n)

{

64 for (int i=0; i<n; i++)

std::cout << x[i] << " ";

66 std::cout << std::endl;

}

CS319 — More on functions 32/35

Page 33: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Default values

In C++, one can also define functions that have assigned default values:

int mult(int a, int b=1, int c=1) // from 07Mult.cpp

{

return(a * b * c);

}

This means that, if the user fails to provide the second and thirdarguments to the function, it is assumed that they are both 1.

Example

std::cout << "mult(1) = " << mult(1);

std::cout << "mult(1,2) = " << mult(1,2);

std::cout << "mult(1,2,3) = " << mult(1,2,3);

CS319 — More on functions 33/35

Page 34: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Bitwise operators

Our next example is in 12Binary.cpp, and uses some bitwise operators.These relate to the logical operators you may have seen in CS304.

First we’ll look at a function to convert from decimal to binary:

12Binary.cpp

std:: string Int_to_Binary(int a)

46 {

std:: string A="";

48 for (int i=(int)log2(a); i>=0; i--)

{

50 if ( a >= pow(2,i))

{

52 A=A+"1";

a=a-pow(2,i);

54 }

else

56 A=A+"0";

}

58 return(A);

}

We’ll return to a recursion-based implementation later...

CS319 — More on functions 34/35

Page 35: More on functions - CS319: Scientific Computing (with C++)maths.nuigalway.ie/~niall/CT343/Week03/Week03.pdf · 7 Function overloading 8 A detailed example 9 Default values 10 Bitwise

Bitwise operators

Next, the calling part (modified from the actual code to simplifyformatting):

12Binary.cpp (main function)

int a, b, c;

std::cout << "Input two integers: ";

std::cin >> a >> b;

std::cout << "You entered: " << a << " and " << b;

std::cout << a << " = " << Int_to_Binary(a) << std::endl;

std::cout << b << " = " << Int_to_Binary(b) << std::endl;

c = a^b;

std::cout << "XOR: a^b = " << c << " = " << Int_to_Binary(c);

c = a&b;

std::cout << "AND: a&b = " << c << " = " << Int_to_Binary(c);

c = a|b;

std::cout << " OR: a|b = " << c << " = " << Int_to_Binary(c);

CS319 — More on functions 35/35