CIE 202 - Unit 01 - Basic Programing - Spring 2020
CIE 202 - Unit 01 - Basic Programing - Spring 2020
Covered in Lab
2 2
Introduction
to programing
with C++
3
Write a program to compute the Area
of a Circle
4 4
Trace a Program Execution
#include <iostream>
using namespace std; No semicolon
int main()
main()d
{
double radius;
const double PI = 3.14159;
int main()
{
double radius;
const double PI = 3.14159;
int main()
{
// Prompt the user to enter three numbers
double number1, number2, number3;
cout << "Enter three numbers: ";
cin >> number1 >> number2 >> number3;
// Compute average
double average = (number1 + number2 + number3) / 3;
// Display result
cout << "The average of " << number1 << " " << number2
<< " " << number3 << " is " << average << endl;
return 0;
}
Enter three numbers:10.5
numbers:
11 11.5
The average of 10.5 11 11.5 is 11
12 12
Identifiers
The names that identify elements such as
variables and functions in a program
Can have letters, digits, and underscores ( _ ).
Must start with a letter or an underscore, not a
digit.
Cannot be a reserved word.
Can be of any length but C++ compiler may
impose some restriction. Safer to be < 31
characters.
13 13
Variables
#include <iostream>
using namespace std;
int main()
{
int i = k + 1;
cout << I << endl;
int i = 1;
cout << i << endl;
return 0;
}
14 14
Basic
Data Types
15
Numerical Data Types
Name Synonymy Range Storage Size
float
C++11: long long is Negative range: 32-bit IEEE 754
defined in C++11 -3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
long double Negative range: 80-bit
-1.18E+4932 to -3.37E-4932
Positive range:
3.37E-4932 to 1.18E+4932
Significant decimal digits: 19
16 16
sizeof Function
You can use the sizeof function to find the size of a
type. For example, the following statement displays
the size of int, long, and double on your machine.
17 17
Numeric Operators
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
18 18
Example: Displaying Time
Write a program that obtains minutes
from seconds.
#include <iostream>
using namespace std;
int main()
{
// Prompt the user for input
int seconds;
cout << "Enter an integer for seconds: ";
cin >> seconds;
int minutes = seconds / 60;
int remainingSeconds = seconds % 60;
cout << seconds << " seconds is " << minutes <<
" minutes and " << remainingSeconds << " seconds " <<
endl; Run
DisplayTime
return 0;
}
19 19
Exponent Operations
cout << pow(2.0, 3) << endl; // Displays 8.0
cout << pow(4.0, 0.5) << endl; // Displays 2.0
cout << pow(2.5, 2) << endl; // Displays 6.25
cout << pow(2.5, -2) << endl; // Displays 0.16
20 20
Overflow
When a variable is assigned a value that
is too large to be stored, it causes
overflow. For example, executing the
following statement causes overflow
21 21
Arithmetic Expressions
3 + 4 x 10( y − 5)(a + b + c) 4 9+ x
− + 9( + )
5 x x y
is translated to
22 22
Augmented Assignment
Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
23 23
Increment and
Decrement Operators
Operator Name Description
The expression (var++) evaluates to the
post- original value in var and increments var by 1.
var++
increment
The expression (++var) increments var by 1
pre-
++var and evaluates to the new value in var after the
increment
increment.
The expression (var--) evaluates to the original
post- value in var and decrements var by 1.
var--
decrement
25 25
Numeric Type Conversion
Consider the following statements:
short i = 1;
long k = i * 3 + 4;
double d1 = i * 3.1 + k / 2;
double d2 = i * 3.1 + k / 2.0;
d1 = 6.1
d2 = 6.6
26 26
Type Casting
Implicit casting
int i = 3;
double d = i; //type widening.
//i did not change
Explicit casting
int i = static_cast<int>(3.0); //type narrowing
int i = (int)3.9; //Fraction part is truncated
27 27
Example: Keeping Two Digits
After Decimal Points
Write a program that displays the sales tax
#include <iostream>
(6%)
usingwith twostd;digits after the decimal point.
namespace
int main()
{
// Enter purchase amount
double purchaseAmount;
cout << "Enter purchase amount: ";
cin >> purchaseAmount;
return 0;
}
28 28
Selections
29
if Statements
Boolean Expression
Statement(s)
30 30
Relational Operators
31 31
Examples
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, display HiFive. If the number is even,
display HiEven.
32 32
Examples
Write a program that prompts
#includethe user to enter an integer. If the
<iostream>
number is a multiple of 5,using namespace std;
display HiFive. If the number is even,
display HiEven. int main()
{
// Prompt the user to enter an integer
int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 5 == 0)
{ cout << "HiFive" << endl;
cout << "HiFive" << endl;
if
} (number % 2 == 0 )
ifcout << "HiEven"
(number % 2 == 0<<
) endl;
{
return
cout 0;
<< "HiEven" << endl;
} }
return 0;
}
33 33
Examples
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, display HiFive. Otherwise, if the number
is even, display HiEven.
34 34
Examples
#include <iostream>
Write a program that prompts the user std;
using namespace to enter an integer. If the
number is a multiple of 5,intdisplay
main()
HiFive. Otherwise, if the number
is even, display HiEven. {
// Prompt the user to enter an integer
int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 5 == 0)
{
cout << "HiFive" << endl;
}
else Nested
{
if (number % 2 == 0 )
cout << "HiEven" << endl;
}
return 0;
} 35 35
Multiple Alternative if
Statements
Only if the
body of
else is just if
if (score>=>=95.0)
if (score 90.0)
an if- if (score
(score >=>=95.0)
90.0)
cout
cout <<<<"Grade
"Grade is is
A";A"; cout
cout <<
<< "Grade
"Grade isisA";
A";
else
else
statement else if (score
(score>=>= 80.0)
else if 80.0)
if (score>=>=80.0)
if (score 80.0) Equivalent cout
cout <<
<< "Grade
"Grade isisB";
B";
cout<<<<"Grade
cout "Grade is B";
is B"; else if (score
else if (score>=>= 70.0)
65.0)
else
else cout
cout <<
<< "Grade
"Grade isisC";
C";
if (score
if (score>= >= 70.0)
65.0) else
else if (score >= 60.0)
cout<<<<"Grade
cout "Grade is C";
is C"; cout
cout <<
<< "Grade
"Grade isisF";
D";
else
else else
if (score
cout << "Grade>= is60.0)
F"; This is better cout << "Grade is F";
cout << "Grade is D";
else
cout << "Grade is F";
(a) (b)
36
What is wrong?
37 37
Logical Operators
38 38
Examples
Write a program that checks whether a number is divisible by 2 and
3, whether a number is divisible by 2 or 3, and whether a number is
divisible by 2 or 3 but not both:
39 39
Examples
#include <iostream>
using namespace std;
Write a program that checks whether a number is divisible by 2 and
int main()
3, whether
{
a number is divisible by 2 or 3, and whether a number is
divisible by 2 or 3 but not both:
int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 2 == 0 || number % 3 == 0)
cout << number << " is divisible by 2 or 3." << endl;
return(0);
}
40 40
Examples
#include <iostream>
using namespace std; Short-circuit operators
Write a program that checks whether a number is divisible by 2 and
int main()
3, whether
{
a number is divisible by 2 or 3, and whether a number is
divisible by 2 or 3 but not both:
int number; Stops if condition 1 is False
cout << "Enter an integer: ";
cin >> number;
Stops if condition 1 is True
if (number % 2 == 0 && number % 3 == 0)
cout << number << " is divisible by 2 and 3." << endl;
if (number % 2 == 0 || number % 3 == 0)
cout << number << " is divisible by 2 or 3." << endl;
return(0);
}
41 41
Different unique cases?
if (selectedOption == 0)
{
//create new file;
}
else if (selectedOption == 1)
{
//open existing file;
}
else if (selectedOption == 2)
{
//close current file;
}
else if (selectedOption == 3)
{
//exit program;
}
else
{
cout << "Error: invalid input" << endl;
}
42 42
switch Statements
switch (selectedOption)
{
case 0:
//create new file;
break;
case 1:
//open existing file;
break;
case 2:
//close current file;
break;
case 3:
//exit program;
break;
default:
cout << "Error: invalid input" << endl;
}
43 43
Must switch Statements
switch (selectedOption)
{
case 0: Must yield a value of char, int, or enum type (can be expression)
//create new file;
break;
case 1:
//open existing file;
break; Must be a const of the same type as switch-expression
case 2:
//close current file;
break;
case 3:
//exit program;
break;
default:
cout << "Error: invalid input" << endl;
}
44 44
switch Statements
switch (selectedOption)
{
case 0:
//create new file;
break;
case 1:
//open existing file;
break;
case 2:
//close current file; Can be removed, but then next case will be executed
break;
case 3:
//exit program;
break; Optional, to perform actions when no case is matched.
default:
cout << "Error: invalid input" << endl;
}
45 45
What is the output?
char ch = 'b'; A:
switch (ch) b
{ B:
bb
case 'a': cout << ch; C:
case 'b': cout << ch; bc
case 'c': cout << ch; b
} D:
c
46 46
Operator Precedence
47 47
Loops
48
Introducing while Loops
int count = 0;
while (count < 100) // loop continuation condition
{ // loop body
cout << "Welcome to C++!\n";
count++;
} count = 0;
false
(count < 100)?
true
cout << "Welcome to C++!\n";
count++;
49 49
Ending a Loop with a Sentinel
Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify
the end of the loop. Such a value is known as a
sentinel value.
50 50
#include <iostream>
using namespace std;
int main()
{
int data;
cout << "Enter an integer (the input ends if it is 0): ";
cin >> data;
return 0;
}
51
Exercise
3
5
7
9
52 52
do-while Loop
Statement(s)
(loop body)
true Loop
Continuation
do Condition?
{ false
// Loop body;
Statement(s);
} while (loop-continuation-condition);
53 53
#include <iostream>
using namespace std;
int main()
{
// Keep reading data until the input is 0
int sum = 0;
int data = 0;
do
{
sum += data;
return 0;
}
54
do-while Loop
What is wrong in the following code?
int sum = 0;
do
{
// Read the next data
cout << "Enter an integer (the input ends if it is 0): ";
int data;
cin >> data;
sum += data;
} while (data != 0);
(3)
(3)Execute
Executeloop
loop
56 56
Notes
The initial-action in a for loop can be a list of zero or more
comma-separated expressions.
for (i = 0; i < 100; i++)
57 57
Example: Using for Loops
// Initialize sum
double sum = 0;
// Display result
cout << "The sum is " << sum << endl;
58 58
Which Loop to Use?
The three forms of loop statements are
equivalent
Use the most intuitive and comfortable for
you:
– A for loop: if the number of repetitions is
counter-controlled.
– A while loop: if the number of repetitions is
sentinel-controlled
– A do-while loop: replaces a while loop if the
loop body must be executed before testing
the continuation condition.
59 59
Nested Loops
What does this program do?
return 0;
}
61
What does this program do?
int main()
{
int sum = 0;
int number = 0;
return 0;
}
62
Arrays
63
Introducing Arrays
Array is a data structure that represents a collection
of the same types of data.
double myList [10];
myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34.0
myList[7] 45.45
myList[8] 99.993
myList[9] 111.23
64
Declaring Array Variables
datatype arrayRefVar[arraySize];
Example:
double myList[10]; // the indices are from 0 to 9
C++ requires that the array size used to declare an array must
be a constant expression.
int size = 4;
double myList[size]; // Wrong
65
Using Indexed Variables
After an array is created, use indexed variables as
a regular variable:
double myList[4];
myList[0] = 5;
myList[1] = 9;
myList[2] = myList[0] + myList[1];
66
Using Indexed Variables
C++ does not check array’s boundary
When an array is created, its elements are
assigned with arbitrary values.
double myList[10];
cout << myList[2] << endl; !
cout << myList[12] << endl; !
67
Printing arrays
cout << myList; // Not what you want/mean;
To print a regular array, print each element using a loop:
for (int i = 0; i < ARRAY_SIZE; i++)
cout << myList[i] << " ";
68
Copying Arrays
list = myList;
}
69
Functions
70
Opening Problem
What does this program do?
int main()
{
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
cout << "Sum from 1 to 10 is " << sum << endl;
sum = 0;
for (int i = 20; i <= 37; i++)
sum += i;
cout << "Sum from 20 to 37 is " << sum << endl;
sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
cout << "Sum from 35 to 49 is " << sum << endl;
return 0;
}
71 71
An Alternative
int sum(int i1, int i2)
{
int sum = 0; Function Definition
for (int i = i1; i <= i2; i++) (Define a Function)
sum += i;
return sum;
}
int main()
{ Function Call
cout << "Sum from 1 to 10 is " << sum(1, 10) << endl;
cout << "Sum from 20 to 37 is " << sum(20, 37) << endl;
cout << "Sum from 35 to 49 is " << sum(35, 49) << endl;
return 0; (Invoke a function)
}
72
Return
value type Method An Alternative
name
int sum(int i1, int i2)
{ Parameters List
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
Return value
int main()
{
cout << "Sum from 1 to 10 is " << sum(1, 10) << endl;
cout << "Sum from 20 to 37 is " << sum(20, 37) << endl;
cout << "Sum from 35 to 49 is " << sum(35, 49) << endl;
return 0;
}
73
An Alternative
Function signature
int sum(int i1, int i2) Function header
{
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i; Function body
return sum;
}
int main()
{
cout << "Sum from 1 to 10 is " << sum(1, 10) << endl;
cout << "Sum from 20 to 37 is " << sum(20, 37) << endl;
cout << "Sum from 35 to 49 is " << sum(35, 49) << endl;
return 0;
}
74
Formal Parameters
Can be void
An Alternative
int sum(int i1, int i2)
{
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
(Arguments)
int main() Actual Parameters Keep order
{
cout << "Sum from 1 to 10 is " << sum(1, 10) << endl;
cout << "Sum from 20 to 37 is " << sum(20, 37) << endl;
cout << "Sum from 35 to 49 is " << sum(35, 49) << endl;
return 0;
}
75
Call Stacks
int max(int num1, int num2) int main()
{ {
int result; int i = 5;
if (num1 > num2) int j = 2;
result = num1; int k = max(i, j);
else }
result = num2;
return result;
}
76
Overloading Functions
The max function used earlier works for int
data type.
What if you also need the max of two floating-
point numbers?
77
// Return the max of two int values
int max(int num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
return 0;
}
79
Ambiguous Invocation
int maxNumber(int num1, double num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
double maxNumber(double num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2; Ambiguous invocation is a compilation error.
}
int main()
{
cout << maxNumber(1, 2) << endl;
return 0;
}
80
Function Declaration(Two Options)
Function Prototype
int max(int num1, int num2) int max(int num1, int num2);
Function Declaration
{
int result; int main()
if (num1 > num2) {
result = num1; int i = 5;
else int j = 2;
result = num2; int k = max(i, j);
return result; }
}
int max(int num1, int num2)
Function Declaration
int main() {
{ int result;
int i = 5; if (num1 > num2)
int j = 2; result = num1;
int k = max(i, j); else
} result = num2;
return result;
}
81
#include <iostream>
using namespace std;
return 0;
}
82
#include <iostream>
#include "MyFile.h"
using namespace std;
int main()
{
cout << "The maximum of 3 and 4 is " << max(3, 4) << endl;
cout << "The maximum of 3.0 and 5.4 is " << max(3.0, 5.4) << endl;
cout << "The maximum of 3.0, 5.4, and 10.14 is " << max(3.0, 5.4, 10.14) << endl;
return 0;
}
83
Default Arguments
C++ allows you to declare functions with default argument
values. The default values are passed to the parameters
when a function is invoked without the arguments.
void printRectArea(double length, double width = -1)
{
if (width == -1)
width = length; Trailing defaults
int main()
{ Watch out for ambiguity
printRectArea(3, 4); //displays 12 with function overloads
printRectArea(4); //displays 16
return 0;
} 84
Inline Functions
Functions makes the program easy to read and easy to maintain, but
involve runtime overhead
C++ provides inline functions to avoid function calls.
Compiler copies the function code in line at the point of each invocation.
Compiler has the right to ignore this request!
inline void f(int month, int year)
{ int main()
cout <<"month is " << month << endl; {
cout <<"year is " << year << endl; int month = 10, year = 2008;
} cout<<"month is "<<month<<endl;
cout<<"year is "<<year<<endl;
int main() cout<<"month is "<< 9 <<endl;
{ cout<<"year is "<< 2010 <<endl;
int month = 10, year = 2008; f(9, 2010);
f(month, year);
f(9, 2010); return 0;
}
return 0;
}
85
Scope of Variables
A local variable: a variable defined inside a function.
Scope: o where in the program the variable can be referenced.
o starts from its declaration to the end of the containing block.
You can declare a local variable with the same name in different blocks.
void function1()
{
⋮
for (int i = 1; i < 10; i++)
{
⋮
int j;
for (j = 10; j > 0; j--)
The scope of i
{
The scope of j
⋮
}
⋮
}
} 86
Scope of Local Variables,
cont.
It is fine to declare i in two It is not good practice to
non-nesting blocks declare i in two nesting blocks
for (int i = 1; i < 10; i++) for (int i = 1; i < 10; i++)
{ {
x += i; sum += i;
} }
87
Global Variables
Global variables:
Declared outside all functions and are
accessible to all functions in its scope.
Defaulted to zero if not directly assigned.
88
#include <iostream> A) x is 1
using namespace std; y is 0
void t1(); // Fnc prototype x is 2
void t2(); // Fnc prototype y is 1
int main() B) x is 1
y is 0
{ x is 2
t1(); y is 2
t2();
return 0; C) x is 1
} y is 0
x is 1
int y; y is 1
// Global variable, default to 0
D) x is 1
void t1() y is 0
{ x is 1
int x = 1; y is 2
cout << "x is " << x << endl << "y is " << y << endl;
x++; y++;
}
void t2()
{
int x = 1;
cout << "x is " << x << endl << "y is " << y << endl;
} 89
Unary Scope Resolution
A local variable name can be the same as a global
variable name
Access the global variable using ::globalVariable.
The :: operator is known as the unary scope
resolution operator.
#include <iostream>
using namespace std;
int v1 = 10;
int main()
{
int v1 = 5;
cout << "local variable v1 is " << v1 << endl;
cout << "global variable v1 is " << ::v1 << endl;
return 0;
} 90 90
Unary Scope Resolution
A local variable name can be the same as a global
variable name
Access the global variable using ::globalVariable.
The :: operator is known as the unary scope
resolution operator.
#include <iostream>
//using namespace std;
int v1 = 10;
int main()
{
int v1 = 5;
std::cout << "local variable v1 is " << v1 << std::endl;
std::cout << "global variable v1 is " << ::v1 << std::endl;
return 0;
} 91 91
static Local Variables
static variables:
Declared inside a function and not destroyed after
the function completes its execution.
Retains its last value for the next call.
Defaulted to zero if not directly assigned.
92 92
#include <iostream>
using namespace std; A) x is 1
y is 2
void t1(); // Function prototype x is 1
y is 2
int main()
{ B) x is 2
t1(); y is 2
t1(); x is 3
y is 2
return 0;
} C) x is 2
y is 2
void t1() x is 3
{ WHAT IF y is 3
static int x = 1; static int x;
int y = 1; x = 1; D) x is 2
x++; y is 2
y++; x is 2
cout << "x is " << x << endl; y is 2
cout << "y is " << y << endl;
} 93
Pass by Value
Write a program for swapping two variables.
void swap(int n1, int n2)
{
int temp = n1;
n1 = n2; The values of the
n2 = temp;
} arguments are not
int main()
changed after the
{ function is invoked.
int num1 = 1;
int num2 = 2;
swap(num1, num2);
cout << "After invoking the swap function, num1 is "
<< num1 << " and num2 is " << num2 << endl;
return 0;
}
After invoking the swap function, num1 is 1 and num2 94
is 2
94
Pass by Value, cont.
95 95
Pass by Reference
Write a program for swapping two variables.
void swap(int&
swap(int n1,
n1,int
int&
n2)
n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int num1 = 1;
int num2 = 2;
swap(num1, num2);
cout << "After invoking the swap function, num1 is "
<< num1 << " and num2 is " << num2 << endl;
return 0;
}
After invoking the swap function, num1 is 2 and num2 96
is 1
96
Pass by Reference, cont.
97 97
Reference Variables Example
int main()
{
int count = 1;
int& r = count;
cout << "count is " << count << endl;
cout << "r is " << r << endl;
r++;
cout << "count is " << count << endl;
cout << "r is " << r << endl;
count is 1
count = 10;
r is 1
cout << "count is " << count << endl; count is 2
cout << "r is " << r << endl; r is 2
count is 10
return 0; r is 10
}
98 98
Constant Reference
Parameters
// Return the max between two numbers
int max(const int& num1,
max(int& num1, const int& num2)
int& num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
99
Usage of Parameter Passing
Call by reference is appropriate for all
objects that may be changed by the
function
Call by value is appropriate for small
objects that should not be changed by
the function
Call by constant reference is
appropriate for large objects that should
not be changed by the function
101 100
Abstract
Data Types
102
101
Abstract Data Types (ADT)
1-103
102
Enumerated Data Type
A programmer-defined data type that consists of values
known as enumerators, which represent integer constants.
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY };
In memory...
SUNDAY = 0
int main() MONDAY = 1
TUESDAY = 2
{ WEDNESDAY = 3
Day day; // Declare THURSDAY = 4
104 103
Enumerated Data Types
C++ allows you to declare an enum and variable in one
statement.
Example:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY} day = MONDAY;
int main()
{
cout << day; // Prints 1
Day day2 = WEDNESDAY;
if (day2 > MONDAY) { …
105 104
Enumerated Data Types
C++ allows you to declare an enum and variable in one
statement.
Example:
int main()
{
enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY} day = MONDAY;
cout << day; // Prints 1
Day day2 = FRIDAY;
if (day2 > MONDAY) { …
106 105
Combining Data into
Structures
Structure: C++ construct that allows multiple
variables to be grouped together
General Format:
struct <structName>
{
type1 field1;
type2 field2;
. . .
};
1-107
106
Example struct Declaration
struct Student
{ structure tag
1-108
107
Defining Variables
struct declaration does not allocate
memory or create variables
To define variables, use structure tag as
type name: hamdy
Student hamdy; studentID
name
intake
gpa
1-109
108
Accessing Structure Members
Use the dot (.) operator to refer to members
of struct variables:
1-111
110
Comparing struct Variables
if (gehad.studentID == stu1.studentID) ✔
1-112
111
Nested Structures
A structure can contain another structure as a
member:
struct PersonInfo
{
string name, address, city;
};
struct Student
{
int studentID;
PersonInfo pData; // structure as a member
short intake;
double gpa;
};
1-113
112
Members of Nested Structures
Use the dot operator multiple times to
refer to fields of nested structures:
Student s;
s.pData.name = "Ahmed";
s.pData.city = "Tanta";
1-114
113
Structures as Function
Arguments
May pass members of struct variables to
functions: computeGPA(mayar.gpa);
1-115
114
Example
Student getStudentData()
{
Student stu;
cin >> stu.studentID;
getline(cin, stu.pData.name);
getline(cin, stu.pData.address);
getline(cin, stu.pData.city);
cin >> stu.intake;
cin >> stu.gpa;
return stu;
}
1-116
115
Example
void getStudentData(Student &stu)
{
//Student stu;
cin >> stu.studentID;
getline(cin, stu.pData.name);
getline(cin, stu.pData.address);
getline(cin, stu.pData.city);
cin >> stu.intake;
cin >> stu.gpa;
//return stu;
}
1-117
116
Random
Numbers
118
117
Computers
and Random Numbers
Computers generate random number for everything from
cryptography to video games and gambling
Random numbers are
– “True” random numbers
https://www.howtogeek.com/183051/htg-explains-how-computers-generate-random-numbers/
118
Computers
and Random Numbers
Computers generate random number for everything from
cryptography to video games and gambling
Random numbers are
– “True” random numbers
– Pseudo-random numbers
Using a mathematical formula
→ A pattern of apparently non-related numbers
Same start-value (seed) to the generator to get the
same sequence results on each run
119
Random Numbers in C++
120
Random Numbers in C++
To generate pseudo-random numbers in a determined range:
122 121
#include <cstdlib> //required for srand and rand
#include <iostream> //required for cout and cin
using namespace std;
int main()
{
double avg = 0.0;
int i, minX = 30, maxX = 50;
int randVal, seed;
cout << "Enter seed: ";
cin >> seed;
srand(seed); // usually called only one time to start a sequence
int main()
{
double avg = 0.0;
int i, minX = 30, maxX = 50;
int randVal, seed;