165
C++ Boot Camp C++ Boot Camp A review of your first C++ class

C++ Boot Camp

  • Upload
    dooley

  • View
    57

  • Download
    0

Embed Size (px)

DESCRIPTION

C++ Boot Camp. A review of your first C++ class. The Skeleton. #include void main ( ) { // Go ahead and memorize this. // It has to be there! } // Note: this should go in a .cpp file. Documenting Your Programs. - PowerPoint PPT Presentation

Citation preview

Page 1: C++ Boot Camp

C++ Boot CampC++ Boot Camp

A review of your first C++ class

Page 2: C++ Boot Camp

The SkeletonThe Skeleton

#include <iostream.h>void main ( ) {

// Go ahead and memorize this.// It has to be there!

}

// Note: this should go in a .cpp file

Page 3: C++ Boot Camp

Documenting Your ProgramsDocumenting 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 */

Page 4: C++ Boot Camp

Printing to the ScreenPrinting 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

Page 5: C++ Boot Camp

CoutCout

• Some examples:

cout << “This is a sample string”;

cout << my_int << endl;cout << “C++ scares me”;cout << “Hello” << “ world!” << endl;

Page 6: C++ Boot Camp

Getting Input from the UserGetting Input from the User

• Use cin (pronounced “see-in”)• Read into variables (later)• Example:

// Declare a variableint myInt;// Load it with information from the keyboardcin >> myInt;// Print it outcout << “myInt is “ << myInt << endl;

Page 7: C++ Boot Camp

CinCin

• More examples:

cin >> my_int;

cin >> age >> name;

Page 8: C++ Boot Camp

Chaining stream OperationsChaining 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;

Page 9: C++ Boot Camp

Special Escape SequencesSpecial 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

Page 10: C++ Boot Camp

Your First C++ ProgramYour First C++ Program

#include <iostream.h>

void main ( ) {cout << “Hello World” << endl;

}

// Note: yes, this should be put into a .cpp file

Page 11: C++ Boot Camp

Rules about SyntaxRules 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

Page 12: C++ Boot Camp

Your First C++ ProgramYour First C++ Program

#include <iostream.h>

void main ( ) {cout << “Hello World” << endl;

}

Begin the main

End the main End a single statement

Page 13: C++ Boot Camp

Compiling Your ProgramCompiling 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

Page 14: C++ Boot Camp

Knowing When to CompileKnowing 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!

Page 15: C++ Boot Camp

Overview of VariablesOverview 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

Page 16: C++ Boot Camp

Data TypesData 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

Page 17: C++ Boot Camp

Primitive Data TypesPrimitive 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!

Page 18: C++ Boot Camp

Primitive Data TypesPrimitive 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)

Page 19: C++ Boot Camp

How to Declare a VariableHow to Declare a Variable(of (of anyany type) type)

• Format:<data type> <variable name>;

• Variable name you can choose almost anything

• Examples:byte age;float gpa;String name;char letterGrade;

age gpa

nameletterGrade

Page 20: C++ Boot Camp

How Big is it: sizeof( )How Big is it: sizeof( )

• sizeof( ) will tell you how much memory something takes up in bytes

• Usage:int myInt;cout << sizeof (myInt) << endl;

Page 21: C++ Boot Camp

Reserved Words in C++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

Page 22: C++ Boot Camp

Legal Variable NamesLegal 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; // legalchar test_value; // legaldouble double; // not legalint rum&coke; // not legalboolean true or false; // not legal for two

reasons!

Page 23: C++ Boot Camp

Literal ValuesLiteral Values

• Values that are constant• Examples:

– String literal – “Hello, World!”– Whole number literal – 17– Decimal literal – 3.14159– Character literal – ‘V’

Page 24: C++ Boot Camp

Initializing VariablesInitializing 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;

Page 25: C++ Boot Camp

Why Size MattersWhy 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;

longshort

long

short

long

short

Page 26: C++ Boot Camp

OperatorsOperators

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

Page 27: C++ Boot Camp

Type CastingType 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!

Page 28: C++ Boot Camp

Conditionals and Boolean Conditionals and Boolean ExpressionsExpressions

Page 29: C++ Boot Camp

A Flow DiagramA Flow Diagram

Did you breakanything?

Are you lying?

Are you passingyour classes?

Yes

Yes

No

No

No

Blame it onsomeone else

Lay low andkeep hidden

Have yourparents asked

about it?

Yes

Yes

Ask for $$

No

Page 30: C++ Boot Camp

The BooleanThe 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

Page 31: C++ Boot Camp

Relational OperatorsRelational Operators(for primitive data types)(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!

Page 32: C++ Boot Camp

Relational Operator Relational Operator ExamplesExamples

• Literal Example5 > 3 // true6 != 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

Page 33: C++ Boot Camp

&& and || Operators&& 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

Page 34: C++ Boot Camp

Now Let’s Do Something!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

}

Page 35: C++ Boot Camp

““if” Exampleif” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start < end ) {

cout << “A”;} // end ifcout << “B”;

} // end main

Page 36: C++ Boot Camp

““if” Exampleif” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start < end ) {

cout << “A”;} // end ifcout << “B”;

} // end main

A

B

Page 37: C++ Boot Camp

““if” Exampleif” Example(Part II)(Part II)

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start > end ) {

cout << “A”;} // end ifcout << “B”;

} // end main

Page 38: C++ Boot Camp

““if” Exampleif” Example(Part II)(Part II)

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start > end ) {

cout << “A”;} // end ifcout << “B”;

} // end main

B

Page 39: C++ Boot Camp

The “else” statementThe “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!

Page 40: C++ Boot Camp

““else” Exampleelse” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start > end ) {

cout << “A”;} // end ifelse {

cout << “B”;} // end else

} // end main

Page 41: C++ Boot Camp

““else” Exampleelse” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start > end ) {

cout << “A”;} // end ifelse {

cout << “B”;} // end else

} // end main

B

Page 42: C++ Boot Camp

““else” Exampleelse” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start < end ) {

cout << “A”;} // end ifelse {

cout << “B”;} // end else

} // end main

Page 43: C++ Boot Camp

““else” Exampleelse” Example

#include <iostream>using namespace std; void main ( ) {

int start = 5;int end = 19;if (start < end ) {

cout << “A”;} // end ifelse {

cout << “B”;} // end else

} // end main

A

Page 44: C++ Boot Camp

else if’selse 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}

Page 45: C++ Boot Camp

Combining into “else if”sCombining into “else if”s(Selecting one from many)(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 ifelse if (start < end) {

cout << “B”;} // end else if

} // end main

Page 46: C++ Boot Camp

Combining into “else if”sCombining into “else if”s(Selecting one from many)(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 ifelse if (start < end) {

cout << “B”;} // end else if

} // end main

A

Page 47: C++ Boot Camp

else catch-all Exampleelse 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 ifelse if (start > end) {

cout << “B”;} // end else ifelse {

cout << “C”;} // end else

} // end main

Page 48: C++ Boot Camp

else catch-all Exampleelse 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 ifelse if (start > end) {

cout << “B”;} // end else ifelse {

cout << “C”;} // end else

} // end main

C

Page 49: C++ Boot Camp

Switch statementsSwitch 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>:

}

Page 50: C++ Boot Camp

Switch ExampleSwitch 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?

Page 51: C++ Boot Camp

Switch ExampleSwitch Example(A better 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

Page 52: C++ Boot Camp

The default keywordThe 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:

}

Page 53: C++ Boot Camp

““default” Exampledefault” 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

Page 54: C++ Boot Camp

LoopingLooping

Page 55: C++ Boot Camp

IterationIteration

• 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

Page 56: C++ Boot Camp

Criteria for loopsCriteria for loops

1. Usually have some initial condition• Starting a counter• Beginning in a certain state

2. Must have a test to continue3. Must make progress towards

finishing

Page 57: C++ Boot Camp

Loops in Everyday LifeLoops 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

Page 58: C++ Boot Camp

The for loopThe 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

Page 59: C++ Boot Camp

Satisfying the TeacherSatisfying 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

Page 60: C++ Boot Camp

““But I want them But I want them numbered!”numbered!”

• No problem…

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

Page 61: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

1

Page 62: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

1true

Page 63: C++ Boot Camp

Why this worksWhy 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

Page 64: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

2

Page 65: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

2true

Page 66: C++ Boot Camp

Why this worksWhy 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

Page 67: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

3

Page 68: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

3true

Page 69: C++ Boot Camp

Why this worksWhy 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

Page 70: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

4

Page 71: C++ Boot Camp

When will it end?When will it end?

• We see that this will go on for a while

• It’s a little more interesting later around 1000

Page 72: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

999true

Page 73: C++ Boot Camp

Why this worksWhy 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

Page 74: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

1000

Page 75: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000;

counter++) {cout << counter << “I will not pour…”<<endl;

}

counter

1000true for last time

Page 76: C++ Boot Camp

Why this worksWhy this works(are we finished?)(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

Page 77: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

}

counter

1001

Page 78: C++ Boot Camp

Why this worksWhy this works

int counter;for (counter = 1; counter <= 1000; counter+

+) {

cout << counter << “I will not pour…”<<endl;

} // Jump down here and continue……

counter

1001false

Page 79: C++ Boot Camp

Final OutputFinal 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.

Page 80: C++ Boot Camp

The while loopThe 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}

Page 81: C++ Boot Camp

ExampleExample

bool teacherHappy = FALSE;int lineNumber = 1;

while (!teacherHappy) {cout << lineNumber << “I will not…” << endl;lineNumber++;teacherHappy = attitudeFunction ( );

}// assume attitudeFunction can change // teacherHappy

Page 82: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 83: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 84: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(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

Page 85: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 86: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 87: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(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

Page 88: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 89: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

}

counter

1

Page 90: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(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

Page 91: C++ Boot Camp

Infinite LoopsInfinite 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 tank1 I will not pour Clorox in the fish tank1 I will not pour Clorox in the fish tank1 I will not pour Clorox in the fish tank

.

.

.

}Continueforever

Page 92: C++ Boot Camp

Problem Solved…Problem Solved…

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;

counter++;}

counter

1

Page 93: C++ Boot Camp

Problem Solved…Problem Solved…

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

1

Page 94: C++ Boot Camp

Problem Solved…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

Page 95: C++ Boot Camp

Problem Solved…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

Page 96: C++ Boot Camp

Example: Re-Writing 1-1000Example: Re-Writing 1-1000(using a while loop)(using a while loop)

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

2

Page 97: C++ Boot Camp

Problem Solved…Problem Solved…

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

2

Page 98: C++ Boot Camp

Problem Solved…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

Page 99: C++ Boot Camp

Problem Solved…Problem Solved…

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

3

Page 100: C++ Boot Camp

How does it end?How does it end?

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

999

Page 101: C++ Boot Camp

How does it end?How does it end?

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

999

Page 102: C++ Boot Camp

How does it end?How does it end?

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

999

Page 103: C++ Boot Camp

Problem Solved…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

Page 104: C++ Boot Camp

How does it end?How does it end?

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

1000

Page 105: C++ Boot Camp

How does it end?How does it end?

int counter = 1;

while (counter < 1000) {cout << counter << “I will not…” << endl;counter++;

}

counter

1000

Page 106: C++ Boot Camp

How does it end?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

1000now false

Page 107: C++ Boot Camp

Another Problem SolvedAnother 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

1000now true

Page 108: C++ Boot Camp

The do-while loopThe do-while loop

• Similar to while loop• Must execute at least one time (test is

at bottom)

• Has format:do {

}while (<boolean value>);

Page 109: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

0

Page 110: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

0

Page 111: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

1

Page 112: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

1

Output: 1

Page 113: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

1

Page 114: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

2

Page 115: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

2

Output: 2

Page 116: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

2

Page 117: C++ Boot Camp

ExampleExample(count from 1 to 3)(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

Page 118: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

3

Output: 3

Page 119: C++ Boot Camp

ExampleExample(count from 1 to 3)(count from 1 to 3)

int counter = 0;

do {counter++;cout << counter << endl;

} while (counter < 3);

counter

3

now false, so loop is finished

Page 120: C++ Boot Camp

Simple RulesSimple 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

Page 121: C++ Boot Camp

Functions and Data PassingFunctions and Data Passing

Page 122: C++ Boot Camp

TerminologyTerminology

• 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

Page 123: C++ Boot Camp

AKAAKA(also known as)(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)

Page 124: C++ Boot Camp

Why have functions?Why have functions?(see anything similar?)(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 codecin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

…cin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

Page 125: C++ Boot Camp

Why have functions?Why have functions?(see anything similar?)(see anything similar?)

All of this codeis 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 codecin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

…cin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

Page 126: C++ Boot Camp

Basic IdeaBasic 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 codecin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

…cin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

Page 127: C++ Boot Camp

Give the function a nameGive 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 codecin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

…cin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

Page 128: C++ Boot Camp

Call the function Call the function (instead of writing all that code)(instead of writing all that code)

double average;int userNum1, userNum2;cout << “Please enter the 2 numbers” << endl;myFunction

…// a lot of other codemyFunction

…myFunction

cin >> userNum1;cin >> userNum2;average = (userNum1 + userNum2) / 2;

myFunction

Page 129: C++ Boot Camp

What have we done?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)

Page 130: C++ Boot Camp

Scope of VariablesScope 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 myIntfunction1 function2

char myChar; int myInt;

Page 131: C++ Boot Camp

The ProcedureThe Procedure

• All functions follow a procedure• The procedure is:

Return type, function name, parametersReturn type, function name, parametersReturn type, function name, parameters

………

Page 132: C++ Boot Camp

The return typeThe 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

Page 133: C++ Boot Camp

Figure out the return typeFigure out the return type

• Function Nameaverage 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

Page 134: C++ Boot Camp

The function’s nameThe 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

Page 135: C++ Boot Camp

ParametersParameters

• 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

Page 136: C++ Boot Camp

ExamplesExamples

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

Page 137: C++ Boot Camp

Getting the function to Work Getting the function to Work for Youfor 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!

Page 138: C++ Boot Camp

ExampleExample(always start at main)(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

Page 139: C++ Boot Camp

ExampleExample(declare variables)(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 num2num3

? ? ?

Page 140: C++ Boot Camp

ExampleExample(declare variables)(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 num2num3

result1 result2

? ? ?

? ?

Page 141: C++ Boot Camp

ExampleExample #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 num2num3

result1 result2

5 7 4

? ?

Page 142: C++ Boot Camp

ExampleExample(call the function)(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 num2num3

result1 result2

5 7 4

? ?

WAKE UP!

Page 143: C++ Boot Camp

ExampleExample(data passing)(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 num2num3

result1 result2

5 7 4

? ?

5 7

Page 144: C++ Boot Camp

ExampleExample(main falls asleep)(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 num2num3

result1 result2

5 7 4

? ?

5 7

// The function is now ACTIVE

Page 145: C++ Boot Camp

ExampleExample(function is doin’ its thing)(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 num2num3

result1 result2

5 7 4

? ?

5 7

// 5 + 7 is 12; 12 / 2 == 6

Page 146: C++ Boot Camp

ExampleExample(function finishes and passes info back)(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 num2num3

result1 result2

5 7 4

? ?

5 7

// 5 + 7 is 12; 12 / 2 == 6

6

Page 147: C++ Boot Camp

ExampleExample(main wakes back up; average sleeps)(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); // 6result2 = average (num3, num1);

}

double average (int x, int y) { return ( (x+y) / 2);}

x y

num1 num2num3

result1 result2

5 7 4

6 ?

sleep

Page 148: C++ Boot Camp

ExampleExample((re-using re-using the average function with num3 and the average function with num3 and

num1)num1) #include <iostream.h>void main ( ){

int num1, num2, num3;double result1, result2;num1 = 5; num2 = 7; num3 = 4; result1 = average (num1, num2); // 6result2 = average (num3, num1);

}

double average (int x, int y) { return ( (x+y) / 2);}

x y

num1 num2num3

result1 result2

5 7 4

6 ?

WAKE UP!

Page 149: C++ Boot Camp

ExampleExample((re-using re-using the average function with num3 and the average function with num3 and

num1)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 num2num3

result1 result2

5 7 4

6 ?

4 5

Page 150: C++ Boot Camp

ExampleExample(main asleep, function awake)(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 num2num3

result1 result2

5 7 4

6 ?

4 5

Page 151: C++ Boot Camp

ExampleExample(function doin’ it again)(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 num2num3

result1 result2

5 7 4

6 ?

4 5

// 4 + 5 == 9; 9 / 2 == 4.5

Page 152: C++ Boot Camp

ExampleExample(function doin’ it again)(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 num2num3

result1 result2

5 7 4

6 ?

4 5

// 4 + 5 == 9; 9 / 2 == 4.5

4.5

Page 153: C++ Boot Camp

ExampleExample(main wakes back up; average sleeps)(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); // 6result2 = average (num3, num1); // 4.5

}

double average (int x, int y) { return ( (x+y) / 2);}

x y

num1 num2num3

result1 result2

5 7 4

6 4.5

sleep

Page 154: C++ Boot Camp

Another Quick ExampleAnother Quick Example(void return types)(void return types)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

void printNum (int myNum) { cout << myNum << endl;}

myNum

sleep

Page 155: C++ Boot Camp

Another Quick ExampleAnother Quick Example(declare variables)(declare variables)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

? ? ?

sleep

void printNum (int myNum) { cout << myNum << endl;}

Page 156: C++ Boot Camp

Another Quick ExampleAnother Quick Example(initialize variables)(initialize variables)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

sleep

void printNum (int myNum) { cout << myNum << endl;}

Page 157: C++ Boot Camp

Another Quick ExampleAnother Quick Example(call the function)(call the function)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

void printNum (int myNum) { cout << myNum << endl;}

myNum

num1 num2num3

5 7 4

WAKE UP!

Page 158: C++ Boot Camp

Another Quick ExampleAnother Quick Example(data passing)(data passing)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

5

void printNum (int myNum) { cout << myNum << endl;}

Page 159: C++ Boot Camp

Another Quick ExampleAnother Quick Example(function does its thing; main asleep)(function does its thing; main asleep)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

5

void printNum (int myNum) { cout << myNum << endl;}

Page 160: C++ Boot Camp

Another Quick ExampleAnother Quick Example(function does its thing; main asleep)(function does its thing; main asleep)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

5

5

void printNum (int myNum) { cout << myNum << endl;}

Page 161: C++ Boot Camp

Another Quick ExampleAnother Quick Example(function is done)(function is done)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

5

5

void printNum (int myNum) { cout << myNum << endl;}

Page 162: C++ Boot Camp

Another Quick ExampleAnother Quick Example(function falls asleep; main awake)(function falls asleep; main awake)

#include <iostream.h>void main ( ){

int num1, num2, num3;num1 = 5; num2 = 7; num3 = 4; printNum (num1);

}

myNum

num1 num2num3

5 7 4

5

void printNum (int myNum) { cout << myNum << endl;}

Page 163: C++ Boot Camp

Function RulesFunction 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

Page 164: C++ Boot Camp

Example of a PrototypeExample of a Prototype(Putting the function below the main)(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

Page 165: C++ Boot Camp

First Programming First Programming AssignmentAssignment

You are to complete programming problem 4 from chapter 8 of your textbook (page 415). Make sure that you prompt the user for the input values of the program and output the result to the screen.

As additional requirements for this program you may only use the cin and cout object in the main function of your program. You must also create at least one other function outside of main.