You are on page 1of 30

Starting out with Programming Logic and

Design
Fifth Edition

Chapter 6
Functions

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Learning Objectives
6.1 Introduction to Functions: Generating Random Numbers
6.2 Writing Your Own Functions
6.3 More Library Functions

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.1 Introduction to Functions (1 of 2)
A function is a module that returns a value back to the part of the
program that called it
– Many languages provide libraries of functions that you can
use, such as Random Number Generator
– A function is like a module, but it returns a value that can
be used in your program
Library functions
– Written functions that come with most languages
– Usually common tasks and save time for the programmer
because it allows for code reuse

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.1 Introduction to Functions (2 of 2)
The Random Number Generator function is useful in:
– Game programs
– Simulation programs
– Statistical programs
– Computer security such as encryption

How random function works


– Set number = random(1, 100)
– 1 and 100 define the range of the number that can be returned,
and are called arguments
– The function is called and a random number is returned and
assigned to the variable number
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.2 Writing Your Own Functions (1 of 3)
Most languages allow coders to write functions
• The function header specifies the data type of the value that is
returned, the name of the function, and any parameter variables
• The function body are the statements that execute when the
function calls
• The return statement specifies the value that is returned when
the function ends

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.2 Writing Your Own Functions (2 of 3)

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.2 Writing Your Own Functions (3 of 3)
Additional concerns
– While you can pass as many arguments into a function, you can only
return one value
– Functions simplify code, increase the speed of development, and ease
the facilitation of teamwork
– Each function should be flowcharted separately
– IPO (input, processing, and output), can be used to show what a
function does
IPO Chart for the getRegularPrice Function
Input Processing Output
None Prompts the user to enter an The item’s regular
item’s regular price price, as a Real

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (1 of 6)
Mathematical Functions
– Functions typically accept one or more values as
arguments, perform a mathematical operation using the
arguments, and return the results

Set result = sqrt(16)


– Returns the square root of 16
Set area = power(4, 2)
– Raises the value of 4 to the power of 2

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (2 of 6)
Other Common Mathematical Functions
– abs calculates the absolute value of a number
– cos returns the cosign of an argument
– round rounds to the nearest integer
– sin returns the sine of an argument
– tan returns the tangent of an argument

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (3 of 6)
Data Type Conversion Functions
– Library functions that convert values from one data type to
another
▪ toInteger converts a real to an integer
▪ toReal converts an integer to a real
– Real numbers can store integers
– Integers cannot store real numbers
– Type mismatch errors will occur without converting values

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (4 of 6)
Formatting Functions
– Allow to format a number in a certain way
– currencyFormat will be used to format a number to a
currency

– Display would be $6,450.88

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (5 of 6)
String Functions
– Allow for working with strings
– length function returns the length of a function
– append function joins multiple strings together
– toUpper and toLower converts a string to upper or lower
case
– substring can extract a character or a portion of a string
out of a string

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.3 More Library Functions (6 of 6)
– contains identifies similar strings within two strings
– stringToInteger and stringToReal converts string that
stores a number, to a number data type
– isInteger and isReal test numbers to see if it can be
converted to a string

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Java

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Java (1 of 4)
• Generating Random Numbers in Java
– Include the following import statement at the top of your program:

import java.util.Random;

– In your program, create a Random object:

Random randomNumbers = new Random();

– To get a random integer, use the object's nextInt() method:

int number;
number = randomNumbers.nextInt(10);

– In this example, a random integer in the range 0-9 will be assigned to the number
variable.

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Java (2 of 4)
import java.util.Random;

public class RandomNumbers


{
public static void main(String[] args)
{
Random randomNumbers = new Random();
int counter, number;

for (counter = 1; counter <= 5; counter++)


{
number = randomNumbers.nextInt(100) + 1;
System.out.println(number);
}
Example Output
}
93
} 17
21
44
72

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Java (3 of 4)
• Writing Your Own Value-Returning Methods in Java

Data type of the value that is returned

public static int sum(int num1, int num2)


{
int result;
result = num1 + num2;
return result;
}
The value that is returned

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Java (4 of 4)
import java.util.Scanner;

public class ValueReturningMethod


{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int firstAge, secondAge, total;

System.out.print("Enter your age: ");


firstAge = keyboard.nextInt();
System.out.print("Enter your best friend's age: ");
secondAge = keyboard.nextInt();
total = sum(firstAge, secondAge);
System.out.print("Together you are " + total + " years old.");
}

public static int sum(int num1, int num2)


{
int result;
result = num1 + num2;
return result; Example Output
}
Enter your age: 25
}
Enter your best friend's age: 24
Together you are 49 years old.

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Python

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Python (1 of 4)
• Generating Random Numbers in Python
– Include the following import statement at the top of your program:

import random

– To get a random integer, use the random.randint() function:

number = random.randint(1, 100)

– In this example, a random integer in the range 1-100 will be assigned to the
number variable.

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Python (2 of 4)
import random

def main():
for count in range(5):
number = random.randint(1, 100)
print(number)

main()

Example Output
89
7
16
41
12

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Python (3 of 4)
• Writing Your Own Value-Returning Functions in Python

def sum(num1, num2):


result = num1 + num2
return result

The value that is returned

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: Python (4 of 4)
def main():
first_age = int(input('Enter your age: '))
second_age = int(input("Enter your best friend's age: "))
total = sum(first_age, second_age)
print('Together you are', total, 'years old.')

def sum(num1, num2):


result = num1 + num2
return result

main()

Example Output
Enter your age: 25
Enter your best friend's age: 24
Together you are 49 years old.

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++ (1 of 5)
• Generating Random Numbers in C++
– Include the following include directive at the top of your program:

#include <cstdlib>

– To get a random integer, call the rand() function:

int number;
number = rand();

– In this example, a random integer will be assigned to the number variable.

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++ (2 of 5)
• Seeding the Random Number Generator
– To get a random sequence of numbers each time you run the program, you must
seed the random number generator with a different value.
– A common technique is to use the time() function to seed the random number
generator.
– The time() function returns the number of seconds that have elapsed since
midnight, January 1, 1970. The time() function requires the following #include
directive:

#include <ctime>

– Example:

unsigned seed = time(0);


srand(seed);
cout << rand() << endl;

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++ (3 of 5)
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int number, counter;

unsigned seed = time(0);


srand(seed);

for (counter = 1; counter <= 5; counter++)


{
number = 1 + rand() % 100;
cout << number << endl; Example Output
} 85
return 0; 67
} 89
25
5

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++ (4 of 5)
• Writing Your Own Value-Returning Methods in C++

Data type of the value that is returned

int sum(int num1, int num2)


{
int result;
result = num1 + num2;
return result;
}
The value that is returned

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
6.4 Focus on Languages: C++ (5 of 5)
#include "stdafx.h"
#include <iostream>
using namespace std;

int sum(int, int); // Function prototype

int main()
{
int firstAge, secondAge, total;

cout << "Enter your age: ";


cin >> firstAge;
cout << "Enter your best friend's age: ";
cin >> secondAge;
total = sum(firstAge, secondAge);

cout << "Together you are " << total


<< " years old." << endl;

return 0;
}

int sum(int num1, int num2)


Example Output
{ Enter your age: 25
int result; Enter your best friend's age: 24
result = num1 + num2; Together you are 49 years old.
return result;
}

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Copyright

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved

You might also like