C++ Boot Camp

Preview:

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

C++ Boot CampC++ Boot Camp

A review of your first C++ class

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

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

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

CoutCout

• Some examples:

cout << “This is a sample string”;

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

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;

CinCin

• More examples:

cin >> my_int;

cin >> age >> name;

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;

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

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

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

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

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

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!

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

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

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!

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)

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

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;

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

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!

Literal ValuesLiteral Values

• Values that are constant• Examples:

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

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;

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

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

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!

Conditionals and Boolean Conditionals and Boolean ExpressionsExpressions

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

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

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!

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

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

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

}

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

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

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

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

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!

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

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

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

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

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}

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

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

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

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

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

}

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?

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

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:

}

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

LoopingLooping

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

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

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

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

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

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

}

Why this worksWhy this works

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

+) {

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

}

counter

1

Why this worksWhy this works

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

+) {

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

}

counter

1true

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

Why this worksWhy this works

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

+) {

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

}

counter

2

Why this worksWhy this works

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

+) {

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

}

counter

2true

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

Why this worksWhy this works

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

+) {

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

}

counter

3

Why this worksWhy this works

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

+) {

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

}

counter

3true

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

Why this worksWhy this works

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

+) {

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

}

counter

4

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

Why this worksWhy this works

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

+) {

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

}

counter

999true

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

Why this worksWhy this works

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

+) {

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

}

counter

1000

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

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

Why this worksWhy this works

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

+) {

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

}

counter

1001

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

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.

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}

ExampleExample

bool teacherHappy = FALSE;int lineNumber = 1;

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

}// assume attitudeFunction can change // teacherHappy

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

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

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

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

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

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

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

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

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

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

Problem Solved…Problem Solved…

int counter = 1;

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

counter++;}

counter

1

Problem Solved…Problem Solved…

int counter = 1;

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

}

counter

1

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

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

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

Problem Solved…Problem Solved…

int counter = 1;

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

}

counter

2

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

Problem Solved…Problem Solved…

int counter = 1;

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

}

counter

3

How does it end?How does it end?

int counter = 1;

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

}

counter

999

How does it end?How does it end?

int counter = 1;

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

}

counter

999

How does it end?How does it end?

int counter = 1;

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

}

counter

999

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

How does it end?How does it end?

int counter = 1;

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

}

counter

1000

How does it end?How does it end?

int counter = 1;

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

}

counter

1000

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

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

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

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

int counter = 0;

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

} while (counter < 3);

counter

0

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

int counter = 0;

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

} while (counter < 3);

counter

0

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

int counter = 0;

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

} while (counter < 3);

counter

1

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

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

int counter = 0;

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

} while (counter < 3);

counter

1

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

int counter = 0;

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

} while (counter < 3);

counter

2

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

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

int counter = 0;

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

} while (counter < 3);

counter

2

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

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

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

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

Functions and Data PassingFunctions and Data Passing

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

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)

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;

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;

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;

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;

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

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)

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;

The ProcedureThe Procedure

• All functions follow a procedure• The procedure is:

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

………

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

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

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

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

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)

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!

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

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

? ? ?

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

? ? ?

? ?

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

? ?

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!

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

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

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

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

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

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!

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

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

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

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

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

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

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

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

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!

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

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

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

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

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

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

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

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.