You are on page 1of 40

Monday, Oct 11

Questions about Project #1?


Week 1 review challenge
A potpourri of new topics

More about variables


New operators (+=, ++, etc.)
The if statement
String variables

th

Review Challenge
This program computes the average of 2 numbers and
prints the result. Find the syntax & semantic errors.
#include <iostream>
int main(void)
{
int sum, a,
b;
std::cout << Enter 2 numbers:\n;
std ::
cin >> a;
sum = sum + a;
std::c
in >> b
sum = sum + b;
sum = sum / 2;
std::cout >> Average: + sum;
;
)

Review Challenge
Given a number, n, in seconds, print out the number of
hours, minutes and seconds that n represents.
#include <iostream>

E.g. if the user types in


7265, the program
should print:

int main(void)
{
int n;

Hours: 2
Minutes: 1
Seconds: 5

std::cout << Enter n: ;


std::cin >> n;
// add your code here
std::cout <<
std::cout <<
std::cout <<
}

;
;
;

Hint: Use regular division


and modulo division

More About Variables


Learn how to use char
variables.
Learn how to initialize
more than one variable
at a time
Learn about const
variables
Learn some new C++
operators

Linda writes her


first C++ program

char variables
int main(void)
{
char small_num;
small_num = -125;

// this is OK!

char grade, punct;


grade = A;
punct = $;
cout << Your grade is: << grade;

Last time we learned


that char variables can
hold numbers between
-127 and 128.
A char variable can also
hold a symbolic
character, like a letter
or a punctuation mark.

To assign a symbolic value to a character variable, use


single quotation marks and .
You print out character variables just like you do any
other variable.

char variables
#include <iostream>
int main(void)
{
char grade;
cout << Enter desired grade: ;
cin >> grade;
cout << You dont deserve a <<
grade;
}

grade

Enter desired grade: B


You dont deserve a B

P
B

You can also


prompt the user
to input a single
character using
std::cin.
The user can
type in a single
character and
then hit the
enter key.

Assigning Multiple Variables


at The Same Time
#include <iostream>
int main(void)
{
int a, b, c;

Sometimes its convenient to assign many


variables to the same value at once.
This is how you do it.
#include <iostream>

a = b = c = 5;
int main(void)
{
int a, b, c;

c = 5;
b = c;
a = b;

And heres how C++ treats it.

Const Variables
Whats wrong with this program?
#include <iostream>
int main(void)
{
double rad;
std::cout << Enter the radius of your zit: ;
std::cin >> rad;
std::cout << Zit circumference: << 2 * rad * 3.141;
std::cout << Zit area: << rad*rad * 3.141;
}

Hint:
1.What do we have to do to our program
to get increased precision (3.141 ->3.14159)?

Const Variables
Use const variables when you have a value that is
fixed (like , the speed of light, etc.), and is
used multiple times in your program.
You can define your
constant variable at the
int main(void)
top of your program once
{
3.141592653; and then use it over and
const double PI = 3.14;
over.
double rad;
#include <iostream>

std::cout << Enter the radius of your zit: ;


Then you can be sure you
std::cin >> rad;

use the exact same value

std::cout << Zit circumference: << 2 * rad * PI;


everywhere
in your
std::cout << Zit area: << rad*rad
* PI;

program.

Const Variables
Once a variable is defined as const, its value cant be changed.
Also, you must set the value of a const variable when it is defined.
#include <iostream>
int main(void)
{
const int numHumanLegs = 2;

numHumanLegs = 10;

// syntax error!

const float gallonsOfPhlegm;= 365;

//
// OK!
syntax error!

New Operators: +=, -=, *= and /=


Before:

a -88
45
1
5
15
11

int main(void)
{
int a;

After:
int main(void)
{
int a;

a = 5; a = 5 + 10;
a = a + 10;
a = a * 3; a = 15 * 3;
a = a / 4; a = 45 / 4;
a = a % 2; a = 11 % 2;
std::cout << a;
}

a = 5;
a += 10;
a *= 3;
a /= 4;
a %= 2;
std::cout << a;
}

The +=, *=, /= and %= operators are basically


shorthand notation for lazy C++ programmers.

New Operators: ++ and -int main(void)


{
int a = 5;
a = a 1;

int main(void)
{
int a = 5;
a--; // OR --a;
int b = 6;
b++; // OR ++b;

int b = 6;
b = b + 1;
}

The ++ and -- operators allow you to quickly


increment and decrement variables by one.
But theres a catch!!!

++ and -- Specifics
You may only use the ++ and -- operators with
variables. Not with expressions or numbers.
int main(void)
{
int a = 5;

++a;

// this is just fine

++(a+5);

// SYNTAX ERROR!

7--;

// SYNTAX ERROR!

The if Statement
The if statement is used to make decisions in your
C++ programs.
// Lets learn the IF statement
#include <iostream>

passcode

91

int main(void)
{
int passcode;

If the the passcode


is equal to 9939 then
do the
cout << "Enter password:
"; next line.
Note: No semicolon!
std::cin >> passcode;
If the the passcode
Is 1234 equal
to 9939?
is not
equal to 9939
if (passcode == 9939)
then do the
next line. Enter password: 1234
std::cout << "Password
accepted.\n";
Is 1234 not equal to 9939?

if (passcode != 9939)
std::cout << "\aInvalid password.\n";
}

Invalid password.

Introducing the if Statement


The if statement is used to test whether or not an
expression is true or false.

If this is true

if ( expression )
do this statement;

Then run the command


before the semicolon.

The program runs the statement before the next semicolon


only if the expression is true.

Here are some sample expressions:

> bbb )
aaa>=
!=
==
ais
greater
than
b;
a
has
has
greater
athe
different
same
thanvalue
or
value
equal
asthan
b;
to b;
b;
cout << a

if (

The if Statement
Lets learn how to use more advanced forms of the
if statement

Form #1
if ( expression )
do this statement;
else
do this statement;

If the expression is
true, e.g. age < 34, then
C++ runs the first
statement, else C++ runs
the second statement.

#include <iostream>
using namespace std;
int main(void)
{
int age;
cout << "Enter age: ";
cin >> age;
if (age < 34)
cout << Just a kid";
else
cout << Old f@rt!;
}

The if Statement
Lets learn how to use more advanced forms of the
if statement

Form #2

if ( expression )
do this statement;
else if ( expression2 )

do this statement;
else if ( expression3 )
do this
this statement;
statement;
do
else if ( expression4 )
do this statement;

#include <iostream>
using namespace std;
int main(void)
{
int price;
cout << "Enter the price: ";
cin >> price;
if (price > 100)
cout << Expensive";
else if (price < 20)
cout << Cheap;
else
cout << Just right.;
}

The if Statement
As soon as a condition is found to be true in a set of if, else-if
statements, none of the else clauses are evaluated.
#include <iostream>
int main(void)
{
int score = 80;

80 >= 90???

score

80

You got a B, not bad!


Now go study some more!

if (score >= 90)


cout << You got an A, good job!\n;
80 >= 80???
else if (score >= 80)
cout << You got a B, not bad.\n;
skip else if (score >= 70)
cout << You got a C, you slacker!\n;
skip else
cout << You must be taking Dr. Smallbergs class.\n;
cout << Now go study some more!\n;
}

The if Statement
Sometimes, you might want to run more than one
statement if your expression is true

if ( expression )

{ do this statement;
else
do this statement
statement;too;
}

{ do this statement;

#include <iostream>
using namespace std;
int main(void)
{
int hairs;
cout << "Enter hairs: ";
cin >> hairs;

also do this;
and this too;

if (hairs < 100)


{
cout << Youre balding..";
cout << You must be Carey;
}

This is called a block.

cout << Have a nice day.;


}

The if Statement
You can also define new variables
within any block in your program.

if ( expression )
{
do this
int
foo,statement;
bar;
float
bletch
= 16; too;
do this
statement
When
a block
exits, all
}

int main(void)
{
int hairs;

hairs

177
125
-18

cout << "Enter hairs: ";


cin >> hairs;

250 > 100??

if (hairs > 100)


{
int real_hairs;

of its variables
disappear!

Enter hairs: 250


Liar, you have 125
Have a nice day

real_hairs

250/2

real_hairs = hairs / 2;
cout << Liar, you have <<
real_hairs;
}
cout << Have a nice day\n;
}

Be Careful With The if Statement


int main(void)
{
int

Whats wrong with it?


How do we fix it?

iq;

std::cout << "Enter your IQ: ";


std::cin >> iq;

31 > 100???

if (iq > 100)

iq -47
31

{ std::cout << Thats pimp!\n";


} std::cout << Youre smart!\n";

Ignore next statement!

Enter your IQ: 31


Youre smart!

Be Careful With The if Statement


int main(void)
{
int
iq;

intWhats
main(void)
wrong with it?
{
int
iq;

std::cout <<"Enter IQ:";


std::cout <<"Enter IQ:";
std::cin
>> iq;
std::cin >> iq;
Youre not supposed
to have
a ; here
if (iq < 100)
if (iq < 100) ;
do-nothing-here;
std::cout << USC student";
std::cout << USC student";
}
}

If you put a semicolon after an if statement, this is what the


compiler thinks you mean
Remember, the if statement will run the command before the
next semicolon. If there is no command before the semicolon,
then your program will just do nothing.

More Problems With if

int main()
{
int num_beers;
std::cin >> num_beers;
if (num_beers > 3)
if (num_beers < 15)
{
std::cout <<
Drunk but alive\n;
if (num_beers
< 15)
std::cout << Drunk but alive\n;
else
std::cout <<
<< Barely
Barely buzzed.\n;
buzzed.\n;
}
std::cout
} else
std::cout << Barely buzzed.\n;
}

What will this


program print if I
drink
A. 2 beers
B. 7 beers
C. 18 beers

Now what happens if I change the program in the following way


Does the else clause go with the top if statement or the bottom
one?

Confusing, huh? In general, use { and } to make things


unambiguous.

The if Statement
Sometimes you will see C++ programmers place an arithmetic
expression in between the parentheses of an if statement.

int main()
a 5
{
b
4
int a = 5, b = 4;

(5-4)*3
3

if ((a b)*3)
std::cout<< Will it print this\n;
else
std::cout << or this?\n;
}
If the expressions value is not equal to zero, then the
program runs the next statement as if the expression were
true.

The if Statement
Sometimes you will see C++ programmers place an arithmetic
expression in between the parentheses of an if statement.

int main()
a 5
{
b
5
int a = 5, b = 5;

(5-5)*3
0

if ((a b)*3)
std::cout<< Will it print this\n;
else
std::cout << or this?\n;
}
If the expressions value is equal to zero, then the program
runs the else statement as if the expression were false.

Be Careful With If Statements!


Questions:
1. Wheres the error?
2. What will be printed out?
3. How do you fix it?
4. How can you really fix it?

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

iq 981
50
179

iq;

cout << "Enter your IQ: ";


cin >> iq;
if (iq = 50)
cout << "You belong at USC.\n";
cout << "Your IQ: " << iq << "\n";
}

Enter your IQ: 179

You belong at USC.

Your IQ: 50

An example with if and char


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

Note: A is less than B and B


is less than C, etc.
Also a is not equal to A.
Chars are case sensitive!

cout << "Enter the first letter of your name: ";


cin >> firstLetter;
if (firstLetter == A)
cout << Is your name Alice?\n";
else if (firstLetter >= M)
cout << You might be Mary or Nancy...\n;
}

An Interesting Idea
Question: Why would I use the following syntax in my
program?
int main(void)
{
int score;

cin >> score;


if (0 == score)
cout << Oh dear!\n;

Instead of
int main(void)
{
int score;

cin >> score;


if (score == 0)
cout << Oh dear!\n;

An Interesting Idea
Answer: To prevent bugs like the following:

int main(void)
{
int score;

cin >> score;


if (score = 0)
cout << Oh dear!\n;

An Interesting Idea
Lets see how it works!

int main(void)
{
int score;

int main(void)
{
int score;

cin >> score;


if (0 == score)
cout << Oh dear!\n;

Syntax error!

cin >> score;


if (0 = score)
cout << Oh dear!\n;

If you make this kind of logic error,


your program will give a compile
error, and you can fix it right away.

C++ Strings
So far, weve learned how to define integer and floatingpoint variables.
C++ also lets us define string variables.
Instead of holding numbers like int or double, string
variables holds a string of characters.

To use string variables you should add the following


statements to the top of your program:
#include <string>
// put at the top of your program
using namespace std; // or write: using std::string;

C++ Strings
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string myname;
myname = Carey;
cout << Hello, << myname;
}

myname Carey

Hello, Carey

You can define a new


string variable just like
you define any other C++
variable.
Unlike normal variables,
string variables always
start out empty when you
define them,
You must use
double quotation marks
and when you assign a
string variable to a string
value.

C++ Strings
#include <iostream>
#include <string>

You can input a string


from the user using the
standard cin >> command.

using namespace std;


int main(void)
{
string myname;

BUT cin will only allow you


to type in a single word at
a time.

cout << Name? ;


cin >> myname;
cout << Hello << myname;
}

myname

Alan

If you type in more than one word, only the


first word will be stored in your variable.

Name? Alan Wang


Hello Alan

C++ Strings
You can use the
comparison operators
on strings as well.

#include <iostream>
#include <string>
using namespace std;

As with char variables,


comparisons are case
sensitive.

int main(void)
{
string myname;
cout << Name? ;
cin >> myname;
if (myname == Carey)
cout << You stud!\n;
else
cout << You slacker!\n;
}

myname

CAREY

Name? CAREY
You slacker!

C++ Strings
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string password;
cout << Password? ;
cin >> password;
if (password < UCLA)
cout << Too low;
else if (password > UCLA)
cout << Too high!;
else
cout << Welcome,
master.\n;

< <= > and >=


comparisons are done
lexicographically.
Alan comes before
Aron. Aron comes
before Ben, etc
Zooplankton comes
before aardvark
(lowercase letters come
after uppercase letters)

Concatenating C++ Strings


#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string msg1 = Go;

Go + Bruins
msg1 = msg1 + Bruins;
cout << msg1 << \n;
msg1 += !!!;
! ! !
cout << msg1 << \n;
}

You can use + or += to


concatenate one
string onto another
string.
msg1

Go

Go Bruins
Go Bruins!!!

Inputting Multi-word Strings


To prompt the user for
more than one word and
store them into a string
variable, you must use the
getline function.

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string pass;
cout << Enter password: ;
getline(cin, pass);
if (pass == UCLA rules)
cout << Welcome Carey;
else
cout << Youre not Carey;
}

pass

UCLA rules

Dont use cin >> pass; for


this case
Enter password:

UCLA rules

Welcome Carey

getline: more details


int main(void)
{
string password;
getline(cin, password);
}

The getline command reads characters from the


keyboard until you hit the enter key and stores
those characters into your string variable.
Like our main function, getline is a function too. Its
job is to input a string of characters from the user.

getline: more details


To use the getline function, you write:
getline(cin, variablename);
int main(void)
{
string model, color;

// info about a car

getline(cin, model);
getline(cin, color);
...
}

In between the parentheses, always write cin first,


followed by a comma and then your variables name.

Inputting Both Numbers and Strings


Be careful!
int main(void)
{
int numCookies;
string cookieType;
cout << "How many cookies would you like to buy? ";
cin >> numCookies;

cin.ignore(100000, '\n'); // place before getline


cout << Which kind? ";
getline(cin, cookieType);
cout << numCookies << << cookieType << for you.;
}

Any time you use cin before using getline, you must put
a special command between the two or it wont work!

You might also like