This document provides an introduction and overview of key concepts in C++ programming, including data types, operators, conditional statements, loops, functions, variables, input/output, and more. It begins with an introduction and overview of topics to be covered. It then demonstrates the basic structure of a C++ program, use of comments, printing to the screen, getting user input, and chaining stream operations. The document continues explaining additional concepts like special characters, data types, operators, conditional statements, switch statements, and looping structures. It provides examples throughout to demonstrate each concept.
4. Documenting Your Programs
• This is called “commenting”, and the
computer ignores this when compiling.
• There’s 2 ways to do it in C++!
// This is for a single line comment.
/* This is for a paragraph of comments
and can go on and on. It doesn’t matter
until you see the */
5. Printing to the Screen
• Use cout to do this (pronounced “see-out”)
• cout can print out just about anything
– Variables of most data types
– Multiple things at once
– Special characters like ‘n’ (newline), etc.
• Print multiple things with additional <<‘s
• Print out endl to drop to next line
6. Cout
• Some examples:
cout << “This is a sample string”;
cout << my_int << endl;
cout << “C++ scares me”;
cout << “Hello” << “ world!” << endl;
7. Getting Input from the User
• Use cin (pronounced “see-in”)
• Read into variables (later)
• Example:
// Declare a variable
int myInt;
// Load it with information from the keyboard
cin >> myInt;
// Print it out
cout << “myInt is “ << myInt << endl;
9. Chaining stream Operations
• There is no limit to the number of things
that you can print & read
• Simply chain them together like this:
cout << “First item” << “second item” << endl;
10. Special Escape Sequences
• Added within strings
• Performs “special character”
n newline
r carriage return (not common)
t tab
a alert (beep)
backslash
’ single quote
” double quote
11. Your First C++ Program
#include <iostream.h>
void main ( ) {
cout << “Hello World” << endl;
}
// Note: yes, this should be put into a .cpp file
12. Rules about Syntax
• Where do the ;’s go?
– Semicolons come after single statements
– Similar to a period at the end of a sentence
• Where do the { and } go?
– Creates a block of text for multiple single
statements
– { tells the computer to begin a section
– } tells the computer to end a section
– Can be nested (or inside of each other)
• Let’s go back to our first c++ program
13. Your First C++ Program
#include <iostream.h>
void main ( ) {
cout << “Hello World” << endl;
}
Begin the main
End the main End a single statement
14. Compiling Your Program
• You’ll use one of two things:
– The command-line: g++ (on Unix)
– Your IDE (like Visual C++)
• When you compile, you’ll have one of two
things happen:
– It compiles
– It doesn’t
• If it doesn’t compile, you have syntax errors
15. Knowing When to Compile
• As a rule, the less comfortable you are, the
more you should compile
• This isolates the errors
• As a rule, compile:
– After you type in the skeleton
– After every 5 or 10 lines of new code
• Don’t become dependent on the compiler!
16. Overview of Variables
• Computer programs manipulate data
• There is a need to store data
• Variables:
– Represent a named cell in the computer’s memory
– Used to hold information
• When you declare a variable:
– You open up some of the computer’s memory
– You’re giving the variable an identifier (name)
• You only do this once per variable
17. Data Types
• A data type describes the kind of information a
variable can hold
• Some data types are built into the language
• Some data types we define ourselves (later)
• Different Forms:
– Primitive data types
– Complex data types
18. Primitive Data Types
• These are the simplest kinds of data types
• Built-in
• Whole numbers:
– short (relatively small numbers)
– int (larger numbers)
– long (VERY large numbers)
• Number of bytes these take up depends on
compiler and OS!
19. Primitive Data Types
• Decimal numbers:
– float (less precise than a double)
– double (more precise than a float)
– Precision means how many numbers come
after the decimal point
• Others:
– char (holds characters like ‘a’, ‘A’, ‘1’, ‘ ‘)
– bool (holds only a true or false value)
20. How to Declare a Variable
(of any type)
• Format:
<data type> <variable name>;
• Variable name you can choose almost anything
• Examples:
byte age;
float gpa;
String name;
char letterGrade;
age gpa
name letterGrade
21. How Big is it: sizeof( )
• sizeof( ) will tell you how much memory
something takes up in bytes
• Usage:
int myInt;
cout << sizeof (myInt) << endl;
22. Reserved Words in C++
• These words are used by C++ for special
reasons, so you can’t use them
• List:
– auto, bool, break, case, catch, char, class, const,
continue, default, do, double, else, enum, extern,
float, for, friend, goto, if, inline, int, long,
namespace, new, operator, private, protected,
public, register, return, short, signed, sizeof,
static, struct, switch, template, this, throw, try,
typedef, union, unsigned, void, volatile, while
23. Legal Variable Names
• Can’t be a reserved word
• Can’t begin with a number
• Can’t contain special symbols
– Like #, @, !, ^, &, /, ), or SPACES
– Exceptions: underscore _, and dollar sign $
• Examples:
byte $theValue; // legal
char test_value; // legal
double double; // not legal
int rum&coke; // not legal
boolean true or false; // not legal for two reasons!
24. Literal Values
• Values that are constant
• Examples:
– String literal – “Hello, World!”
– Whole number literal – 17
– Decimal literal – 3.14159
– Character literal – ‘V’
25. Initializing Variables
• Initializing a variable means giving a variable
some kind of starting value
• Assignment operator is =
• Copies the information on the right into the
variable on the left and must be compatible
• Can be a literal OR another variable!
• Examples:
int age;
age = 15;
char letterGrade = ‘B’;
char yourGrade = letterGrade;
26. Why Size Matters
• Each data type takes up a different amount of the computers
memory (in bytes)
• Can’t put a larger data typed variable into a smaller data typed
variable:
short s = 5; long l = 5;
long l = s; short s = l;
long
short
long
short
long
short
27. Operators
• + adds two variables/literals together
(including Strings)
• - subtraction
• / division
• * multiplication
• % modulus (remainder)
• ( and ) follows standard math rules
• Example:
int result = ( (4 % 3) * 5) + 1; // result gets 6
28. Type Casting
• This occurs when you want to put something
larger into something smaller
• Can possibly lose precision or value
• Has format:
<smaller var> = (<smaller data type>)<larger var>;
• Example:
long myLong = 17;
short myShort = (short)myLong;
// We are squeezing myLong into myShort!
30. A Flow Diagram
Did you break
anything?
Are you lying?
Are you passing
your classes?
Yes
Yes
No
No
No
Blame it on
someone else
Lay low and
keep hidden
Have your
parents asked
about it?
Yes
Yes
Ask for $$
No
31. The Boolean
• A bool is a something that resolves to true
(1) or false (0)
• You can get booleans several different ways
– Simple
– Complex
• These booleans will be used (later) to
make decisions to change your program’s
behavior
32. Relational Operators
(for primitive data types)
• Relational Operators
> greater than
< less than
== equals
! Not
!= not equal
>= greater than or equal
<= less than or equal
• Notice that all of these return us a true or false
value!
33. Relational Operator Examples
• Literal Example
5 > 3 // true
6 != 6 // false
(4 <= 2) // false
‘c’ != ‘b’ // true
!0 // true (prints out 1)
• Variable Example
int num1 = 5;
short num2 = 7;
bool result = num2 > num1;
//Note: result is now true
34. && and || Operators
• These operators check for multiple conditions
• && (AND) needs both the left and the right to be
true in order to return true
• || (OR) needs either one (or both) to be true to
return true
• Can shortcut if necessary
• Examples:
( (6 > 5) && ( ‘c’ == ‘b’) ) // false
( (6 > 5) && ( 7 < 9) ) // true
( (6 > 5) || ( ‘c’ == ‘b’) ) // true
( (6 > 6) || ( ‘c’ == ‘b’) ) // false
35. Now Let’s Do Something!
• Using the if statement, we can decide
whether or not to execute some code!
• Has format:
if (<boolean value>) {
// all the code that’s in here will only execute
// if and only if the boolean above is true
}
36. “if” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
cout << “A”;
} // end if
cout << “B”;
} // end main
37. “if” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
cout << “A”;
} // end if
cout << “B”;
} // end main
A
B
38. “if” Example
(Part II)
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
cout << “A”;
} // end if
cout << “B”;
} // end main
39. “if” Example
(Part II)
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
cout << “A”;
} // end if
cout << “B”;
} // end main
B
40. The “else” statement
• if has a counterpart – the else statement
• If the if clause didn’t execute, the else clause
will!
• Has format:
if (<boolean value>) {
// statements that execute if the boolean is true
}
else {
// statements that execute if the boolean is false
}
• Notice only one set of statements executes, no
matter what!
41. “else” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
cout << “A”;
} // end if
else {
cout << “B”;
} // end else
} // end main
42. “else” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
cout << “A”;
} // end if
else {
cout << “B”;
} // end else
} // end main
B
43. “else” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
cout << “A”;
} // end if
else {
cout << “B”;
} // end else
} // end main
44. “else” Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
cout << “A”;
} // end if
else {
cout << “B”;
} // end else
} // end main
A
45. else if’s
• Selecting one from many
• As soon as one is true, the rest are not considered
• Has format:
if (<boolean value>) {
// statements that execute if the above boolean is true
}
else if (<boolean value>){
// statements that execute if the above boolean is true
}
else if (<boolean value>){
// statements that execute if the above boolean is true
}
else {
// something that executes if nothing matched above
}
46. Combining into “else if”s
(Selecting one from many)
#include <iostream>
using namespace std;
void main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start < middle ) {
cout << “A”;
} // end if
else if (start < end) {
cout << “B”;
} // end else if
} // end main
47. Combining into “else if”s
(Selecting one from many)
#include <iostream>
using namespace std;
void main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start < middle ) {
cout << “A”;
} // end if
else if (start < end) {
cout << “B”;
} // end else if
} // end main
A
48. else catch-all Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start > middle ) {
cout << “A”;
} // end if
else if (start > end) {
cout << “B”;
} // end else if
else {
cout << “C”;
} // end else
} // end main
49. else catch-all Example
#include <iostream>
using namespace std;
void main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start > middle ) {
cout << “A”;
} // end if
else if (start > end) {
cout << “B”;
} // end else if
else {
cout << “C”;
} // end else
} // end main
C
50. Switch statements
• Simplify the else-if statements for primitive data
types
• Trying to find a match
• Once a match is found, it will keep going until it
sees the break keyword (telling it to stop)
• Has format:
switch (<primitive variable>) {
case <value>:
case <value>:
}
51. Switch Example
#include <iostream>
using namespace std;
void main ( ) {
int myInt = 1;
switch (myInt) {
case 1: cout << “A”;
case 2: cout << “B”;
case 3: cout << “C”;
} //end switch
} //end main
// Prints out A, B, and C. Why?
52. Switch Example
(A better example)
#include <iostream>
using namespace std;
void main ( ) {
int myInt = 1;
switch (myInt) {
case 1: cout << “A”;
break;
case 2: cout << “B”;
break;
case 3: cout << “C”;
} //end switch
} //end main
// Only prints out A, because break makes stop
53. The default keyword
• Same thing as the else keyword in an else-
if situation
• It’s the catch-all
• Format:
switch (<primitive variable>) {
case <value>:
case <value>:
default:
}
54. “default” Example
#include <iostream>
using namespace std;
void main ( ) {
int myInt = 5;
switch (myInt) {
case 1: cout << “A”;
break;
case 2: cout << “B”;
break;
default: cout << “C”;
} //end switch
} //end main
// Only prints out C, because of the default
56. Iteration
• One thing that computers do well is repeat
commands
• Programmers use loops to accomplish this
• 3 kinds of loops in C++
– for loop
– while loop
– do while loop
57. Criteria for loops
1. Usually have some initial condition
• Starting a counter
• Beginning in a certain state
2. Must have a test to continue
3. Must make progress towards finishing
58. Loops in Everyday Life
• Bad children are told to write sentences on
the board
“I will not pour Clorox in the fish tank”
• Have to write this sentence either
– A certain number of times
– Until the teacher is happy
– As many as you can during break
59. The for loop
• Good when you know exactly how many times
you need to execute something
• Has format:
for (<initialization>; <test to continue>; <increment>) {
// everything in here is what is repeated
// over and over again
}
• Initialization is where the counter is given a starting
value
• The test determines whether or not to continue
• The increment can be any amount, including negative,
and occurs after the loop statements execute
60. Satisfying the Teacher
• Example: 1000 sentences? No problem…
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << “I will not pour Clorox…” << endl;
}
// Remember, counter++ is the same as
// counter = counter + 1
61. “But I want them numbered!”
• No problem…
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
62. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1
63. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1
true
64. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Output: 1 I will not pour Clorox in the Fish Tank
counter
1
65. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
2
66. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
2
true
67. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Output: 2 I will not pour Clorox in the Fish Tank
counter
2
68. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
3
69. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
3
true
70. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Output: 3 I will not pour Clorox in the Fish Tank
counter
3
71. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
4
72. When will it end?
• We see that this will go on for a while
• It’s a little more interesting later around
1000
73. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
999
true
74. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Output: 999 I will not pour Clorox in the Fish Tank
counter
999
75. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1000
76. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1000
true for last time
77. Why this works
(are we finished?)
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Output: 1000 I will not pour Clorox in the Fish Tank
counter
1000
78. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1001
79. Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
} // Jump down here and continue
…
…
counter
1001
false
80. Final Output
1 I will not pour Clorox in the fish tank.
2 I will not pour Clorox in the fish tank.
3 I will not pour Clorox in the fish tank.
4 I will not pour Clorox in the fish tank.
.
.
.
999 I will not pour Clorox in the fish tank.
1000 I will not pour Clorox in the fish tank.
81. The while loop
• Good for when you don’t know how many
times to repeat
• Teacher says “Write until I’m happy”
• Has format:
while (<boolean value>) {
// stuff to repeat over and over
}
82. Example
bool teacherHappy = FALSE;
int lineNumber = 1;
while (!teacherHappy) {
cout << lineNumber << “I will not…” << endl;
lineNumber++;
teacherHappy = attitudeFunction ( );
}
// assume attitudeFunction can change
// teacherHappy
83. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
84. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
85. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
Output: 1 I will not pour Clorox in the fish tank
counter
1
86. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
87. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
88. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
Output: 1 I will not pour Clorox in the fish tank
counter
1
89. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
90. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
91. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
Output: 1 I will not pour Clorox in the fish tank
counter
1
92. Infinite Loops
• This loop isn’t making a lot of progress!
• Loops that repeat forever are called infinite loops
• Apparently “lock up”
• Output:
1 I will not pour Clorox in the fish tank
1 I will not pour Clorox in the fish tank
1 I will not pour Clorox in the fish tank
1 I will not pour Clorox in the fish tank
.
.
.
} Continue
forever
93. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1
94. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1
95. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
Output: 1 I will not pour Clorox in the fish tank
counter
1
96. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
2
// Remember, counter++ is the same as
// counter = counter + 1
97. Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
2
98. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
2
99. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
Output: 2 I will not pour Clorox in the fish tank
counter
2
100. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
3
101. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
102. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
103. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
104. Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
Output: 999 I will not pour Clorox in the fish tank
counter
999
105. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1000
106. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1000
107. How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
// So we never print out
// 1000 I will not pour Clorox in the fish tank
counter
1000
now false
108. Another Problem Solved
int counter = 1;
while (counter <= 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
// So we can now finish printing
// Still fails at 1001
counter
1000
now true
109. The do-while loop
• Similar to while loop
• Must execute at least one time (test is at
bottom)
• Has format:
do {
}while (<boolean value>);
110. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
0
111. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
0
112. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
113. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
Output: 1
114. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
115. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
116. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
Output: 2
117. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
118. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
// Note: counter is now 3, but we still have
// to finish out the loop – it doesn’t skip
counter
3
119. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
3
Output: 3
120. Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
3
now false, so loop is finished
121. Simple Rules
• for loops good for when you know how
many times you want to repeat
• while and do-while good for when you
don’t
• All loops must finish, or they become
infinite loops
• All loops must have a test to continue, or
they become infinite loops
123. Terminology
• A function is a logical grouping of statements
• Reusable chunks of code
– Write once
– Call as many times as you like
• Benefits
– Reusable
– Easy to work at higher level of abstraction
– Reduces complexity
– Reduces size of code
124. AKA
(also known as)
• Functions can be called several things,
depending on the book or context
• Examples:
– Procedure
– Module
– Method (OOP)
– Behavior (OOP)
– Member function (OOP)
125. Why have functions?
(see anything similar?)
double average;
int userNum1, userNum2;
cout << “Please enter the 2 numbers” << endl;
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
// a lot of other code
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
126. Why have functions?
(see anything similar?)
All of this code
is the same!
double average;
int userNum1, userNum2;
cout << “Please enter the 2 numbers” << endl;
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
// a lot of other code
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
127. Basic Idea
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
Create function instead
double average;
int userNum1, userNum2;
cout << “Please enter the 2 numbers” << endl;
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
// a lot of other code
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
128. Give the function a name
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
myFunction
double average;
int userNum1, userNum2;
cout << “Please enter the 2 numbers” << endl;
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
// a lot of other code
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
…
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
129. Call the function
(instead of writing all that code)
double average;
int userNum1, userNum2;
cout << “Please enter the 2 numbers” << endl;
myFunction
…
// a lot of other code
myFunction
…
myFunction
cin >> userNum1;
cin >> userNum2;
average = (userNum1 + userNum2) / 2;
myFunction
130. What have we done?
• Written the code once, but called it many
times
• Reduced the size of our code
• Easier to comprehend
• Tracing of code skips all around (no longer
linear)
131. Scope of Variables
• Scope – “who can see what”
• Variables that are defined within a function can
only be seen by that function!
• We need a way to send information to the
function
• We need a way for the function to send back
information
• Example: function1 can’t see myInt
function1 function2
char myChar; int myInt;
132. The Procedure
• All functions follow a procedure
• The procedure is:
Return type, function name, parameters
Return type, function name, parameters
Return type, function name, parameters
…
…
…
133. The return type
• A function has the option to return us (the main
algorithm) some information
• If the function doesn’t return us any info, the
return type is void
• Otherwise, the return type is the data type it’s
going to return
• Example of return types:
– int
– char
– boolean
134. Figure out the return type
• Function Name
average double or float
getLetterGrade char
areYouAsleep boolean
getGPA double or float
printMenu void
// Don’t confuse what a function does with it’s
// return type!
getStudentName String
135. The function’s name
• Similar to naming of variables
• Can be almost anything except
– A reserved word (keywords)
– Can’t begin with a number
– Can’t contain strange symbols except _ and $
• Function names should begin with a lower case
• If multiple words in function name, capitalize the first
letter in each word (except the first)
• Example:
thisIsAnExample
136. Parameters
• Functions cannot see each other’s
variables (scope)
• Special variables used to “catch” data
being passed
• This is the only way the main algorithm
and functions have to communicate!
• Located between parentheses ( )
• If no parameters are needed, leave the
parentheses empty
137. Examples
• Remember the procedure
• What can you tell me about these functions?
void doSomething (int data)
double average (int num1, int num2)
boolean didHePass ( )
char whatWasHisGrade ( )
void scareStudent (char gradeOfStudent)
138. Getting the function to Work for
You
• Call it by name
• Pass it the right stuff
– Pass the right number of parameters
– If it expects two things, pass it two things!
– Pass the right type of parameters
– If it expects a char, don’t pass it a double!
– Parameters must match exactly
• If it returns something, do something with it!
139. Example
(always start at main)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
// Note: the average function is currently inactive
140. Example
(declare variables)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
// Note: the average function is currently inactive
num1 num2 num3
? ? ?
141. Example
(declare variables)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
// Note: the average function is currently inactive
num1 num2 num3
result1 result2
? ? ?
? ?
142. Example
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
// Note: the average function is currently inactive
num1 num2 num3
result1 result2
5 7 4
? ?
143. Example
(call the function)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
? ?
WAKE UP!
144. Example
(data passing)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
? ?
5 7
145. Example
(main falls asleep)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
? ?
5 7
// The function is now ACTIVE
146. Example
(function is doin’ its thing)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
? ?
5 7
// 5 + 7 is 12; 12 / 2 == 6
147. Example
(function finishes and passes info back)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
? ?
5 7
// 5 + 7 is 12; 12 / 2 == 6
6
148. Example
(main wakes back up; average sleeps)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2); // 6
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
sleep
149. Example
(re-using the average function with num3 and num1)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2); // 6
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
WAKE UP!
150. Example
(re-using the average function with num3 and num1)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
4 5
151. Example
(main asleep, function awake)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
4 5
152. Example
(function doin’ it again)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
4 5
// 4 + 5 == 9; 9 / 2 == 4.5
153. Example
(function doin’ it again)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2);
result2 = average (num3, num1);
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 ?
4 5
// 4 + 5 == 9; 9 / 2 == 4.5
4.5
154. Example
(main wakes back up; average sleeps)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
double result1, result2;
num1 = 5; num2 = 7; num3 = 4;
result1 = average (num1, num2); // 6
result2 = average (num3, num1); // 4.5
}
double average (int x, int y) {
return ( (x+y) / 2);
}
x y
num1 num2 num3
result1 result2
5 7 4
6 4.5
sleep
164. Function Rules
• You cannot define a function inside of
another function
• Functions usually reside in a class (later)
• Put functions above the call to the function
• Otherwise, use a prototype
• Functions cannot see each other’s
variables
165. Example of a Prototype
(Putting the function below the main)
#include <iostream.h>
void printNum (int myNum);
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
void printNum (int myNum) {
// Remember, printNum can’t see num1, num2 or num3!
cout << myNum << endl;
}
Here’s the prototype