CSCI 1120: Introduction To Computing Using C++ Tutorial 6: Predefined Function
CSCI 1120: Introduction To Computing Using C++ Tutorial 6: Predefined Function
CSCI 1120: Introduction To Computing Using C++ Tutorial 6: Predefined Function
2
Functions: Function Prototypes
• Function prototype consists of
• Function name
• Parameters
• Information the function takes in
• C++ is “strong typed” – error to pass a parameter of the wrong type
• Return type
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing
• Only needed if function definition comes after the function call in the
program
3
Functions: Header Files
• Header files
– Contain function prototypes for library functions
– <cstdlib> , <cmath>, etc.
– Load with #include <filename>
• Example:
#include <cmath>
• Custom header files
– Defined by the programmer
– Save as filename.h
– Loaded into program using
#include "filename.h"
4
C++ Standard Libraries
• C++ provides a huge set of libraries:
– Standard ANSI C library ported over to C++. These libraries are name with a prefix "c" and
without the ".h", e.g., <cmath> for C's <math.h>, <cstdlib> for C's <stdlib.h>, etc
– C++ new Libraries, such as <iostream>, <iomanip>, <string>, <fstream>, <sstream>.
– C++ Standard Template Library (STL): consists of containers, iterators, algorithms and function
objects.
– Boost C++ libraries.
5
Calling Predefined Functions
• To call a function, you have to know the following info about the
function (usually from manuals)
• name, functionality, parameters, return value
6
Math Library Functions
• Math library functions
– Allow the programmer to perform common mathematical calculations
– Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)
• Example
cout << sqrt( 900.0 );
– Calls the sqrt (square root) function. The preceding statement would print 30
– The sqrt function takes an argument of type double and returns a result of
type double, as do all functions in the math library
7
Math Function Examples
1 #include <iostream>
2 #include <cmath> // Need this line to use math functions
3 using namespace std;
4 You can store the returned value
5 int main() { in a variable or use the returned
6 double x; value directly in an expression.
7 x = sqrt(10);
8
9 cout << "x = square root of 10 = " << x << endl;
10 cout << "Ceiling of x = " << ceil(x) << endl;
11 cout << "2 to the power x = " << pow(2.0, x) << endl;
12 cout << "log(x + 10) = " << log10(x + 10) << endl;
13 x = square root of 10 = 3.16228
14 return 0; Ceiling of x = 4
15 } 2 to the power x = 8.95242
8
log(x + 10) = 1.11933
Functions Description Examples
9
Functions Description Examples
Ref: http://www.cplusplus.com/reference/cmath/ 10
Random Number Generation
• rand function
i = rand();
– Load <cstdlib>
– Generates a pseudorandom number between 0 and RAND_MAX (usually 32767)
• A pseudorandom number is a preset sequence of "random" numbers
• The same sequence is generated upon every program execution
• srand function
– Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <ctime>
– time( 0 )
• The time at which the program was compiled
– Changes the seed every time the program is compiled, thereby allowing rand to
generate random numbers
11
Random Number Generation
• rand() (#include <cstdlib>)
x = rand();
• x is assigned an integer between 0 and RAND_MAX (usually 32767)
12
Sample Problem – Distribution of rand()
13
1 #include <iostream>
2 using namespace std;
3 #include <iomanip> // Needed by setw()
4 #include <cstdlib>
5
6 int main() {
7
8 // # of times the outcome is 1, 2, 3, 4, 5, or 6
9 int freq1 = 0, freq2 = 0, freq3 = 0,
10 freq4 = 0, freq5 = 0, freq6 = 0;
11
12 int face; // face value of the dice
13 int i = 1;
14
15 while (i <= 6000) {
16 face = 1 + rand() % 6;
17
18
14
19 if (face == 1) freq1++;
Reserve 13 spaces for
20 else if (face == 2) freq2++;
the next output.
21 else if (face == 3) freq3++;
22 else if (face == 4) freq4++; The output is right
23 else if (face == 5) freq5++; justified in the reserved
24 else freq6++; space.
25 No use if next output is
26 i++; too big to fit into the
27 } // End of while loop reserved space.
28
29 cout << "Face" << setw(13) << "Frequency\n"
30 << " 1" << setw(13) << freq1 << endl
31 << " 2" << setw(13) << freq2 << endl
32 << " 3" << setw(13) << freq3 << endl
33 << " 4" << setw(13) << freq4 << endl
34 << " 5" << setw(13) << freq5 << endl
35 << " 6" << setw(13) << freq6 << endl;
36
37 return 0;
38 }
39 15
Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999
13 character-wide
16
srand() and Random Number Sequence
• rand() only generates pseudorandom number
sequence.
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
19
macOS
Windows
22
Example – randGenPuzzle() function in assignment 3
23
Example – randGenPuzzle() function in assignment 3
Generate a random digit in the
range [0, 8].
24
Sample Problem:
25
Sample Problem: code
int main() {
int i, a, b, c, k;
double x;
a = 0; b = 0; c = 0;
srand(time(NULL));
for (i = 1; i <= 10000; i ++){
x = (double)rand() / RAND_MAX; // generate random variable
if (x <= 0.2){
k = 3; a ++; // count the number of 3
}
if (x > 0.2 && x < 0.7){
k = 5; b ++; // count the number of 5
}
if (x >= 0.7){
k = 7; c ++; // count number of 7
}
}
cout<< a <<" "<< b << " " << c << endl;
return 0;
} 26
Sample Problem 2
• Generate a random permutation of the sequence (1, 2, …, n):
27
Sample Code
#include<iostream> // To shuffle an array a of n elements
#include<cstdlib> (indices 0..n-1):
using namespace std; for (int i = n - 1; i > 0; i--) {
int j = rand() % i;
void printArray(int x[], int n) { swap(randperm[j], randperm[i]);
for (int i = 0; i < n; i++) { }
cout << x[i] << " "; // print the random permuration sequence
} cout << "Random Permutation: ";
cout << endl; printArray(randperm, n);
}
return 0;
int main() { }
int n = 10;
int randperm[10]; // declare the array
// assign (0, 1, ..., n-1) to the array
for (int i = 0; i < n; i++) {
randperm[i] = i;
}
cout << "Original Array: ";
printArray(randperm, n);
28