40
Monday, Oct 11 th Questions about Project #1? Week 1 review challenge A potpourri of new topics – More about variables – New operators (+=, ++, etc.) – The if statement String variables…

UCLA cs class Lecture2 Post

Embed Size (px)

DESCRIPTION

UCLA cs class Lecture2 Post

Citation preview

Page 1: UCLA cs class Lecture2 Post

Monday, Oct 11th

• Questions about Project #1?• Week 1 review challenge• A potpourri of new topics

– More about variables– New operators (+=, ++,

etc.)– The if statement– String variables…

Page 2: UCLA cs class Lecture2 Post

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

Page 3: UCLA cs class Lecture2 Post

Review Challenge

#include <iostream>

int main(void){ int n;

std::cout << “Enter n: “; std::cin >> n;

// add your code here std::cout << ; std::cout << ; std::cout << ;

}

Given a number, n, in seconds, print out the number of hours, minutes and seconds that n represents.

Hint: Use regular division and modulo

division

E.g. if the user types in 7265, the program

should print:

Hours: 2Minutes: 1 Seconds: 5

Page 4: UCLA cs class Lecture2 Post

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…

Page 5: UCLA cs class Lecture2 Post

char variables int main(void){ char small_num; small_num = -125; // this is OK!

Last time we learned that char variables can hold numbers between -127 and

128.

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.

A char variable can also hold a symbolic

character, like a letter or a punctuation

mark.

char grade, punct;

grade = ‘A’; punct = ‘$’; cout << “Your grade is: “ << grade;}

Page 6: UCLA cs class Lecture2 Post

char variables #include <iostream> int main(void){ char grade;

cout << “Enter desired grade: “; cin >> grade;

cout << “You don’t deserve a “ << grade;

}

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.

grade ‘P’

Enter desired grade:B

‘B’

You don’t deserve a B

Page 7: UCLA cs class Lecture2 Post

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

a = b = c = 5;  

}

Assigning Multiple Variables at The Same Time

Sometimes its convenient to assign many variables to the same value at once.

This is how you do it. #include <iostream> int main(void){ int a, b, c;

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

}

And here’s how C++ treats it.

Page 8: UCLA cs class Lecture2 Post

Const VariablesWhat’s 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)?

Page 9: UCLA cs class Lecture2 Post

Const Variables

#include <iostream> int main(void){ const double PI = 3.14; double rad;

std::cout << “Enter the radius of your zit: “; std::cin >> rad;

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

}

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.

3.141592653;

You can define your constant variable at the

top of your program once and then use it

over and over.

Then you can be sure you use the exact same

value everywhere in your program.

Page 10: UCLA cs class Lecture2 Post

#include <iostream> int main(void){

const int numHumanLegs = 2;

numHumanLegs = 10; // syntax error!

}

Const Variables

Once a variable is defined as const, it’s value can’t be changed. Also, you must set the value of a const variable when it is defined.

const float gallonsOfPhlegm; // syntax error!= 365; // OK!

Page 11: UCLA cs class Lecture2 Post

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

int main(void){ int a;

a = 5;a = a + 10;a = a * 3;a = a / 4;a = a % 2;

std::cout << a;}

After:

int main(void){ int 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.

a -885

a = 5 + 10;

15

a = 15 * 3;

45

a = 45 / 4;

11

a = 11 % 2;

1

Page 12: UCLA cs class Lecture2 Post

New Operators: ++ and --

int main(void){ int a = 5;

a = a – 1;

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

int main(void){ int a = 5;

a--; // OR --a;

int b = 6; b++; // OR ++b;}

The ++ and -- operators allow you to quickly increment and decrement variables by one.

But there’s a catch!!!

Page 13: UCLA cs class Lecture2 Post

++ and -- Specifics

int main(void){ int a = 5; ++a; // this is just fine ++(a+5); // SYNTAX ERROR! 7--; // SYNTAX ERROR!}

You may only use the ++ and -- operators with variables. Not with expressions or

numbers.

Page 14: UCLA cs class Lecture2 Post

// Let’s learn the IF statement#include <iostream> 

int main(void){ int passcode; 

cout << "Enter password: "; std::cin >> passcode; 

if (passcode == 9939) std::cout << "Password accepted.\n"; 

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

Note: No semicolon!

The if StatementThe if statement is used to make decisions in

your C++ programs.

passcode

91

Enter password: 12341234

“If the the passcode is equal to 9939 then do the next

line.Is 1234 equal to 9939?

“If the the passcode is not equal to 9939

then do the next line.Is 1234 not equal to 9939? Invalid password.

Page 15: UCLA cs class Lecture2 Post

Introducing the if StatementThe if statement is used to test whether or not an

expression is true or false. 

if ( expression )do this statement;

 The program runs the statement before the next

semicolon only if the expression is true.  

a > b “a greater than b”;

a == b “a has the same value as b”;a != b “a has a different value than b”;a >= b “a is greater than or equal to b”;

If this is true…

Then run the command before the semicolon.

Here are some sample expressions:

 

if ( )

cout <<

Page 16: UCLA cs class Lecture2 Post

The if Statement

  if ( expression )

do this statement; else

do this statement; 

Let’s learn how to use more advanced forms of the if statement…

Form #1 #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!”;}

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

C++ runs the second statement.

Page 17: UCLA cs class Lecture2 Post

The if Statement

  if ( expression )

do this statement; else if ( expression2 )

do this statement;

Let’s learn how to use more advanced forms of the if statement…

Form #2#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.”;}

else do this statement; 

  else if ( expression3 )

do this statement; else if ( expression4 )

do this statement;

Page 18: UCLA cs class Lecture2 Post

The if StatementAs 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;

if (score >= 90) cout << “You got an A, good job!\n”; else if (score >= 80) cout << “You got a B, not bad.\n”; else if (score >= 70) cout << “You got a C, you slacker!\n”; else cout << “You must be taking Dr. Smallberg’s class.\n”;

cout << “Now go study some more!\n”;}

score 80

80 >= 90???

80 >= 80???

skip

skip

You got a B, not bad!Now go study some more!

Page 19: UCLA cs class Lecture2 Post

The if Statement

  if ( expression )

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

#include <iostream>using namespace std; 

int main(void){ int hairs; 

cout << "Enter hairs: "; cin >> hairs;

if (hairs < 100) { cout << “You’re balding.."; cout << “You must be Carey”; }

cout << “Have a nice day.”;}

else do this statement; 

  do this statement;{

}

  do this statement too;

do this statement; 

{

}

  also do this;  and this too;

This is called a “block.”

Page 20: UCLA cs class Lecture2 Post

The if Statement

  if ( expression )

You can also define new variables within any block in

your program.int main(void){ int hairs; 

cout << "Enter hairs: "; cin >> hairs;

if (hairs > 100) { int real_hairs;

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

{ do this statement;

} do this statement too;int foo, bar;float bletch = 16;

hairs -18

Enter hairs:250250

250 > 100??

real_hairs 177

250/2

125

Liar, you have 125

When a block exits, all of its variables

disappear!

Have a nice day

Page 21: UCLA cs class Lecture2 Post

int main(void){ int iq;  std::cout << "Enter your IQ: "; std::cin >> iq;  if (iq > 100) std::cout << “That’s pimp!\n"; std::cout << “You’re smart!\n";} 

Be Careful With The if StatementWhats wrong with it?

iq

-4731

Enter your IQ:31You’re smart!

How do we fix it?

{

}

31 > 100???

Ignore next statement!

Page 22: UCLA cs class Lecture2 Post

int main(void){ int iq;

std::cout <<"Enter IQ:"; std::cin >> iq;

if (iq < 100) ; std::cout << “USC student";}

Whats wrong with it?

You’re not supposed to have a ; here

Be Careful With The if Statement

If you put a semicolon after an if statement, this is what the compiler thinks you mean…

int main(void){ int iq;

std::cout <<"Enter IQ:"; std::cin >> iq;

if (iq < 100) do-nothing-here; std::cout << “USC student";}

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.

Page 23: UCLA cs class Lecture2 Post

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

std::cout << “Barely buzzed.\n”;}

A. 2 beers

B. 7 beers

C. 18 beers

What will this program print if I drink…

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

X

X

 int main(){

int num_beers;std::cin >> num_beers;if (num_beers > 3) if (num_beers < 15)

std::cout << “Drunk but alive\n”; else

std::cout << “Barely buzzed.\n”;}

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

else std::cout << “Barely buzzed.\n”;

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

Page 24: UCLA cs class Lecture2 Post

The if StatementSometimes you will see C++ programmers place an

arithmetic expression in between the parentheses of an if statement.

 int main(){ 

int a = 5, b = 4;

if ((a – b)*3)std::cout<< “Will it print this\n”;

else std::cout << “or this?\n”;}If the expression’s value is not equal to zero, then the program runs the next statement as if the expression were true.

a

5 b

4(5-4)*33

Page 25: UCLA cs class Lecture2 Post

The if StatementSometimes you will see C++ programmers place an

arithmetic expression in between the parentheses of an if statement.

 int main(){ 

int a = 5, b = 5;

if ((a – b)*3)std::cout<< “Will it print this\n”;

else std::cout << “or this?\n”;}

a

5 b

5(5-5)*30

If the expression’s value is equal to zero, then the program runs the else statement as if the expression were false.

Page 26: UCLA cs class Lecture2 Post

 #include <iostream> using namespace std;  int main(void){ int iq;  cout << "Enter your IQ: "; cin >> iq;  if (iq = 50) cout << "You belong at USC.\n";  cout << "Your IQ: " << iq << "\n";  }

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

iq

981

Enter your IQ: 179

17950

You belong at USC. Your IQ: 50

Be Careful With If Statements!

Page 27: UCLA cs class Lecture2 Post

#include <iostream> using namespace std;  int main(void){ char firstLetter;  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 example with if and char

Note: ‘A’ is less than ‘B’ and ‘B’ is less than ‘C’, etc.

Also – ‘a’ is not equal to ‘A’.Chars are case sensitive!

Page 28: UCLA cs class Lecture2 Post

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”;…

int main(void){ int score; cin >> score; if (score == 0) cout << “Oh dear!\n”;…

Instead of…

Page 29: UCLA cs class Lecture2 Post

An Interesting Idea

Answer: To prevent bugs like the following:

int main(void){ int score; cin >> score; if (score = 0) cout << “Oh dear!\n”;…

Page 30: UCLA cs class Lecture2 Post

An Interesting Idea

Let’s see how it works!

int main(void){ int score; cin >> score; if (0 == score) cout << “Oh dear!\n”;…

int main(void){ int score; 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.

Syntax error!

Page 31: UCLA cs class Lecture2 Post

C++ Strings

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;

So far, we’ve learned how to define integer and floating-point variables.

C++ also lets us define string variables.

Instead of holding numbers like int or double, string variables holds a string of characters.

Page 32: UCLA cs class Lecture2 Post

#include <iostream>#include <string> using namespace std;  int main(void){ string myname; myname = “Carey”;

cout << “Hello, “ << myname;}

C++ StringsYou can define a new

string variable just like you define any other

C++ variable.

You must use double quotation marks “ and “ when you assign

a string variable to a string value.

Unlike normal variables, string

variables always start out empty when you

define them,

mynam

e“ ”“Carey”

Hello, Carey

Page 33: UCLA cs class Lecture2 Post

#include <iostream>#include <string> using namespace std;  int main(void){ string myname; cout << “Name? “; cin >> myname;

cout << “Hello “ << myname; }

C++ StringsYou can input a string

from the user using the standard cin >>

command.BUT cin will only allow you to type in a single

word at a time.

If you type in more than one word, only the first word will be stored in your variable.

myname

Name?Alan Wang

“Alan”

Hello Alan

Page 34: UCLA cs class Lecture2 Post

#include <iostream>#include <string> using namespace std;  int main(void){ string myname; cout << “Name? “; cin >> myname; if (myname == “Carey”) cout << “You stud!\n”; else cout << “You slacker!\n”;}

C++ StringsYou can use the

comparison operators on strings as well.

As with char variables, comparisons are case

sensitive.

Name?CAREY

myname

You slacker!

“CAREY”

Page 35: UCLA cs class Lecture2 Post

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

C++ Strings< <= > and >= comparisons are done

lexicographically.

“Alan” comes before “Aron”. “Aron” comes before “Ben”, etc…

“Zooplankton” comes before “aardvark”

(lowercase letters come after uppercase

letters)

Page 36: UCLA cs class Lecture2 Post

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

msg1 = msg1 + “ Bruins”; cout << msg1 << “\n”;

msg1 += “!!!”; cout << msg1 << “\n”;}

Concatenating C++ Strings

You can use + or += to concatenate

one string onto another string.

msg1 “Go” “Go Bruins”” + “

Go Bruins

! ! !”Go Bruins!!!

Page 37: UCLA cs class Lecture2 Post

Inputting Multi-word Strings

#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 << “You’re not Carey“;}

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

the getline function.

Don’t use cin >> pass; for this case…

pass

Enter password:

UCLA rules

“UCLA rules”

Welcome Carey

Page 38: UCLA cs class Lecture2 Post

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

getline: more details

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. It’s job is to input a string of characters from the

user.

Page 39: UCLA cs class Lecture2 Post

getline: more detailsTo use the getline function, you write:

getline(cin, variablename);

In between the parentheses, always write cin first, followed by a comma and then your

variable’s name.

int main(void){ string model, color; // info about a car getline(cin, model); getline(cin, color); ...}

Page 40: UCLA cs class Lecture2 Post

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;

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

won’t work!

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