SlideShare a Scribd company logo
1 of 167
C++
Introduction
Ajay Khatri
Topics
• Data Types
• Operators
• Conditional Statement
• Loops
• Functions
The 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 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 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
Cout
• Some examples:
cout << “This is a sample string”;
cout << my_int << endl;
cout << “C++ scares me”;
cout << “Hello” << “ world!” << endl;
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;
Cin
• More examples:
cin >> my_int;
cin >> age >> name;
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;
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
Your First C++ Program
#include <iostream.h>
void main ( ) {
cout << “Hello World” << endl;
}
// Note: yes, this should be put into a .cpp file
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
Your First C++ Program
#include <iostream.h>
void main ( ) {
cout << “Hello World” << endl;
}
Begin the main
End the main End a single statement
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
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!
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
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
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!
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)
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
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++
• 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 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!
Literal Values
• Values that are constant
• Examples:
– String literal – “Hello, World!”
– Whole number literal – 17
– Decimal literal – 3.14159
– Character literal – ‘V’
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;
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
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
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!
Conditionals and Boolean
Expressions
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
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
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!
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
&& 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!
• 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” 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
“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
“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
“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
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!
“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
“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
“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
“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
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
}
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
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
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
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
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>:
}
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?
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
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:
}
“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
Looping
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
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
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
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
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
“But I want them numbered!”
• No problem…
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1
true
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
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
2
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
2
true
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
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
3
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
3
true
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
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
4
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 works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
999
true
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
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1000
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1000
true for last time
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
Why this works
int counter;
for (counter = 1; counter <= 1000; counter++) {
cout << counter << “I will not pour…”<<endl;
}
counter
1001
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
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.
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
}
Example
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-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
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
Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
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
Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
Example: Re-Writing 1-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
}
counter
1
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
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
Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1
Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1
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…
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-1000
(using a while loop)
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
2
Problem Solved…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
2
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…
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
3
How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
999
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?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1000
How does it end?
int counter = 1;
while (counter < 1000) {
cout << counter << “I will not…” << endl;
counter++;
}
counter
1000
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
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
The do-while loop
• Similar to while loop
• Must execute at least one time (test is at
bottom)
• Has format:
do {
}while (<boolean value>);
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
0
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
0
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
Output: 1
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
1
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
Output: 2
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
2
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
Example
(count from 1 to 3)
int counter = 0;
do {
counter++;
cout << counter << endl;
} while (counter < 3);
counter
3
Output: 3
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
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
Functions and Data Passing
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
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)
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;
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;
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;
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;
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
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 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;
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
…
…
…
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
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
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
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
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)
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!
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
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
? ? ?
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
? ? ?
? ?
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
? ?
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!
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
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
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
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
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
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!
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
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
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
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
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
Another Quick Example
(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 Example
(declare variables)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
myNum
num1 num2 num3
? ? ?
sleep
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(initialize variables)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
myNum
num1 num2 num3
5 7 4
sleep
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(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 num2 num3
5 7 4
WAKE UP!
Another Quick Example
(data passing)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
myNum
num1 num2 num3
5 7 4
5
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(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 num2 num3
5 7 4
5
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(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 num2 num3
5 7 4
5
5
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(function is done)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
myNum
num1 num2 num3
5 7 4
5
5
void printNum (int myNum) {
cout << myNum << endl;
}
Another Quick Example
(function falls asleep; main awake)
#include <iostream.h>
void main ( )
{
int num1, num2, num3;
num1 = 5; num2 = 7; num3 = 4;
printNum (num1);
}
myNum
num1 num2 num3
5 7 4
5
void printNum (int myNum) {
cout << myNum << endl;
}
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
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
Study
Material
Android App to learn C++
https://play.google.com/stor
e/apps/details?id=learn.a
pps.cppprogramming
Thank
You

More Related Content

Similar to C++ Introduction for Beginners

Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ toolAbdullah Jan
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1Mohamed Ahmed
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1Amr Alaa El Deen
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.gerrell
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptxMattMarino13
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptUdhayaKumar175069
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in Cummeafruz
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functionsray143eddie
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptAlefya1
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 

Similar to C++ Introduction for Beginners (20)

Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in C
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 

More from Ajay Khatri

Ajay khatri resume august 2021
Ajay khatri resume august 2021Ajay khatri resume august 2021
Ajay khatri resume august 2021Ajay Khatri
 
Competitive Programming Guide
Competitive Programming GuideCompetitive Programming Guide
Competitive Programming GuideAjay Khatri
 
Zotero : Personal Research Assistant
Zotero : Personal Research AssistantZotero : Personal Research Assistant
Zotero : Personal Research AssistantAjay Khatri
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2Ajay Khatri
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTMLAjay Khatri
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Ajay Khatri
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Ajay Khatri
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)Ajay Khatri
 

More from Ajay Khatri (9)

Ajay khatri resume august 2021
Ajay khatri resume august 2021Ajay khatri resume august 2021
Ajay khatri resume august 2021
 
Competitive Programming Guide
Competitive Programming GuideCompetitive Programming Guide
Competitive Programming Guide
 
Zotero : Personal Research Assistant
Zotero : Personal Research AssistantZotero : Personal Research Assistant
Zotero : Personal Research Assistant
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

C++ Introduction for Beginners

  • 2. Topics • Data Types • Operators • Conditional Statement • Loops • Functions
  • 3. The Skeleton #include <iostream.h> void main ( ) { // Go ahead and memorize this. // It has to be there! } // Note: this should go in a .cpp file
  • 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;
  • 8. Cin • More examples: cin >> my_int; cin >> age >> name;
  • 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
  • 122. Functions and Data Passing
  • 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
  • 155. Another Quick Example (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
  • 156. Another Quick Example (declare variables) #include <iostream.h> void main ( ) { int num1, num2, num3; num1 = 5; num2 = 7; num3 = 4; printNum (num1); } myNum num1 num2 num3 ? ? ? sleep void printNum (int myNum) { cout << myNum << endl; }
  • 157. Another Quick Example (initialize variables) #include <iostream.h> void main ( ) { int num1, num2, num3; num1 = 5; num2 = 7; num3 = 4; printNum (num1); } myNum num1 num2 num3 5 7 4 sleep void printNum (int myNum) { cout << myNum << endl; }
  • 158. Another Quick Example (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 num2 num3 5 7 4 WAKE UP!
  • 159. Another Quick Example (data passing) #include <iostream.h> void main ( ) { int num1, num2, num3; num1 = 5; num2 = 7; num3 = 4; printNum (num1); } myNum num1 num2 num3 5 7 4 5 void printNum (int myNum) { cout << myNum << endl; }
  • 160. Another Quick Example (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 num2 num3 5 7 4 5 void printNum (int myNum) { cout << myNum << endl; }
  • 161. Another Quick Example (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 num2 num3 5 7 4 5 5 void printNum (int myNum) { cout << myNum << endl; }
  • 162. Another Quick Example (function is done) #include <iostream.h> void main ( ) { int num1, num2, num3; num1 = 5; num2 = 7; num3 = 4; printNum (num1); } myNum num1 num2 num3 5 7 4 5 5 void printNum (int myNum) { cout << myNum << endl; }
  • 163. Another Quick Example (function falls asleep; main awake) #include <iostream.h> void main ( ) { int num1, num2, num3; num1 = 5; num2 = 7; num3 = 4; printNum (num1); } myNum num1 num2 num3 5 7 4 5 void printNum (int myNum) { cout << myNum << endl; }
  • 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
  • 166. Study Material Android App to learn C++ https://play.google.com/stor e/apps/details?id=learn.a pps.cppprogramming