Copy the following program into a text editor, save it as myarrays.cpp, and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
Inside main(), add a statement to define an array of double named temp along with a list of five (5) randomly chosen values.
Compile your code to make sure it has correct syntax.
If you have problems, ask a classmate or the instructor for help as needed.
Print element #0 like:
cout << temp[0] << endl;
Compile your code to make sure it has correct syntax.
If you have problems, ask a classmate or the instructor for help as needed.
Verify your code agains the following example. Your array values will vary.
Example Array of Type double
Creating Arrays with No Values
We can declare an array with no values in each element using the following syntax
dataTypevariableName[size];
Where:
dataType: the data type of all the array items
variableName: the name you make up for the array
size: the number of data items the array can hold
For example, the following is the definition of an array named scores that holds 10 values of type int:
const int SIZE = 10;
int scores[SIZE];
Notice the use of the constant SIZE to record the number of elements
To make use of such an array, we would need to assign a value to each element like:
scores[0] = 95;
scores[1] = 97;
// and so on
We may specify a size and initialize only some of the elements
const int SIZE = 10;
int scores[SIZE] = { 95, 97 };
The remaining 8 unassigned elements will get a value of 0 since C++ 99
Check Yourself
The number inside of the square brackets of an array is called an ________.
Like a string, the first element in any array has an index value of ________.
-1
0
1
it depends on the definition
If you declare an array with 10 elements, the index number of the last element is ________.
For the following array definition, answer the questions below:
We can use a loop as a way to access each array element
Notice that the index of an array is an integer number
The index can be a counter variable, like those used in counter-controlled loops
Thus we can use arrays with a loop like:
const int SIZE = 5;
int numList[SIZE] = { 1, 2, 3, 4, 5 };
int total = 0;
for (int i = 0; i < SIZE; i++) {
cout << numList[i] << endl;
total = total + numList[i];
}
cout << total << endl;
The first time through the loop, when i = 0, the value of numList[i] is 1
The value of total starts at 0 but becomes 1 during the first iteration
Activity
Take out a piece of paper and put your name on it.
Create a table with columns for total, i and numList[i] like:
total | i | numList[i]
----------------------
| |
| |
Trace the values of total, i and numList[i] for each iteration of the following loop: (3m)
const int SIZE = 5;
int numList[SIZE] = { 1, 2, 3, 4, 5 };
int total = 0;
for (int i = 0; i < SIZE; i++) {
cout << numList[i] << endl;
total = total + numList[i];
}
When finished, verify your array-and-loop trace with another classmate. (1m)
Check Yourself
For the following code:
const int SIZE = 5;
int numList[] = { 1, 2, 3, 4, 5 };
int total = 0;
for (int i = 0; i < SIZE; i++) {
cout << numList[i] << endl;
total = total + numList[i];
}
cout << total << endl;
For the second time through the loop:
The value of the index variable i is ________
The value of numList[i] is ________
After executing the above code snippet, the value stored in total is ________?
To make use of the rand() function we may need to include the library:
#include <cstdlib>
The syntax for calling the function is:
rand()
For example:
int randNumber = rand(); // returns number between 0 and RAND_MAX
Psuedorandom
The numbers produced by the library appear to be random but are not
We call these types of random numbers psuedorandom
Psuedorandom means that given an initial starting condition, the procedure always produces the same result
Random numbers actual come from a a very long sequence of numbers computed from fairly simple formulas; they just behave like random numbers
The following program uses rand() to produce the same output every time it runs
The reason that the numbers are the same is because the numbers are generated with the same computer commands every time it is called
When running the following program, remember the first few numbers and then start the program again
Notice that the same sequence of numbers is produced
Example Program Using rand()
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int i;
for (i = 0; i < 10; i++) {
int num = rand();
cout << num << "\n";
}
return 0;
}
When running programs we do not always want the same sequence of numbers every time
For instance, if we run a dice simulation for a game we want different numbers every time the program runs
To get a different number, we must "seed" the random number generator
We set the seed with the srand() function with the syntax:
srand(seed)
Where:
seed: the initial number for the random sequence
For example:
randomSeed(seed);
If we change the seed value, we will get different numbers every time
Changing the Starting Value
One common strategy for changing the seed value is to use the current time
Since the time changes every second, we get a new random number sequence every time we run our program
To generate a number from time, we can use the time() function from the standard time library:
srand(time(0));
The expression time(0) returns the number of seconds since January 1, 1970
To make use of the time() function we may need to include the library:
#include <ctime>
We only call srand(time(0)) once in a program or we may get repeated numbers
Example Program Using srand()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(time(0));
int i;
for (i = 0; i < 10; i++) {
int num = rand();
cout << num << "\n";
}
return 0;
}
Check Yourself
The function that sets the starting location, or seed, for rand() is ________.
To produce a new random number sequence every time a program starts use the code: ________.
True or false: you must reseed the random number generator every time before calling rand().
In this exercise we look at how to call functions and learn how to generate random numbers.
Specifications
Copy the following program into a text editor, save it as dice.cpp, and then compile the starter code to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
Add the library cstdlib at the top of the file:
#include <cstdlib>
Random numbers are generated by using the rand() function. Declare two integer variables, die1 and die2, and assign them values returned by the rand() function using code like the following:
int die1 = rand();
int die2 = rand();
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 1481765933
Notice the size of the numbers displayed. We want to limit the size of the random numbers generated by rand() to only six numbers. We limit the range by using the modulus (%) operator.
Change the two assignment statements with the following code:
int die1 = rand() % 6;
int die2 = rand() % 6;
The number 6 in the above code is known as the scaling factor since it limits the scale of the numbers produced by the rand() function.
Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 5
Seeing just one roll of the dice is not very useful. Add a counting loop to roll and display the dice 10 times. For more information, see section: 5.1.1: Using Loops to Count. You may want to use a for loop for counting as described in section 5.1.2: for Statements.
Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 5
You rolled a 3 and a 2
You rolled a 5 and a 0
You rolled a 0 and a 4
You rolled a 0 and a 2
You rolled a 1 and a 3
You rolled a 5 and a 3
You rolled a 5 and a 0
You rolled a 5 and a 0
You rolled a 0 and a 5
Notice that we get numbers in the range of 0 to 5 when we want 1 to 6. To correct this problem, we must add one to each of the statements generating the random numbers. Go ahead and make this change now. For more information, see section: 7.3.5: Simulating Dice.
Rerun your code two or more times and check the numbers rolled. Do you see any patterns? To correct the problem we must "seed" the random number generator. Add the following code after the start of main and before your counting coop:
Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 1 and a 1
You rolled a 4 and a 5
You rolled a 5 and a 6
You rolled a 3 and a 6
You rolled a 2 and a 4
You rolled a 4 and a 6
You rolled a 3 and a 4
You rolled a 1 and a 5
You rolled a 4 and a 5
You rolled a 4 and a 6
Save your final program source code to submit to Canvas as part of assignment 7.
Read the following section and be prepared to answer the Check Yourself questions.
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(1000, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
cout << "You entered: " << input << endl;
return 0;
}
What if we need to enter two validated numbers into a program?
We want to process the first number after input and then input the second number
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(1000, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the input
cout << "You entered: " << input << endl;
double input2 = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input2;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(1000, '\n');
input2 = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the second input
cout << "You entered: " << input2 << endl;
return 0;
}
Our program would be easier to write if we could get the second input without repeating the code
With functions, we give the list of commands a name and then run the list by calling the name
Using functions we keep all the code in one place and avoid duplication
Avoiding duplication reduces the complexity of our code and makes it easier to understand and change
Programming Style: Avoid Duplicating Code
Duplicate code can lead to problems such as:
Long repeated sections that are more difficult to understand than shorter sequences
Repetition of largely identical code within which it is difficult to see the different purposes of each section
Update problems where we make changes in some sections but overlook making changes in other sections
If we find ourselves writing similar code of three or more lines multiple times, we should consider writing a function
Check Yourself
True or false: people write functions to organize code into small understandable pieces.
Which of the following are features of a function?
Must have a name
Can receive input
Performs an action
Must return a value
True or false: when a function finishes executing, the program flow returns to the point just after the code that called the function.
True or false: functions can reduce the amount of repeated code, making programs shorter.
functionName: the name you make up for the function
parameterx: the input values, if any
statements: the list of statements to execute when the function is called
Can you identify each of these syntax items in the function we have always used?
int main() {
// program statements go here
}
Example Program with a Second Function
As an example, the following program has a simple function to add two numbers
Notice that the code has two functions: add() and main()
The second function is placed before main() so the compiler knows about the function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
Function Name
Every function must have a name that identifies the function
Function names follow the same rules as variable names
Technically, we can use any valid identifier for a function name
However, we should use a name that suggests the action the function performs
In our example, add suggests that the function will return the sum of two numbers
Function Structure
The first line of a function is known as the function declaration
int add(int a, int b)
The curly braces {...} contain the function body
The function body is the list of statement the function executes when called
The function declaration describes the name, input types and output type of a function
We will look at these features in more detail in the following sections
Check Yourself
True or false: function names are case sensitive.
Of the following, ________ would be a valid function definition.
fun() { /* C++ statements */ }
int fun;
int fun() { /* C++ statements */ }
int fun();
The statements inside a function are surrounded by ________.
Curly braces -- { }
Parenthesis -- ( )
Square brackets -- [ ]
Colons -- : :
Which of the following is a function definition and which is a function call?
When defining a function, it is worth thinking about what helpful action it will perform
We can make the function more useful if we give it parameters
Recall the use of functions in mathematics like:
f(x, y) = x + y
With the above formula, we can plug in a value for x and y to get a final value
Like in math, we need two parameters for an add function
Read through the following code to identify how the code makes use of the parameters
Example Code with Function Parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
Parameter List
We must have parenthesis after a function name
Inside the parenthesis, we define a list of zero or more parameter variables
Parameters are the inputs to a function
In our example, we have two parameters inside the parenthesis
int add(int a, int b)
Parameters are the declaration of a new variable, even though they are declared inside parenthesis
Each parameter must have both a type and a name, just like a regular variable
If we have more than one parameter, we separate them with commas
Any parameter that we declare must be given an argument when we call the function
In the following image, the value of arguments num1 and num2 are copied to the parameters a and b
Passing Arguments to Function Parameters
Arguments and Parameters
Depending on our background, we might use the term arguments or parameters for the values passed to functions
The terminology is not that important
However, the way I will use the terms is:
A function definition has parameters
int add(int a, int b) { // a and b are parameters
// ...
}
A function call passes arguments to parameters
add(num1, num2); // num1 and num2 are arguments
Arguments are values we pass into functions via parameters
When the argument drops into a function, it lands in a parameter
A parameter is just like other variables in the function
Except that a parameter gets initialized by an argument
The important part is:
We must pass every function parameter an argument.
The arguments must be in the same order as the parameters
Also, the argument value must be compatible with the type of the parameter
For example, we cannot call add() with: add("Ed", "Parrish")
Check Yourself
To received input, a function has __________.
Parameters are set on the first line of a function inside a set of __________
Curly braces -- { }
Parenthesis -- ( )
Square brackets -- [ ]
Colons -- : :
True or false: like any other variable, a function parameter has both a type and a name.
If a function has three parameters, a function call must include ________ arguments.
For the following function header, the parameter names are __________
int add(int a, int b)
a
b
both a and b
cannot tell from the function signature
The following code snippet prints ________.
int addTwo(int x) {
return x + 2;
}
int main() {
int x = addTwo(40);
cout << x << endl;
return 0;
}
In this exercise we trace the function we developed in the last exercise.
Specifications
Create a text file named trace.txt.
In the trace.txt file, list the line numbers of each statement of your program from the last exercise in the order the lines are executed. For example, if main() starts on line 9, statements are executed as follows:
9, 10, 11, 12, ...
Do not bother to list blank lines or lines containing only a curly brace (}) of a function definition.
Review the hand trace with another student in the class. Then add a comment to the top of the file that contains the name of the person with whom you reviewed the code, like:
Reviewed trace with Fred George.
Save the trace.txt to submit to Canvas as part of assignment 7.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 7.4.8: Summary.
#include <iostream>
using namespace std;
int display(int a) {
cout << a << endl; // What will this print?
int x = 42;
cout << x << endl; // What will this print?
return 0;
}
int main() {
int x = 7;
cout << x << endl; // prints 7
x = 11;
cout << x << endl; // prints 11
display(x);
cout << x << endl; // What will this print?
return 0;
}
Check Yourself
A variable that can be used only within the function in which it was declared is known as a __________ variable.
True or false: parameters are local variables.
The area of a program within which a variable exists is known as its ________.
The following code snippet prints ________.
int myFun(int a) {
int x = 12;
a = x;
a = a + 3;
return 0;
}
int main() {
int x = 42;
myFun(x);
cout << x << endl;
return 0;
}
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
Note the placement of the curly braces
There are two common styles of curly brace placement for functions:
Place the opening brace on the same line as the function heading:
int myFunction() {
// statements of the function
}
Place the opening brace under and lined up with the first letter of the return type:
int myFunction()
{
// statements of the function
}
We can use either style as long as we are consistent
Also notice the indentation of the statements inside the function
As before, we always indent 3-4 more spaces after an opening curly brace
After the closing curly brace, we no longer indent the extra 3-4 spaces
Indenting makes it easier to see the block of code
In addition, function names always start with a lower case letter like variables
We can tell the difference between function and variable name because functions have parenthesis
Check Yourself
True or false: always indent code within a function's curly braces.
The number of spaces to indent is ________.
Function names always start with a(n) ________ letter.