5.lec5 Cin If Else
5.lec5 Cin If Else
and
conditional execution
1
Console Input (cin)
8 interactive program: Reads input from the console.
– While the program runs, it asks the user to type input.
– The input typed by the user is stored in variables in the code.
2
cin
– Each method waits until the user presses Enter.
– The value typed by the user is returned.
int age;
cout << "How old are you? "; // prompt
cin >> age;
cout << “You typed " << age;
3
cin example
void main()
{
cout<<"How old are you? "; age 29
cin >>age;
years 36
int years = 65 - age;
cout << years << " years until retirement!";
}
8 Console (user input underlined):
How old are you?
36 years until retirement!
29
4
cin example 2
8 The cin can read multiple values from one
line
void main()
{
int num1, num2
cout << "Please type two numbers: ";
cin >> num1 >> num2;
int product = num1 * num2;
cout << “The product is " << product;
}
A. 2 B. 6 C. 7
D. 8 E. 9
6
input tokens
8 When a token is the wrong type, the
program crashes. (runtime error)
int age;
cout << “What is your age ? ";
cin >> age
Output:
What is your age? Timmy
Error
7
The if/else statement
reading:
8
The if statement
Executes a block of statements only if a test is true
if (test) {
statement;
...
statement;
}
8 Example:
double gpa;
cin >> gpa;
if (gpa >= 2.0){
Scout<<"Application accepted.";
}
9
The if/else statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
8 Example:
double gpa;
if (gpa >= 2.0) {
cout<<"Welcome to Mars University!";
}
else {
cout<<"Application denied.";} 10
Relational expressions
8 if statements and for loops both use logical tests.
8 "Truth! tables"not
for each, used with logical
!(2 == 3) true
values p and q:
p !p
p q p && q p || q
true false
true true true true
fals true
true fals false true e
e
fals true false true 12
e
Nested if/else
Chooses between outcomes using many tests
if (test) {
statement(s);
} else if (test) {
statement(s);
} else {
statement(s);
}
8 Example:
if (x > 0) {
cout<<"Positive";
}
else if (x < 0) {
cout<<"Negative";
}
else {
cout<<"Zero";
} 13
Exercises
8 Write a method that prints out if it is good
weather to go for a bike ride. The weather is
good if the temperature is between 40
degrees and 100 degrees inclusive unless it
is raining, in which case the temperature
must be between 70 degrees and 110
degrees inclusive
8 Write a method that returns the largest of
three numbers using if statements
8 Write a method that determines if one day is
before another day (given month and day) 14
Exercise
8 Prompt the user to enter two people's heights in
inches.
– Each person should be classified as one of the following:
• short (under 5'3")
• medium (5'3" to 5'11")
• tall (6' or over)
17