0% found this document useful (0 votes)
39 views

Review 1 C++ Programming 2

The document provides a review of key concepts for a C++ programming course, including identifiers, literals vs constants, arithmetic precision and type casting, shorthand notation, and conditional statements. It emphasizes choosing meaningful identifiers, using constants instead of literals when possible, and being aware of arithmetic precision for expressions involving different data types. Examples are provided to illustrate proper use of prefix/postfix operators and how they affect evaluation order in expressions.

Uploaded by

CRMSN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Review 1 C++ Programming 2

The document provides a review of key concepts for a C++ programming course, including identifiers, literals vs constants, arithmetic precision and type casting, shorthand notation, and conditional statements. It emphasizes choosing meaningful identifiers, using constants instead of literals when possible, and being aware of arithmetic precision for expressions involving different data types. Examples are provided to illustrate proper use of prefix/postfix operators and how they affect evaluation order in expressions.

Uploaded by

CRMSN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

REVIEW 1

CS A250 – C++ Programming II


WHAT ARE WE REVIEWING?
 Prerequisite for this course: CS A150

 This presentation will only outline important key


points that are needed for this class.
 It is your responsibility to review any topic from CS
A150 not covered in this class’s reviews.
 This review contains a collection of items that you
need to keep in mind when coding to avoid losing
points.

2
OBJECTIVES
 Items that will be reviewed:
 Identifiers
 Literals vs. constants
 Arithmetic precision, type casting, and decimal format
 Shorthand notation / Prefix and postfix
 The optional else
 Conditional operator
 Functions and passing parameters
 Function overloading
 Arrays and vectors: capacity, size and number of elements
 The const modifier for parameters
3
IDENTIFIERS, LITERALS AND
CONSTANTS
4
IDENTIFIERS
 An identifier is a name given to a variable, a
constant, a function, an object, a class…

int myInteger = 3;

vector<int> myVector;

MyClass myObject;

 Identifiers in C++ are case-sensitive


5
GOOD PROGRAMMING PRACTICE
 To improve readability:
 Choose meaningful identifiers

 Do not abbreviate

 Follow the standards we discussed for this class

(see syllabus)

6
LITERAL DATA
 Literals
 Examples:
 2 // Literal constant int
 5.75 // Literal constant double
 ‘Z’ // Literal constant char
 "Hello World" // Literal constant string

 Cannot change values during execution


 Called "literals" because you "literally” type them
in your program!

7
CONSTANTS
 Literals are "OK", but provide little meaning
 For example, seeing the number 24 throughout your
code, tells nothing about what it represents

 Use named constants instead


const int NUMBER_OF_STUDENTS = 24;

 Use all CAPITAL_LETTERS separated by an underscore


for identifiers that refer to constants.

 Added benefit: changes to value can be done in one fix


8
WHICH ONE TO USE?
 Use a literal if
 You are using that value only once
 The value will never change (weeks in a year)
 If you use a literal, always provide a comment to
explain what the value represents
 Example: Dividing a salary by 52 weeks
 Can leave “52” because it is used only once, but need to
comment about what it represents.
 Use a global constant if the value will be used
more than once AND/OR the value might need to
be changed in the future
 Example: An interest rate 9
ABOUT GLOBAL VARIABLES…
 Do NOT use them!
 Only global constants will be allowed!

10
NUMBERS
11
ARITHMETIC PRECISION
 Precision of calculations
 VERY important consideration!
 Expressions in C++ might not evaluate as you would
"expect"!
 "Highest-order operand" determines type of arithmetic
"precision" performed
 Common error!

(see examples on next slide)

12
ARITHMETIC PRECISION (CONT.)
 Examples:
 17 / 5 evaluates to 3 in C++
 Both operands are integers
 Integer division is performed and gives incorrect result

 17.0 / 5 equals 3.4 in C++


 Double "precision" division is performed

 The following performs integer division, giving a


result of 0

int n1 = 1,
n2 = 2;
cout << (n1/ n2);
(more…) 13
ARITHMETIC PRECISION (CONT.)
 Calculations done "one-by-one"
 1 / 2 / 3.0 / 4 performs 3 separate divisions
 First 1 / 2 equals 0
 Then 0 / 3.0 equals 0.0
 Then 0.0 / 4 equals 0.0!

 So changing just "one operand" in a large


expression can lead to incorrect results
 Must keep in mind all individual calculations
that will be performed during evaluation!
 Do NOT trust your program…
 Trust your calculator

14
TYPE CASTING
 Casting for variables
 Can add ".0" to literals to force precision arithmetic

cout << (5.0 / 2) << endl;

 Can use static_cast<type> for variables


 Casting is only temporary → variable num will stay an integer

int num = 2;
double x = static_cast<double>(num) / 2;

 Do NOT use (double)num 15


FORMATTING DECIMALS
 Decimal format is only for output
 Option 1:

cout.setf(ios::fixed);
cout.setf(ios::showpoint); //shows point even if 0
cout.precision(2); //shows 2 decimals

 Option 2:

#include <iomanip>
...
cout << fixed << showpoint << setprecision(2);
16
SHORTHAND NOTATION
17
SHORTHAND NOTATIONS
 Use them!

18
PREFIX AND POSTFIX
 Post-Increment
int n1 = 3;
int n2 = n1++;
 Uses current value of variable, THEN increments it
 Pre-Increment
int n1 = 3;
int n2 = ++n1;
 Increments variable first, THEN uses new value

 No difference if "alone" in statement:


n1++;
++n1;
they both give the same result. 19
PREFIX IN EXPRESSIONS

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 2


{
cout << firstNumber << endl;
}
cout << firstNumber;

What is the output?

20
PREFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 2 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

This happens first


and firstNumber
is incremented by 1.

21
PREFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 3


{
cout << firstNumber << endl; 3 < 3 ? FALSE
}
cout << firstNumber;

Comparison happens next.

22
PREFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

Condition is false and body


of loop will not be executed.

23
PREFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

Program continues and prints


value of firstNumber.

24
PREFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (++firstNumber < secondNumber) firstNumber = 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

OUTPUT:

25
POSTFIX IN EXPRESSIONS

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 2


{
cout << firstNumber << endl;
}
cout << firstNumber;

What is the output?

26
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 2


{
cout << firstNumber << endl; 2 < 3 ? TRUE
}
cout << firstNumber;

The whole condition


is evaluated first.

27
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 2 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

The value of firstNumber


is incremented by 1.

28
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

Body of loop is executed.

OUTPUT:
3
29
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 3


{
cout << firstNumber << endl; 3 < 3 ? FALSE
}
cout << firstNumber;

Condition is
evaluated again.

OUTPUT:
3
30
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 3 4


{
cout << firstNumber << endl;
}
cout << firstNumber;

The value of firstNumber


is incremented by 1.

OUTPUT:
3
31
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 4


{
cout << firstNumber << endl;
}
cout << firstNumber;

Condition is false and body


of loop will not be executed.

OUTPUT:
3
32
POSTFIX IN EXPRESSIONS (CONT.)

int firstNumber = 2,
secondNumber = 3;

while (firstNumber++ < secondNumber) firstNumber = 4


{
cout << firstNumber << endl;
}
cout << firstNumber;

Program continues and prints


value of firstNumber again.

OUTPUT:
3
4 33
PREFIX AND POSTFIX
 As we saw, prefix and postfix might change the
results of the statement.
int firstNumber = 2,
secondNumber = 3; OUTPUT:

while (++firstNumber < secondNumber) 3


{
cout << firstNumber << endl;
}
cout << firstNumber;

int firstNumber = 2,
secondNumber = 3;

OUTPUT: while (firstNumber++ < secondNumber)


{
3 cout << firstNumber << endl;
4 } 34
cout << firstNumber;
CONDITIONS
35
THE OPTIONAL ELSE
 In an if statement, else clause is optional
 If, in the false branch (else), you want "nothing" to
happen → leave it out
 Example:

if (sales >= minimum)


salary += bonus;
cout << "Salary = " << salary;

 Note:
 Nothing to do for false condition, so there is no else clause!
 Execution continues with cout statement 36
CONDITIONAL OPERATOR
 Conditional operator, also called
"ternary operator"
 Essentially "shorthand if-else" operator

if (n1 > n2)


max = n1;
else
max = n2;

 Can be written:

max = (n1 > n2) ? n1 : n2;

37
 "?" and ":" form the "ternary" operator
CONDITIONAL OPERATOR
 Avoid using the conditional operator in an
output expression, because misplacing
parenthesis can produce unwanted results:

cout << ( ( grade < 60 ) ? “fail” : “pass” );


// prints pass or fail

cout << ( grade < 60 ) ? “fail” : “pass”;


// prints 1 or 0

cout << grade < 60 ? “fail” : “pass”;


// error: compares cout to 60

38
FUNCTIONS
39
FUNCTIONS
 Two types:
 void
 Does not return a value

Do NOT exit from a void function using


return;
Find an elegant way to terminate the execution of the function.

 return a value
 In C++
 Only one value can be returned

 Cannot return arrays

 Cannot return functions 40


FUNCTION DECLARATION
 Function declaration
 Syntax

return_type funcName ( parameter_list);

 Goes before main( ) function


 May or may not have parameters
 Although there is no need for parameter names, it improves
readability to include names.
 Comments go before or after function declaration
 Also known as function prototypes

41
FUNCTION DEFINITIONS
 Function definition
 Syntax

return_type funcName (parameter_list )


{
// body
}

 Goes after the main( ) function


 May or may not have a parameter list
 Parameters are automatic objects
 They are destroyed when execution of the function
terminates, just like local variables 42
ARGUMENT PASSING
 The type of parameter determines the
interaction between the parameter and its
argument

 If the parameter is passed by reference


 Parameter is bound to its argument

 If the parameter is passed by value


 The value is copied

43
PASSING ARGUMENTS BY VALUE
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n = 3;
myFunction(n);
cout << n;
...
}
void myFunction (int n)
{
++n;
cout << n << endl; 44
}
PASSING ARGUMENTS BY VALUE
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n;
...
}
void myFunction (int n)
{
++n;
cout << n << endl; 45
}
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n;
... call to myFunction (3)
}
void myFunction (int n)
{
++n;
cout << n << endl; 46
}
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n;
...
}
void myFunction (int n) int n
{ 3
++n;
cout << n << endl; a local copy of n 47
} is created
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n;
...
}
void myFunction (int n) int n
{ 4
++n;
cout << n << endl; local variable n 48
} is incremented
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n; OUTPUT:
...
} 4
void myFunction (int n) int n
{ 4
++n;
cout << n << endl; cout statement 49
} is executed
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n; OUTPUT:
...
} 4
void myFunction (int n)
{ function execution is
terminated and all local
++n;
variables are destroyed
cout << n << endl; 50
}
PASSING ARGUMENTS BY VALUE (CONT.)
 When passing arguments by value, any changes made to
the function parameter will not change the argument.

int main( )
{
int n
int n = 3;
myFunction(n); 3
cout << n; OUTPUT:
... return to function call
and print n again 4
}
3
void myFunction (int n)
{
++n;
cout << n << endl; 51
}
PASSING ARGUMENTS BY REFERENCE
 When passing by reference

 Address of argument is passed

 Caller’s data can be modified by called function

 Typically used
 For input function to retrieve data for caller,
data is then "given" to caller
 When more than one value needs to be returned

 Specified by ampersand (&) after type in parameter


list 52
PASSING ARGUMENTS BY REFERENCE
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{
int n = 3;
myFunction(n);
cout << n;
...
}
void myFunction (int& n)
{
++n;
cout << n << endl; 53
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 3
myFunction(n);
cout << n;
...
}
void myFunction (int& n)
{
++n;
cout << n << endl; 54
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 3
myFunction(n);
cout << n; call to myFunction (3)
...
}
void myFunction (int& n)
{
++n;
cout << n << endl; 55
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 3
myFunction(n);
cout << n;
...
address of n is passed
}
void myFunction (int& n) int& n
{
[address]
++n;
cout << n << endl; 56
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 4 increments
myFunction(n); variable at
cout << n; address
...
finds the
}
address in
void myFunction (int& n) int& n local scope
{
[address]
++n;
cout << n << endl; increment n 57
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 4
myFunction(n);
cout << n; OUTPUT:
...
} 4
void myFunction (int& n) int& n
{
[address]
++n;
cout << n << endl; cout statement is executed 58
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 4
myFunction(n);
cout << n; OUTPUT:
...
} 4
void myFunction (int& n)
{ function execution is
++n; terminated and all local
cout << n << endl; variables are destroyed
59
}
PASSING ARGUMENTS BY REFERENCE (CONT.)
 When passing arguments by reference, any changes made
to the function parameter will change the argument.

int main( )
{ int n
int n = 3; 4
myFunction(n);
cout << n; return to function call OUTPUT:
... and print n again
} 4
4
void myFunction (int& n)
{
++n;
cout << n << endl; 60
}
EXAMPLE
 Project: parameter_passing

61
FUNCTION OVERLOADING
 Overloaded functions have
 Same function name
 Different parameter lists
 Two separate function declarations/definitions
 Function "signature"
 Function name & parameter list
 Must be "unique" for each function definition

 Allows same task performed on different data

62
FUNCTION OVERLOADING (CONT.)
 Example:

double compute( double n1, double n2);


double compute( double n1, double n2, double n3);
double compute( int n1, double n2);

 The above functions have the same name but have


parameters that differ in numbers and/or types.

 Careful: Return type does not matter


63
ARRAYS AND VECTORS
64 Capacity, size, and number of elements
CAPACITY, SIZE, AND NUMBER OF ELEMENTS
 Arrays are frequently partially filled.
 Need to differentiate the physical length of the
array from the actual number of elements that
occupy the array.
 We will use the following conventions:
 The capacity to define the physical length of the
array
 The number of elements to define the total number
of items stored in the array.

 We will NOT use “size” when referring to arrays.


65
CAPACITY OF STATIC ARRAYS
 Capacity of static arrays must be defined at
compilation time
 Always use defined/named constant for array
capacity

const int CAPACITY = 5;

...

int score[CAPACITY];

66
VECTOR SIZE
 The STL vector class defines size as the
number of elements stored in the vector.
 If using a loop, avoid calling the function size
inside the loop and use a variable instead

int size = static_cast<int>( v.size() );

for (int i = 0; i < size; ++i)


cout << v[i] << " ";

Function size() returns an unsigned int,


but we can cast it to an int.
67
REFERENCE, VALUE AND const
MODIFIER FOR PARAMETERS
68
THE const MODIFIER FOR PARAMETERS
 Reference arguments inherently "dangerous"
 Caller’s data can be changed
 Often this is desired, sometimes not
 Use the const modifier to “protect” data

 So, when should you use & and when const?

69
WHEN TO PASS BY REFERENCE (&)?
 When passing objects
 They are large; no need to make another copy
 Example: strings, vectors, objects of classes you
created

void someFunction(string& name, MyClass& obj)


{
// does something
}

70
WHEN TO PASS BY REFERENCE? (CONT.)
 When passing variables that need to be changed and
retain their new value after the function is done

double calculatePayCheck() The value of payRate


{ and hours will be
double payRate = 0.0, hours = 0.0; determined by the
getInfo(payRate, hours); user and they need to
return (payRate * hours); send the information
} back to the function
void getInfo(double& payRate, double& hours) calling.
{
cout << “Enter pay rate and total hours worked: ”;
cin >> payRate >> hours;
}

71
WHEN TO USE const?
 IF you are passing by reference (&)
 AND the value passed by the parameter
should not be modified inside the function
 THEN use const

void printVector(const vector<int>& v)


{
int size = static_cast<int>( v.size() );

for (int i = 0; i < size; ++i)


cout << v[i] << " ";
}

72
PASSING ARRAYS
 Careful! Arrays are automatically passed by
reference, but no & is used!
 Need to use const when necessary

void fillArray(int a[], int numOfElem) Array will be modified.


{ Cannot use const.
for (int i = 0; i < numOfElem; ++i)
a[i] = i + 1;
}
void printArray(const int a[], int numOfElem)
{
for (int i = 0; i < numOfElem; ++i) Array should not be
modified. Use const.
cout << a[i] << “ ”;
}

73
EXAMPLES
 Project: arrays
 Project: vectors

74
GOOD PROGRAMMING
75
CHANGING FLOW OF CONTROL

   IMPORTANT   

Do NOT use:

• break (except on switch statements) and/or

• continue in any of the exercises and /or


programming exams

Choose an elegant way to exit loops and functions.

76
A FEW RULES
 When creating a new VS project
 Name your project “Project”
 You should rename the folder later
 If the project name is too long, files might not be transfer

when you turn in your project


 Name the file that contains the main( ) function
“Main.cpp”
 We will be exchanging files; therefore, we ALL need to use
same naming conventions
 Do NOT forget the name header
 You will lose points if you do
 Make sure has the same format shown on the syllabus

77
A FEW RULES (CONT.)
 When coding:
 Leave a space in between operators
 Leave a line in between blocks of code
 Split statements to avoid horizontal scrolling
 Improve readability when writing decimal numbers:
0.0 instead of .0
3.0 instead of 3
 Write code that is easy to read and understand
 You are not going to look “cool” if you write some code that
is difficult to read
 Declare variables only right before you need them,
instead of listing them at the beginning of the 78
function
ARE YOU DETAIL ORIENTED?
 As a programmer, you need to:

 Make sure your program is readable

 Choose an implementation that makes your code


efficient

 Follow instructions carefully

79
END REVIEW 1
80

You might also like