[go: up one dir, main page]

0% found this document useful (0 votes)
20 views125 pages

CIE 202 - Unit 01 - Basic Programing

This document provides an introduction to basic programming concepts using C++, covering topics such as data types, selections, loops, and arrays. It includes examples of program execution, reading input, and using various operators and control structures. The content is structured to guide learners through fundamental programming principles and practical coding exercises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views125 pages

CIE 202 - Unit 01 - Basic Programing

This document provides an introduction to basic programming concepts using C++, covering topics such as data types, selections, loops, and arrays. It includes examples of program execution, reading input, and using various operators and control structures. The content is structured to guide learners through fundamental programming principles and practical coding exercises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 125

Unit 1

Basic Programing
with C++
Data Types, Selections, Loops,
Arrays
Reference for these slides
Liang, Y. Daniel. Introduction to Programming with C++. Pearson Education India, 2011.
Gaddis, Tony, and Piyali Sengupta. Starting out with C++: from control structures
through objects. Pearson, 2012.
1
Agenda Covered in Lectures

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;

// Step 1: Read in radius


radius = 20;

// Step 2: Compute area


double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
5 5
Trace a Program Execution
allocate memory
for radius
#include <iostream>
using namespace std;
radius no value
int main()
{
double radius; // Declaring a variable of type double
const double PI = 3.14159;

// Step 1: Read in radius


radius = 20;

// Step 2: Compute area


double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
6 6
Trace a Program Execution
allocate memory memory
#include <iostream> for PI
using namespace std;
radius no value
int main() Literal
PI 3.14159
{
double radius;
const double PI = 3.14159;
// Naming a constant, should have a value.

// Step 1: Read in radius


radius = 20;

// Step 2: Compute area


double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
7 7
Trace a Program Execution
#include <iostream> assign 20 to radius memory
using namespace std;
radius 20
int main() PI 3.14159
{
double radius;
const double PI = 3.14159;

// Step 1: Read in radius


radius = 20;// Assignment Statements
Literal
// Step 2: Compute area
double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
8 8
Trace a Program Execution
#include <iostream> memory
using namespace std;
radius 20
int main() PI 3.14159
{ area 1256.636
double radius;
const double PI = 3.14159;
compute area and assign it
// Step 1: Read in radius to a new variable area
radius = 20;

// Step 2: Compute area


double area = radius * radius *
//PI;
Declare variable & assign it

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
9 9
Trace a Program Execution
#include <iostream> memory
using namespace std;
radius 20
int main() PI 3.14159
{ area 1256.636
double radius;
const double PI = 3.14159;

// Step 1: Read in radius print a message to the


radius = 20; console

// Step 2: Compute area


double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
10 10
Reading Input from the Keyboard
#include <iostream>
using namespace std;

int main()
{
double radius;
const double PI = 3.14159;

// Step 1: Read in radius


cout << "Enter a radius: ";// Use the cin object to read
cin >> radius; // input from the keyboard.

// Step 2: Compute area


double area = radius * radius * PI;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
} 11 11
Reading Multiple Input in One Statement
#include <iostream>
using namespace std;

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

short short int –215 to 215–1 (-32,768 to 32,767) 16-bit signed

unsigned short unsigned short int 0 to 216–1 (65535) 16-bit unsigned

int signed –231 to 231–1 (-2147483648 to 2147483647) 32-bit

unsigned unsigned int 0 to 232–1 (4294967295) 32-bit unsigned


signed
long long int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed
unsigned long unsigned long int 0 to 232–1 (4294967295) 32-bit unsigned
long long –263 (-9223372036854775808) to
263–1 (9223372036854775807) 64-bit signed

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.

cout << sizeof(int) << " " <<


sizeof(long) << " " << sizeof(double);

17 17
Numeric Operators

+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

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

short value = 32767 + 1;

-32768

21 21
Arithmetic Expressions
3  4 x 10( y  5)( a  b  c ) 4 9x
  9(  )
5 x x y

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

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

The expression (--var) decrements var by 1 and


pre-
--var evaluates to the new value in var after the
decrement
decrement.
24 24
Increment and
Decrement Operators, cont.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as

int newNum = 10 * (++i); i = i + 1;


int newNum = 10 * i;

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%) with
using twostd;
namespace digits after the decimal point.
int main()
{
// Enter purchase amount
double purchaseAmount;
cout << "Enter purchase amount: ";
cin >> purchaseAmount;

double tax = purchaseAmount * 0.06;


cout << "Sales tax is " << static_cast<int>(tax * 100) /
100.0;

return 0;
}
28 28
Selections

29
if Statements
Boolean Expression

Outer parentheses: Required


if ((radius
radius>=
>=00))
NO Semicolon!!
{
area = radius * radius * PI;
cout << "The area for the circle of " << " radius "
<< radius << " is " << area;
}
}
false
Boolean
Expression
Braces can be omitted if the block contains only
one statement true

Statement(s)

30 30
Relational Operators

Operator Name Example Result

< less than 1 < 2 true


<= less than or equal to 1 <= 2 true
> greater than 1 > 2 false
>= greater than or equal to 1 >= 2 false
== equal to 1 == 2 false
!= not equal to 1 != 2 true

31 31
Examples
 Writea 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
 Writea program that prompts
#includethe<iostream>
user to enter an integer. If the
number is a multiple ofusing namespace std;
5, 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 to
using namespace enter
std; an integer. If the
number is a multiple ofint
5, display
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;
} Nested
else
{
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
if (score >= 95.0)
(score >= 90.0)
an if- if (score >= 95.0)
(score >= 90.0)
cout <<<< "Grade
"Grade is isA";
A"; cout
cout<<
<< "Grade
"Grade is
is A";
A";
else statement elseelse
if (score >= 80.0)
else if (score >= 80.0)
Equivalent cout
if (score
(score >=>= 80.0)
80.0) cout << "Grade
<< "Grade is
is B";
B";
cout <<
cout <<"Grade
"GradeisisB";
B"; elseelse
if (score
if (score>= >=
70.0)
65.0)
else cout << "Grade is C";
cout << "Grade is C";
if (score
if (score>=>=65.0)
70.0) elseelse
if (score >= 60.0)
cout <<
cout <<"Grade
"GradeisisC";
C"; cout
cout<<
<< "Grade
"Grade is
is D";
F";
else
else else
if (score
cout >= 60.0)
<< "Grade is F"; This is better cout << "Grade is F";
cout << "Grade is D";
else
cout << "Grade is F";

(a) (b)

36
What is wrong?

if (score >= 65.0)


cout << "Grade is C";
else if (score >=
80.0)
cout << "Grade is B";
else if (score >=
95.0)
cout << "Grade is A";
else
cout << "Grade is F";

37 37
Logical Operators
Operator Name Description

! not logical negation


&& and logical conjunction
|| or logical disjunction

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 and 3." << endl;

if (number % 2 == 0 || number % 3 == 0)
cout << number << " is divisible by 2 or 3." << endl;

if ((number % 2 == 0 || number % 3 == 0) &&


!(number % 2 == 0 && number % 3 == 0))
cout << number << " divisible by 2 or 3, but not both." <<
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;

if ((number % 2 == 0 || number % 3 == 0) &&


!(number % 2 == 0 && number % 3 == 0))
cout << number << " divisible by 2 or 3, but not both." <<
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.

Write a program that reads and calculates the sum of


an unspecified number of integers. The input 0
signifies the end of the input.

50 50
#include <iostream>
using namespace std;

int main()
{
int data;
cout << "Enter an integer (the input ends if it is 0): ";
cin >> data;

// Keep reading data until the input is 0


int sum = 0;
while (data != 0)
{
sum += data;

// Read the next data


cout << "Enter an integer (the input ends if it is 0): ";
cin >> data;
}

cout << "The sum is " << sum << endl;

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;

// Read the next data


cout << "Enter an integer (the input ends if it is 0): ";
cin >> data;
}
while (data != 0);

cout << "The sum is " << sum << endl;

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);

cout << "The sum is " << sum << endl;


55 55
(1) initialize
for Loops
(2)
(2)Check
Checkbefore
beforeloop
loop
int i;
for (i = 0; i < 100; i++)
{ (4)
(4)Update
Update@@end
endofofloop
loop

cout << "Welcome to C++!\n";


}

(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+
+)
 The action-after-each-iteration in a for loop can be a list of
zero or more comma-separated statements.
for (i = 0; i < 100; i+
 You can have NO stopping condition (infinite loop) +)

for (i = 0; i < 100; i+


+)
for (int i = 1; i < 100; cout << (i++));

57 57
Example: Using for Loops

What does this program do?

// Initialize sum
double sum = 0;

// Add 0.01, 0.02, ..., 0.99, 1 to sum


for (double i = 0.01; i <= 1.0; i = i + 0.01)
sum += i;

// 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?

for (int i = 1; i <= 9; i++)


{
for (int j = 1; j <= 9; j++)
{
// Display the product and align
properly
112 2
3 435 4
6 758 6
9 7 8
cout << setw(3)
" " << i<<
* j;
i * j; 9
2 4 6 8 10 12 14 16 18
} 326 4
9 12
6 15
8 10
18 12
21 14
24 16
27
cout << "\n"; 18
4 8 12 16 20 24 28 32
} 363 6 9 12 15 18 21 24
27
5 10 15 20 25 30 35 40
454 8 12 16 20 24 28 32
36
6 12 18 24 30 36 42 48
545 10 15 20 25 30 35 40
45
7 14 21 28 35 42 49 56
60
636 12 18 24 30 36 42 4860
What does this program do?
int main()
{
int sum = 0;
int number = 0;

while (number < 20)


{
number++;
sum += number; Exit the whole while loop
if (sum >= 100)
break;
}

cout << "The number is " << number << endl;


cout << "The sum is " << sum << endl;

return 0;
}

61
What does this program do?
int main()
{
int sum = 0;
int number = 0;

while (number < 20)


{
number++;
if (number == 10 || number == 11)
continue;
sum += number; End the current iteration
} and jump to the next one

cout << "The sum is " << sum << endl;

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

const int size = 4; ✔


double myList[size]; //
Correct
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;

This is not allowed in C++.

You must copy individual elements from one array to


the other as follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i]; ✔
}
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; (Invoke a function)
cout << "Sum from 35 to 49 is " << sum(35, 49) <<
endl;
return 0;
}
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 int main()
num2) {
{ int i = 5;
int result; int j = 2;
if (num1 > num2) int k = max(i, j);
result = num1; }
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;
}

// Find the max of two double values


double max(double num1, double num2)
{
if (num1 > num2)
return num1;
else
return num2;
}

// Return the max of three double values


double max(double num1, double num2, double num3)
{
return max(max(num1, num2), num3);
}
78
int main()
{
// Invoke the max function with int parameters
cout << "The maximum of 3 and 4 is "
<< max(3, 4) << endl;

// Invoke the max function with the double parameters


cout << "The maximum of 3.0 and 5.4 is "
<< max(3.0, 5.4) << endl;

// Invoke the max function with three double parameters


cout << "The maximum of 3.0, 5.4, and 10.14 is "
<< max(3.0, 5.4, 10.14) << endl;

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 int max(int num1, int
Function Declaration

num2) num2);
{
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; }
}

Function Declaration
int max(int num1, int
int main() num2)
{ {
int i = 5; int result;
int j = 2; if (num1 > num2)
int k = max(i, j); result = num1;
} else
result = num2;
return result; 81
#include <iostream>
using namespace std;

// Function prototype Can be moved to a separate header


int max(int num1, int num2); file. MyFile.h
double max(double num1, double num2);
Then add:
double max(double num1, double num2, double num3);
#include "MyFile.h"
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;
}

int max(int num1, int num2)


{

} Should be moved with the
double max(double num1, double num2) prototypes to MyFile.h
{ or to MyFile.cpp

}
double max(double num1, double num2, double num3) Reusing Functions by
{
Different Programs

}

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

cout << "area is " << length * width << endl;


}

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;
int main() cout<<"year is
{ "<<year<<endl;
int month = 10, year = 2008; cout<<"month is "<< 9
f(month, year); <<endl;
f(9, 2010); cout<<"year is "<< 2010
<<endl;
return 0; f(9, 2010);
}
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

void function1() void function2()


{ {
int x = 1; int i = 1;
int y = 1; int sum = 0;

for (int i = 1; i < 10; i++) for (int i = 1; i < 10; i++)
{ {
x += i; sum += i;
} }

for (int i = 1; i < 10; i++) cout << i << endl;


{ cout << sum << endl;
y += 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

B) x is 1
int main()
y is 0
{ x is 2
t1(); y is 2
t2();
return 0; C) x is 1
} y is 0
x is 1
y is 1
int y; // 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; 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 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 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
100 100
Abstract
Data Types

101

101
Abstract Data Types (ADT)
 A datatype created by programmers that
specifies
– values that can be stored
– operations that can be done on the values

 User of an ADT does not need to know


the implementation of the data type, e.g.,
how the data is stored

1-102
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
MONDAY = 1
int main() TUESDAY = 2
{ WEDNESDAY =
3
Day day; // Declare THURSDAY = 4
day = MONDAY; // Assign to one of the
values
cout << day; // Prints 1
Day day2 = WEDNESDAY; // Declare and
Assign
if (day2 > MONDAY) { … 103 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) { …

104 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) { …

105 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-106
106
Example struct Declaration
struct Student
{ structure tag

int studentID; structure members


string name;
short intake;
double gpa;
};

1-107
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-108
108
Accessing Structure Members
 Use the dot (.) operator to refer to members
of struct variables:

cin >> stu1.studentID;


getline(cin,
stu1.name);
stu1.gpa = 3.75;

 Member variables can be used in any manner


appropriate for their data type
1-109
109
Displaying a struct Variable

cout << ayman; // won’t work if ayman


is
// defined as a struct
cout << ayman.studentID << endl;
cout << ayman.name << endl; ✔
cout << ayman.intake << endl;
cout << ayman.gpa << endl;

1-110
110
Comparing struct Variables

if (gehad == stu1) // won’t work

if (gehad.studentID == stu1.studentID) ✔

1-111
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-112
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-113
113
Structures as Function
Arguments
 May pass members of struct variables to
functions: computeGPA(mayar.gpa);

 May pass entire struct variables to functions:


showData(mayar);

 Can be passed by reference

 Functions can return a struct.

1-114
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-115
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-116
116
Random
Numbers

117

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++

 Should include <cstdlib> header file


 Functions provided:
void srand(unsigned int seed);
 Sets the seed for the random number generator

int rand();
 Generates and returns an integer value in the

range 0..RAND_MAX (a constant in cstdlib)


 C++'s random number generator has a period of 232

120
Random Numbers in C++
To generate pseudo-random numbers in a determined range:

int v1, v2, v3;


v1 = rand() % 100; // v1 in the range 0 to 99
v2 = rand() % (100 + 1);
// v2 in the range 0 to 100
v3 = rand() % 100 + 1; // v3 in the range 1 to 100
v4 = rand() % 30 + 1985;
// v4 in the range 1985-2014

121 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

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


{ // rand() is called each time a pseudo-random number is
randVal = rand() % (maxX - minX + 1) + minX;
needed
cout << randVal << endl;
}
for (i = 0; i < 10000; i++)
{
avg += rand() % (maxX - minX + 1) + minX;
}
avg = avg / 10000;
cout << "Avg of 10000: " << avg << endl;
return (0);
}
122
Enter seed: 12 Enter seed: 1652 Enter seed: 12
42 38 42
46 32 46
40 43 40
41 43 41
40 36 40
43 48 43
32 34 32
38 48 38
31 31 31
42 49 42
Avg of 10000: 39.9971 Avg of 10000: 40.0484 Avg of 10000: 39.9971

Note: Same seed = same sequence = same results


123
Using Time to Seed the Generator

 If you hard code the seed or allow the user to


enter a seed, simulated randomness is lost
 Most programmers use the “time” function to
seed the generator
– Must include the <time.h> library
 Call function “time()”
– time(NULL)
 Returns the current time from the system

clock expressed in number of seconds


elapsed since 00:00 hours, Jan 1, 1970
UTC
124
#include <cstdlib> //req'd for srand and rand
#include <iostream> //req'd for cout and cin
#include <time.h> //req’d for time
using namespace std;

int main()
{
double avg = 0.0;
int i, minX = 30, maxX = 50;
int randVal, seed;

srand(time(NULL)); // Use the clock to seed the generator

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


{
randVal = rand() % (maxX - minX + 1) + minX;
cout << randVal << endl;
}
for (i = 0; i < 10000; i++)
{
avg += rand() % (maxX - minX + 1) + minX;
}
avg = avg / 10000;
cout << "Avg of 10000: " << avg << endl;
return (0);
}
125

You might also like