C++ Workshop - Week 3 (Ch. 4) - Quizzes and Exercises

This topic is 3744 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Quizzes and Extra Credit for Week 3.

Post your answers to the Quizzes from Week 3 here rather than in the chapter thread, so as not to spoil things for the others.
Chapter 4 Quiz 1. What do statements do in C++? 2. Where can you put a compound statement? 3. What’s another name for a compound statement? 4. What syntax identifies the beginning and ending of a block? 5. What is an expression in C++? 6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side? 7. What do operators act upon? 8. Can an expression be acted upon by operators? 9. What does the assignment operator do? 10. What is an r-value and an l-value? How does this relate to question 6 above? 11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs. 12. What happens when you subtract a large unsigned number for a smaller unsigned number? 13. [Extra Credit]What is integer truncation? How can it be avoided? 14. What are the increment/decrement operators, and how are they used. Show examples. 15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples. 16. What is the precedence of the mathematical operators? 17. Are the operators left-to-right or right-to-left? 18. What about the assignment operator? 19. What operator can ALWAYS be used to change the precedence of an expression? 20. How are nested parentheses read? Show examples. 21. Can all expressions be evaluated for their truth? 22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert) 23. What is the ANSI standard size of that data type? 24. What are the six relational operators? Show examples of what values they return with different inputs. 25. What does an ‘if’ statement do? 26. When is an if-block executed, when is it skipped? 27. What does an ‘else’ statement do? 28. When is an else-block executed, when is it skipped? 29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped? 30. What are the 3 logic operators in C++? How are they used? Show examples. 31. What is “Short Circuit Evaluation?” How might it be beneficial? 32. What is the precedence of the logical and conditional operators? 33. What is the conditional operator? How is it used? When might it be useful? Show examples. Chapter 4 Exercises 1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen. 2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.

Share on other sites
1. What do statements do in C++?
Controls the sequence of execution, evaluates and expression, or does nothing.

2. Where can you put a compound statement?
Anywhere you can put a statement.

3. What’s another name for a compound statement?
Block

4. What syntax identifies the beginning and ending of a block?
‘{‘ & ‘}’

5. What is an expression in C++?
Anything that evaluates to a value.

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
Right side, the left side is where the expression is assigned.

7. What do operators act upon?
Operands

8. Can an expression be acted upon by operators?
Yes, any expression can be an operand.

9. What does the assignment operator do?
Changes the value on the left side of the operator

10. What is an r-value and an l-value? How does this relate to question 6 above?
L-left side, r-right side. Determines some of the characteristics of the value (5 can only be an r-value)

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
Addition (+), subtraction (-), multiply (*), divide (/), modulus – int remainder (%). 1+2*2-3/3=5. (wrong =4)

12. What happens when you subtract a large unsigned number for a smaller unsigned number?
Takes the difference from the highest available value.

13. [Extra Credit]What is integer truncation? How can it be avoided?
Non-integer quotients are shortened to their integer values. Using floating point values instead of int.

14. What are the increment/decrement operators, and how are they used. Show examples.
(++) and (--) are used to increase or decrease the value by 1. x++ adds one to the value of x and stores that new value in x.

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
Prefix increments/decrements prior to assignment, postfix assigns after increment/decrement. int y = ++x (y=x+1), int y = x++ (y=x)

16. What is the precedence of the mathematical operators?
*, ?, % before +, -

17. Are the operators left-to-right or right-to-left?
Left to right

18. What about the assignment operator?
Right to left

19. What operator can ALWAYS be used to change the precedence of an expression?
Parentheses

20. How are nested parentheses read? Show examples. I
nnermost contained operators are read first. (3 * 4 + (3 - 2) – 1), the (3 – 2) is performed first.

21. Can all expressions be evaluated for their truth?
But what is the nature of truth…….yes

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
bool

23. What is the ANSI standard size of that data type?
1 byte

24. What are the six relational operators? Show examples of what values they return with different inputs.
1 == 1 (true), 1 != 1 (false), 1 > 1 (false), 1 >= 1 (true), 1 < 1 (false), 1<=1 (true).

25. What does an ‘if’ statement do?
It allows you to test for a condition.

26. When is an if-block executed, when is it skipped?
It is executed if the relation expression it is based upon is true; it is not executed when false.

27. What does an ‘else’ statement do?
Executes a block of code when the condition on which the if statement is based is false.

28. When is an else-block executed, when is it skipped?
When the condition evaluates to true.

29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped?
It allows you to check for another condition when the first evaluates to false.

30. What are the 3 logic operators in C++? How are they used? Show examples.
AND &&, OR ||, NOT ! if ((x == 1) && (y == 7)) evaluates true if both conditions are true. if ((x == 1) || (y == 7)) evaluates true if either is true. if ( !(x==1)) evaluates true of the condition evaluates false.

31. What is “Short Circuit Evaluation?” How might it be beneficial?
If the condition has already been determined, there is no need to evaluate additional conditions, this can save time in execution.

32. What is the precedence of the logical and conditional operators?
&& then || then ?:

33. What is the conditional operator? How is it used? When might it be useful? Show examples.
?:, like a mini if, else statement. Would be useful for a small conditional statement. x = (x < 10) ? ++x : 1;

Chapter 4 Exercises

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.
#include <iostream>int main(){	int rate, time;	std::cout << "Please insert rate: ";	std::cin >> rate;	std::cout << "Please insert your time: ";	std::cin >> time;	std::cout << "The distance traveled is: " << rate * time << std::endl;	return 0;}

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.
#include <iostream>int main(){	int guess, x=5 ;	std::cout << "Please enter your guess: ";	std::cin >> guess;	if (guess == x)	{		std::cout << "You are right!\n";	}	else if (guess < x)	{		std::cout << "Too low.\n";	}	else	{		std::cout << "Too high\n";	}	return 0;}

[Edited by - Gambler on June 24, 2006 4:47:15 PM]

Share on other sites
Quote:
 11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs. Addition (+), subtraction (-), multiply (*), divide (/), modulus – int remainder (%). 1+2*2-3/3=5.

Looks like someone forgot about operator precedence.

That expression evalutes to 4 :
1 + 2 * 2 - 3 / 3(equivelant) 1 + ( 2 * 2 ) - ( 3 / 3 )1 + 4 - 14

I'm not trying to be pedantic, but this kind of mistake can be really hard to track down in code, as the compiler cannot help you. Whether you intended the value to be 4, or 5, it does not know.

Share on other sites
Dang it - I knew better than that - thanks for the callout

Quizzes and Extra Credit for Week 3.

Chapter 4 Quiz

1. What do statements do in C++?
controls the sequence of execution, evaluates and expression, or does nothing (the null statement)

2. Where can you put a compound statement?
Any place that we can put statement

3. What’s another name for a compound statement?
 a block

4. What syntax identifies the beginning and ending of a block?
opening brace ({) identify the beginningclosing brase (}) identify the ending

5. What is an expression in C++?
 Expression in C++ can be defined as any statemet that return a value

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
The right side of an assignment operator

7. What do operators act upon?
Operators act on operand

8. Can an expression be acted upon by operators?
can

9. What does the assignment operator do?
The assignment operator (=) causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator

10. What is an r-value and an l-value? How does this relate to question 6 above?
r-value is an operand that can be on the left side of an assignment operatorl-value is an operand that can be on the right side of an assignment operatorThe relation : the lvalue is assigned to the rvalue value.

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
addition (+), subtraction (-), multiplication {*), division (/), and modulus (%)example of addition  a= 4+6                     a= 10example of subtraction b = 5-3                        b = 2example of multiplication c = 3*3                          c = 9example of division d = 6/2                    d = 3example of modulus e = 20%2                   e = 0

12. What happens when you subtract a large unsigned number for a smaller unsigned number?
 overflow

13. [Extra Credit]What is integer truncation? How can it be avoided?
The floating value on the integer was truncated, it can be avoided by assigned the integer into double or float data type

14. What are the increment/decrement operators, and how are they used. Show examples.
increment is increases the value of the variable by 1, decrement is decreases the value of the variable by 1The can be used by using "++" or "--"For example: we want to increment variable d, then we just write d++ on our coding

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
Prefix : Increment the value and then fetch it, Postfix : Fetch the value and then increment the original value.For example int a = 21;            int b = a++            int c = ++athen the result is a = 23, b=21, c = 23;

16. What is the precedence of the mathematical operators?
 modulus (%), division (/), multiplication (*), subtracti0n (-), and at las t addition (+).

17. Are the operators left-to-right or right-to-left?
left to right

18. What about the assignment operator?
Right to left

19. What operator can ALWAYS be used to change the precedence of an expression?
parentheses

20. How are nested parentheses read? Show examples.
Read from the inside out.for example : ((a+b)*c)              (a+b) is executed first, and then times with c

21. Can all expressions be evaluated for their truth?
can

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
bool

23. What is the ANSI standard size of that data type?
1 byte

24. What are the six relational operators? Show examples of what values they return with different inputs.
equals (==}, not equals (!=}, Greater than (>), Greater than or equals {>=}, less than (<}, less than or equals (<=)...for example   3==3 is true, 3>2 is true, 3>4 ia false, 3<2 is true, 3<5 is false.

25. What does an ‘if’ statement do?
the if statement enable us to test for a condition (such as whether two variable are equal) and branch to different parts of your code, depending on the result.

26. When is an if-block executed, when is it skipped?
 The if-block executed when expression is true, and it's skipped when the expression is false

27. What does an ‘else’ statement do?
To executed another statement if the condition is false

28. When is an else-block executed, when is it skipped?
an else block executed when expression is false, and it's skipped when the expression is true

29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped?
 the else if statement is the statement that will b executed if the 'if' condition is false, it was skipped if the "if" condition is true.

30. What are the 3 logic operators in C++? How are they used? Show examples.
Logical AND (&&), Logical OR (||), Logical Not (!)

31. What is “Short Circuit Evaluation?” How might it be beneficial?
The situation where the compiler only evaluate the first statement, and if it is determined, whether false or true, the compiler will not determined the next statement.The beneficial is the compiler will be more efficiency

32. What is the precedence of the logical and conditional operators?
NOT(!), AND (&&), OR(||)

33. What is the conditional operator? How is it used? When might it be useful? Show examples.
 conditional operator is the only operator that take three term(expression1) ? (expression2) : (expression3)For example: (3>1)?A:B will be return statement A because (3>1) is true

Chapter 4 Exercise

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.

#include <iostream>using namespace std;int main(){    int dist, rate, time;        cout << "Enter the rate of movement: " ;    cin >> rate;        cout << "Enter the time: ";    cin >> time;        dist = rate * time;        cout << "The distance is " << dist << endl;        return 0;    }

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.

#include<iostream>using namespace std;int main(){    int input, secret = 8;        cout << "Enter your choosen number: " ;    cin >> input;        if(input != secret){        if(input > secret)            cout << "To High" << endl;        else            cout << "To Low" << endl;    }else        cout << "Just Right" << endl;           return 0;}

Share on other sites
Chapter 4 Quiz

1. What do statements do in C++?
They can control the sequence of operations, evauluate an expression, or do nothing.

2. Where can you put a compound statement?
Any place you can put a single statement.

3. What’s another name for a compound statement?
A block.

4. What syntax identifies the beginning and ending of a block?
{}

5. What is an expression in C++?
Anything that evaulates a value.

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
The right side. Constants cannot have their values changes, thus cannot be on the left side of an equation.

7. What do operators act upon?
Operands.

8. Can an expression be acted upon by operators?
Yes.

9. What does the assignment operator do?
Assigns a value to a variable.

10. What is an r-value and an l-value? How does this relate to question 6 above?
Values that can be on the right side and left side of the assignment operator, respectively. Constants can only be r-values.

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
x = 1 + 2;
returns the value 3 to x

-, subtracts values from one another
x = 2 - 1;
returns the value 1 to x

*, multiplies values
x = 2 * 2;
returns the value 4 to x

/, divides values
x = 5 / 2;
returns the value 2 to x

%, called modulus, returns the division remainder of two values
x = 5 % 2;
returns the value 1 to x

12. What happens when you subtract a large unsigned number for a smaller unsigned number?
It wraps around to the largest unsigned value that variable can hold, very bad.

13. [Extra Credit]What is integer truncation? How can it be avoided?
Not 100% sure - this is when a real number is plugged into a variable of int type, and is then truncated, IE 5.2 becomes 5. This can be avoid by simply assigning the proper variable types to variables in your program? I have a feeling I'm missing something here...

14. What are the increment/decrement operators, and how are they used. Show examples.
++
x++ or x += 1
increments x by 1

--
x-- or x -= 1
decrements x by 1

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
Prefix increments your variable before performing whatever operation you're doing, postfix increments it after.
So:
a = b++
assigns b to a, and then increments it.

a = ++b
increments b, then assigns b to a.

16. What is the precedence of the mathematical operators?
%, * and / first, from left to right, and then + and - from left to right.

17. Are the operators left-to-right or right-to-left?
Left to right.

18. What about the assignment operator?
The right most assignment operator is always evaluated first.

19. What operator can ALWAYS be used to change the precedence of an expression?
Parentheses.

20. How are nested parentheses read? Show examples.
From the inside out. So:
x = ((a + b) * c)
and a = 1, b = 2 and c = 3, a + b is evaluated first (3) and then multiple by c, thus assigning 9 to x.

21. Can all expressions be evaluated for their truth?
Yes.

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
bool.

23. What is the ANSI standard size of that data type?
1 byte.

24. What are the six relational operators? Show examples of what values they return with different inputs.

if a = 1 and b = 2...
a == b evaluates false
a != b evaluates true
a > b evaluates false
a >= b evaluates false
a < b evaluates true
a <= b evaluates true

if a = 2 and b = 2...
a == b evaluates true
a != b evaluates false
a > b evaluates false
a >= b evaluates true
a < b evaluates false
a <= b evaluates true

25. What does an ‘if’ statement do?
It tests for a condition and allows you to execute certain blocks of code depending on the result.

26. When is an if-block executed, when is it skipped?
It is executed if the 'if' expression is evaluated as true, otherwise it is skipped.

27. What does an ‘else’ statement do?
It executes a block of code if initial 'if' expression is not true.

28. When is an else-block executed, when is it skipped?
It is only executed when the initial 'if' expression isn't true, otherwise it is skipped.

29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped?
I *think*, this is basically just an embedded if statement in and else statement? It is executed if expression a was false but expression b was true.

30. What are the 3 logic operators in C++? How are they used? Show examples.
&& (AND), || (OR) and ! (NOT). So, if x is 5 and y is 5:

((x == 5) && (y == 5)) evaluates true
((x == 5) || (y == 4)) evaluates true
(!(x == 5)) evaluates false

31. What is “Short Circuit Evaluation?” How might it be beneficial?
For example, if the first part of an && expression is false, C++ won't bother to check the second half, since it's evaluation is meaningless at this point. This results in faster run times (I would imagine?)

32. What is the precedence of the logical and conditional operators?
&& then || then ?: from left to right.

33. What is the conditional operator? How is it used? When might it be useful? Show examples.
z = (x > y) ? x : y;
This states if x is greater than y, assign x to z, otherwise, assign y to z. It is basically a shorter, simpler if else statement.

Chapter 4 Exercises

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.

#include <iostream>int main(){	using namespace std;	int dist, rate, time;	cout << "Enter the rate of movement:" << endl;	cin >> rate;	cout << endl << "Enter the amount of time traveled:" << endl;	cin >> time;	dist = rate * time;	cout << endl<< "The distance traveled is: " << dist << endl;	return 0;}

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.

#include <iostream>int main(){	using namespace std;	int secret = 33; //this number is secret and can be changed	int guess;	cout << "I know a secret number! Try to guess it:" << endl;	cin >> guess;	if (guess > secret)		cout << endl << "Your guess was too big, sorry." << endl;		if (guess < secret)		cout << endl << "Your guess was too small, sorry." << endl;	if (guess == secret)		cout << endl << "You are so smrt! You guessed the number correctly." << endl;	return 0;}

Share on other sites

1. What do statements do in C++?
1a. C++ statements control the sequence of execution, evaluate expressions, or do nothing at all.

2. Where can you put a compound statement?
2a. Any place you can put a single statement.

3. What’s another name for a compound statement?
3a. A block.

4. What syntax identifies the beginning and ending of a block?
4a. The curly braces. { and }.

5. What is an expression in C++?
5a. Anything that evaluates to a value.

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
6a. The RIGHT side. The other side if for l-values only, or rather specific addresses for storing values. You can’t store a value IN an expression.

7. What do operators act upon?
7a. Operands.

8. Can an expression be acted upon by operators?
8a. Yes. Any expression can be used as an operand of an operator.

9. What does the assignment operator do?
9a. Changes the value of the left operand (left side of operator) to match the value of the expression on the right operand (right side of operator).

10. What is an r-value and an l-value? How does this relate to question 6 above?
10a. A operand that can legally on the left side of an operator is an l-value. That which can be on the right side in an r-value. All l-values are also r-value, but the reverse is not true. An expression is an r-value, which is why it cannot go on the left side.

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
11a. Addition (+), Subtraction (-), Multiplication (*), Division (/), and modulus (%). A = 2+2; B = 2-2; C = 2*2; D=2/2; E=2%3;

12. What happens when you subtract a large unsigned number for a smaller unsigned number?
12a.You get underflow, which results in a value which is a very large number.

13. [Extra Credit]What is integer truncation? How can it be avoided?
13a. Integer truncation is what happens when a real number with a fractional value is stored in an integer variable. To be more specific, the fractional component is “lopped off,” in essence rounding down to the nearest whole number. For example: int myValue = 2.2; would result in myValue being 2. Note that sometimes this problem can be less obvious. In the example I provided before we were explicitly using fractional values, but keep in mind the problem can occur when using entirely integers as well. For example…what’s 2/3? .66666…. But when you divide 2/3 and store it in an integer variable, the result is ‘truncated’ to 0. int myValue = 2/3; [myValue := 0] The solution is to be aware of your data, and have a clear understanding of the types of results to expect within your expressions. If there is a chance that an expression will have a fractional component and you NEED that fractional component, store your results in ‘float’ or ‘double’ types, rather than integer types.

14. What are the increment/decrement operators, and how are they used. Show examples.
14a. ++ and --. They are used to take a variable, increment or decrements its value and store the result back in the same variable. This is most commonly used in iterative devices such as for loops or while loops. Example:
for( int i = 0; i < 10; i++ ){    // use i as an index into an array, etc…}

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
15a. With prefix the value of the variable is changed before the assignment operator is applied. With postfix the value of the variable is changed after evaluation of the assignment operator.
Example:

// In this example I is set to 10, then the value of I is stored in j, and finally the value stored in I is incremented.
int i = 10;
int j = i++;

// In this example, I is set to 10, then it’s incremented to 11, and finally the result is stored in j
int j = ++i;

16. What is the precedence of the mathematical operators?
16a. %, * and / are evaluated first, in order from left to right…. and then + and -, again from left to right.

17. Are the operators left-to-right or right-to-left?
17a. Left to right

18. What about the assignment operator?
18a. Right to left

19. What operator can ALWAYS be used to change the precedence of an expression?
19a. The parentheses

20. How are nested parentheses read? Show examples.
20a. From the inside out. 2 * ( 5 – (2 + 2 ) ) ; Here the 2 + 2 is evaluated first, even though its lowest in precedence, and is on the right side of the expression. Next the 5- is evaluated, and finally the 2*. So as you can see by using parentheses you can change both the precedence and the left to right order of the expression.

21. Can all expressions be evaluated for their truth?
21a. Yes. All expressions return a value, and the result of that value can be tested for zero or non-zero. 0 is treated as false, non-zero is treated as true.

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
22a. bool.

23. What is the ANSI standard size of that data type?
23a. 1 byte.

24. What are the six relational operators? Show examples of what values they return with different inputs.
24a. equals (==), not equals (!=), Greater than (>), Greater than or equal to (>=), Less than (<), Less than or equal to (<=).
1 == 1; // true
1 == 2; // false

1 != 2; // true
1 != 1; // false

3 > 2; // true
3 > 3; // false

2 >= 2; // true
2 >= 3; false

3 < 5; // true
3 < 3; // false

3 <= 3; // true
3 <= 2; false

25. What does an ‘if’ statement do?
25a. It enables you to test for a condition, and then branch to different parts of your code, depending on the success or failure of the test.

26. When is an if-block executed, when is it skipped?
26a. It is executed when the test for the condition passes (is true). It is skipped when the test is false.

27. What does an ‘else’ statement do?
27a. It allows you to enter a block of code if a test condition fails.

28. When is an else-block executed, when is it skipped?
28a. It is executed when no previous test in the same if-else chain succeeds. It is never skipped. If it is ‘reached,’ it is executed.

29. [Extra Credit] What does an ‘else if’ statement do? When is executed and when is it skipped?
29a. An if-else statement combines the functionality of an if and an else statement. That is, IF some condition is met, then the block will be executed; ONLY, when no previous condition within an if-else chain has already been met. Unlike the “else” statement, an ‘if else’ statement will be skipped if the condition being tested for is not true.

30. What are the 3 logic operators in C++? How are they used? Show examples.
30a. AND (&&), OR (||), NOT (!).
&& is used to determine the union of multiple expressions. If both operands of a && are true, the result is true. If either operand is false, the result if false.
|| is used to determine the junction of multiple expressions. If either operand of || is true, the result is true. If BOTH operands are false, the result is false.
! is used to negate the value of an expression. If the operand is true, the result is false. If the operand is false, the result is true.

31. What is “Short Circuit Evaluation?” How might it be beneficial?
31a. Short circuit evaluation is a logical optimization put in place by the compiler which prevents compound expressions from being further evaluated once the result is known. For example…with AND (&&) statements, the result is true only if BOTH operands are true. So as soon as you know one is false, there is no reason to test the result of the second, because the total result of the compound expressions is already false. Likewise with OR (||) statements. If the first operand is evaluated to be true, there is no reason to test the value of the second operand, the value of the compound expressions is decidedly true.

32. What is the precedence of the logical and conditional operators?
32a. !, then &&, then ||…from left to right.

33. What is the conditional operator? How is it used? When might it be useful? Show examples.
33a. The conditional operator, also called the ternary operator as it is the only C++ operator with 3 inputs, tests the result of a logical expression. If the value is true, the result is the same as the second operand. If the result was false, the value returned is the same as the 3rd operand.

Chapter 4 Exercises

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.
#include <iostream>int main( void ){	using namespace std;	int dist, rate, time;	cout << "Enter the rate of movement:" << endl;	cin >> rate;	cout << endl << "Enter the amount of time traveled:" << endl;	cin >> time;	dist = rate * time;	cout << "The distance traveled is: " << dist << endl;	return 0;}

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.
#include <iostream>int main( void ){	using namespace std;	int number = 50;	int guess;	cout << "Enter your guess:" << endl;	cin >> guess;	if( guess > secret )		cout << "Sorry, your guess was too high." << endl;		if( guess < secret )		cout << "Sorry, Your guess was too low." << endl;	if( guess == number )		cout << "You guessed juuust right! << endl;	return 0;}

Share on other sites
Chapter 4 Quiz

1. What do statements do in C++?
Control the sequence of execution, evaluates an expression, or null.

2. Where can you put a compound statement?
Any place you can put a single statment.

3. What’s another name for a compound statement?
Block

4. What syntax identifies the beginning and ending of a block?
{ }

5. What is an expression in C++?
Anything that evaluates to a value.

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
Right side, the other side is the lvalue, the memory address(es) for storing values.

7. What do operators act upon?
Operands

8. Can an expression be acted upon by operators?
Yes.

9. What does the assignment operator do?
Changed the value of the left operand (lvalue) to equal the expression/value on the right side (rvalue)

10. What is an r-value and an l-value? How does this relate to question 6 above?
right operand, left operand. Expressions can not be on the lvalue, values can be on either side, one defining the other.

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
+ - * / %
Ex. x = (4+4)*(3-2)/2 x = 4
Ex. x = 4+4*3-2/2 x = 15
Ex. x = 8 % 3 x = 2 (remainder)
12. What happens when you subtract a large unsigned number for a smaller unsigned number?
Underflow

13. [Extra Credit]What is integer truncation? How can it be avoided?
When an expressions value is a decimal float, but the value is stored in an integer it will round down.

14. What are the increment/decrement operators, and how are they used. Show examples.
++ --
c = 1;
c++;
c == 2;

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples. Prefix - Increment the value then fetch it.
Postfix - Fetch it then increment the original value.
int c = 3, x;
x = c++;
x == 3, c == 4;

int c = 3, x;
x = ++c;
x == 4, c == 4;

16. What is the precedence of the mathematical operators?
% ^ / + -

17. Are the operators left-to-right or right-to-left?
left to right.

18. What about the assignment operator?
Right to left.

19. What operator can ALWAYS be used to change the precedence of an expression?
()

20. How are nested parentheses read? Show examples.
in to out.

21. Can all expressions be evaluated for their truth?
Yes

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
boolean

23. What is the ANSI standard size of that data type?
1 byte

24. What are the six relational operators? Show examples of what values they return with different inputs.
Equals == 52 == 52 true

Not Equals != 1002 != 967 true

Greater Than > 1103 > 501 true

Greater Than >= 102 >= 50 true
or Equals 102>= 102 true

Less Than <= 60 <= 37 false
or Equals 21 <= 21 true

25. What does an ‘if’ statement do?
The if statement enables you to test for a condition and branch to different parts of your code, depending on the result

26. When is an if-block executed, when is it skipped?
If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed.

27. What does an ‘else’ statement do?
Runs a statment if the expression is 0.

28. When is an else-block executed, when is it skipped?
If the orignal if statment returned null it will run the else, when the if statment returns bool the else statment will be skipped.

29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped? ???

30. What are the 3 logic operators in C++? How are they used? Show examples. && || !
if x=1 && y=1 (if x and y are 1 returns true) && (and)
if x=1 || y=1 (if either x or y returns 1 condition is true) || (or)
if !x=1 (if x does not equal 1 return true) ! (not)

31. What is “Short Circuit Evaluation?” How might it be beneficial?
If the first operand is evaluated to be true, it does not test the value of the second operand.

32. What is the precedence of the logical and conditional operators?
!, then &&, then ||...

33. What is the conditional operator? How is it used? When might it be useful? Show examples. Pretty much the same thing as an if statment.

(expression1) ? (expression2) : (expression3)
Read as "If expression1 is true, return the value of expression2; otherwise, return the value of expression3.

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.
#include <iostream>int main(){  float rate, time, dist;  std::cout << "Enter the rate of travel: ";  std::cin >> rate;  std::cout << "Enter the time traveled: ";  std::cin >> time;  dist = rate * time;  std::cout << "The distance traveled was: " << dist << std::endl;return 0;}

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.
#include <iostream>int main(){  int guess, secret = 28;  std::cout << "Enter a whole number and try to guess the secret number: ";  std::cin >> guess;  if (guess == secret)  {    std::cout << "Congrats!! You guess the secret number!" << std::endl;  }  else  {    if (guess < secret)      std::cout << "Try again and input a larger number." << std::endl;    else      std::cout << "Try again and input a smaller number." << std::endl;  }return 0;}

Share on other sites
Chapter 4.

1) What do statements do in C++?
A) A statement controls the sequence of execution, evaluates an expression, or does nothing (the null statement).

2) Where can you put a compound statement?
A) Any place you can put a single statement, you can put a compound statement.

3) What's another name for a compound statement?
A) A block.

4) What syntax identifies the beginning and ending of a block?
A) An opening brace " { " identifies the beginning and a closing brace " } " the end of a block.

5) What is an expression in C++?
A) An expression is anything that evaluates to a value.

6) Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
A) The right side, not on the left because expressions can be literals and literals are allways r-values.

7) What do operators act upon?
A) Operators act upon operators.

8) Can an expression be acted upon by operators?
A) Yes, it can.

9) What does the assignment operator do?
A) It assigns the r-value to the l-value.

10) What is an r-value and an l-value? How does this relate to question 6 above?
A) An operand that legally can be on the left side of an assignment operator is called an l-value. That which can be on
the right side is called an r-value. It is related towards question 6 because not every r-value can be a l-value while every l-value can be a r-value.

11) What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
A) The 5 are:
Description operator input output
Addition + 6 + 3 9
Subtraction - 6 - 3 3
Multiplication * 6 * 3 18
Division / 6 / 3 2
Modulus % 6 % 3 0

12) What happens when you subtract a large unsigned number from a smaller unsigned number?
A) Then the result will wrap around to the highest possible unsigned number.

13) What is integer truncation? How can it be avoided?
A) It cuts of the integer value and won't round of an integer, f.e. 5.4 or 5.9 will both be truncated to 5. Avoiding this can be achieved by using float or double for the variable in mind.

14) What are the increment/decrement operators, and how are they used. Show examples.
A) ++ is the increment and -- is the decrement operator, they are used as follows:
++i increment prefix
i++ increment postfix
--i decrement prefix
i-- decrement postfix

15) What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
A) Prefix increment/decrement operator is evaluated before the assignment, the postfix is evaluated after the assignment. Examples:
Performing this on an integer variable myAge which equals 38 results in the following:
myAge++; Outputs 38
++myAge; Outputs 39
myAge--; Outputs 38
--myAge; Outputs 37

15) What is the precedence of the mathematical operators?
A) Higher: multiplication, division, modulo
17) Are the operators left-to-right or right-to-left?
A) Left-to-right.

18) What about the assignment operator?
A) That is right to left.

19) What operator can ALWAYS be used to change the precedence of an expression?
A) Parentheses can always be used to accomplish this.

20) How are nested parentheses read? Show examples.
A) For the inside out, for example: (2 * (5 + 1)) = 2 * 6 = 12
3 - (4 / (6 * (2 + 4))) = 3 - (4 / (6 * 6)) = 3 - (4 / 36) = 3 - 9 = 6

21) Can all expressions be evaluated for their truth?
A) Yes.

22) What data type is exclusively for truthiness?(tip of the hat to Stephen Colbert)
A) Bool.

23) What is the ANSI standard size of that data type?
A) 1 byte (8 bits).

24) What are the six relational operators? Show examples of what values they return with different inputs.
A) < , >, <=, >=, == and !=.
Examples: 5 < 3 returns false
5 > 3 returns true
5 <= 5 returns true
5 >= 4 returns true
5 == 5 returns true
5 != 5 returns false
5 == 6 returns false
5 != 6 returns true

25) What does an if statement do?
A) It enables you to test for a condition (such as whether two variables are equal) and branch to different parts of your code, depending on the result.

26) When is an if - block executed, when is it skipped?
A) It's executed when the expression is true, it is skipped when the expression is false.

27) What does an else statement do?
A) It gives the opportunity to branch of if the if statement is false.

28) When is an else-block executed, when is it skipped?
A) It's executed when the if-block is skipped, it's skipped when the if-block is executed.

29) What does an else if statement do? When is it executed and when is it skipped?
A) An else if statement executes an additional statement, it is executed when the expression is true, and skipped when the expression is false.

30) What are the 3 logic operators in C++? How are they used? Show examples.
A) || , && , ! , are the OR, AND and NOT operators.
Examples:
if ( ( x == 5) || ( y == 5) )
if ( ( x == 5) && ( y == 5) )
if ( ! ( x == 5) )

31) What is "Short Circuit Evaluation"? How might it be beneficial?
A) The "Short Circuit Evaluation" determines whether the first (left) expression is true or false, depending on which logic operator is used, it will either check the following expression or stop depending on which logic operator was used.

32) What is the precedence of the logical and conditional operators?
A) Highest: !
High: < , <= , > , >=
Low: == , !=
Lower: &&
Lowest: | |

33) What is the conditional operator? How is it used? When might it be useful? Show examples.
A) The conditional operator takes three expressions and returns a value: (expression1) ? (expression2) : (expression3) Its read as "if expression1 is true, return the value of expression2; otherwise, return the value of expression3. It might be useful when you want to right a small inline function that only returns the value of that expression.

/*1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.*/#include <iostream>int main(){	double dist = 0.0, time, rate;	std::cout << "Enter the rate and time you traveled." << std::endl;	std::cout << "Rate equals: ";	std::cin >> rate;	if (rate < 0)	{		std::cout << "You can't have walked less then 0 km., enter the rate again please.\n";		std::cout << "Rate equals: ";		std::cin >> rate;	}	else	{		std::cout << "You walked at: " << rate << " km/hr." << std::endl;		std::cout << "Time equals: ";		std::cin >> time;		if (time < 0)		{			std::cout << "You can't have walked less then 0 hours, enter the time again please.\n";			std::cout << "Time equals: ";			std::cin >> time;		}		std::cout << "The total amount of time you walked is: " << time << " hour(s)." << std::endl;	}	dist = rate * time;	std::cout << std::endl << std::endl;	std::cout << "The total distance you walked is: " << dist << " km." << std::endl;	std::cout << "Thank you for entering your data." << std::endl;		return 0;}

/*2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.*/#include <iostream>int main(){	int secret = 8;	int guess;	std::cout << "\t\tWelcome to the guessing game!\n";	std::cout << "Please enter a number between 1 and 10: ";	std::cin >> guess;	if ( (guess < 0) || (guess > 10) )	{		std::cout << "You've entered a number below 0 or above 10" << std::endl;	}	else	{		if (guess < secret)			std::cout << "The number is smaller then the secret number!" << std::endl;		else if (guess > secret)			std::cout << "The number is bigger then the secret number!" << std::endl;		else			std::cout << "You've guessed the secret number, it is: " << secret << " ." << std::endl;	}	std::cout << "Thank you for playing this game. Goodbye!" << std::endl;		return 0;}

Share on other sites
Chapter 4 Quiz

1. What do statements do in C++?
Controls the sequence of execution

2. Where can you put a compound statement?
Any place you can put a single statement, It must be in a block which starts with an opening brace and closes with the closing brace { }

3. What’s another name for a compound statement?
Block Statement

4. What syntax identifies the beginning and ending of a block?
The opening brace {

5. What is an expression in C++?
Anything that evaluates to a value

6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
The right side

7. What do operators act upon?
operands

8. Can an expression be acted upon by operators?
Yes

9. What does the assignment operator do?
Assigns a value to a variable

10. What is an r-value and an l-value? How does this relate to question 6 above?
Right and Left, they show which side of the assignment operator something can be.

11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
addition (+) subtraction (-) multiplication (*) division (/) and modulus (%)

12. What happens when you subtract a large unsigned number for a smaller unsigned number?
The variable will reset, so like 1 - 2 would end up being 65,535.

13. [Extra Credit]What is integer truncation? How can it be avoided?
When a fraction is rounded by placing it in an enteger, like If you assign 19.39 to an integer then it will truncate, and the integer will only hold the 19.

14. What are the increment/decrement operators, and how are they used. Show examples.
Var++ or ++Var increment and Var-- or --Var will decrement.

15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
prefix, ++Var will increment the variable before doing the action it was asked to do (example: myAge = ++Var; will increment Var before assigning it to myAge and myAge = Var++; will increment Var AFTER assigning it to myAge

16. What is the precedence of the mathematical operators?
parentheses, exponents, multiplication and division, addition and subtraction

17. Are the operators left-to-right or right-to-left?
left to right, however some operators, like the assignment operator, are operated right to left.

18. What about the assignment operator?
right to left

19. What operator can ALWAYS be used to change the precedence of an expression?
parentheses

20. How are nested parentheses read? Show examples.
The data inside parentheses is completed first
((a+b)*c+(d-f)*e)*8 will complete a+b and d-f first, then it will multiply the answer of a+b with c and d-f times e. After that's done it will add the two values it just came up with then multiply that sum times 8.

21. Can all expressions be evaluated for their truth?
Yes

22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
boolean

23. What is the ANSI standard size of that data type?
one-byte holding only 2 values

24. What are the six relational operators? Show examples of what values they return with different inputs.
equals (==) not equals (!=) greater than (>) greater than or equal to (>=) less than (<) less than or equal to (<=)

25. What does an ‘if’ statement do?
Checks if a relational expression is true or false

26. When is an if-block executed, when is it skipped?
It is executed if true, skipped if false

27. What does an ‘else’ statement do?
If the relational expression is false, the statement will send the compiler to the else statement.

28. When is an else-block executed, when is it skipped?
executed when the relational expression is false, skipped if the compiler went through the if block already.

29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped?
You can check multiple data with an if statement. An example:
if (a>b)
std::cout >> "a is higher than b!";
else if (a<b)
std::cout >> "a is lower than b!";
else if (a==b)
std::cout >> "a is the same as b!";

30. What are the 3 logic operators in C++? How are they used? Show examples.
And (&&) Or (||) and Not (!)

31. What is “Short Circuit Evaluation?” How might it be beneficial?
When the compiler evaluates an and statement and the first is not true, it won't bother checking the second.
When the compiler evaluates an or statement and the first is true, it won't bother checking the second.

32. What is the precedence of the logical and conditional operators?
the logical and, logical or then the conditional operater in that order.

33. What is the conditional operator? How is it used? When might it be useful? Show examples.
The ternary operator. The only operater that takes three terms. (expression1) ? (expression2) : (expression3) reads If expression1 is true return the value of expression2 otherwise return expression3 and can be used in place of if statements, but they can't get too complicated (They can't be nested)

Chapter 4 Excersises

[source lang=cpp]#include <iostream>int main(){	float rate, time;	float dist;	std::cout << "This program will calculate the distance traveled" << std::endl << "over the time given using the speed." << std::endl << std::endl;	std::cout << "Please enter the speed in MPH: ";	std::cin >> rate;	std::cout << "Please enter the time traveling in hours: ";	std::cin >> time;	dist = rate / time;	if (time != 1)		if (rate != 1)			if (dist != 1)				std::cout << std::endl << "In " << time << " hours you could travel " << dist << " miles at a speed of " << rate << " miles per hour." << std::endl;			else				std::cout << std::endl << "In " << time << " hours you could travel " << dist << " mile at a speed of " << rate << " miles per hour." << std::endl;		else			if (dist != 1)				std::cout << std::endl << "In " << time << " hours you could travel " << dist << " miles at a speed of " << rate << " mile per hour." << std::endl;			else				std::cout << std::endl << "In " << time << " hours you could travel " << dist << " mile at a speed of " << rate << " mile per hour." << std::endl;	else		if (rate != 1)			if (dist != 1)				std::cout << std::endl << "In " << time << " hour you could travel " << dist << " miles at a speed of " << rate << " miles per hour." << std::endl;			else				std::cout << std::endl << "In " << time << " hour you could travel " << dist << " mile at a speed of " << rate << " miles per hour." << std::endl;		else			if (dist != 1)				std::cout << std::endl << "In " << time << " hour you could travel " << dist << " miles at a speed of " << rate << " mile per hour." << std::endl;			else				std::cout << std::endl << "In " << time << " hour you could travel " << dist << " mile at a speed of " << rate << " mile per hour." << std::endl;	return 0;}

Extra - I even made it make sure the hour and hours is right (1 hour, 2 hours) etc.

[source lang=cpp]#include <iostream>int main(){	int number = 19, response;	std::cout << "Welcome to the number game!" << std::endl << "Try to guess my number: ";	std::cin >> response;	if (response == number)		std::cout << "You got it first try! Congratulations!" << std::endl;	else if (response > number)		std::cout << "Oops! The number you guessed is too high!" << std::endl;	else if (response < number)		std::cout << "Oops! The number you guessed is too low!" << std::endl;	else		std::cout << "Something wrong has happened that caused you to get this message." << std::endl;	std::cout << std::endl << "Thanks for playing! I hoped you enjoyed it." << std::endl;	return 0;}

1. 1
2. 2
3. 3
frob
15
4. 4
5. 5

• 20
• 12
• 13
• 14
• 80
• Forum Statistics

• Total Topics
632144
• Total Posts
3004405

×