본문 바로가기
[Umich] COE Core/ENGR 101 (Matlab, C++)

[Notes] Ch.13 More C++ Basics and Branching (Runestone)

by Class of 26' Yuri Hong 2022. 11. 18.

I. Implicit Type Conversions

1. int to double

1. Widening conversion: a double can always hold any integer value. 

(1)   A double is a wider data type than an int.  

(2)   There is no info loss in this conversion, so this conversion and other widening conversions are generally considered safe.

2. double to int

(1)   The double value is truncated and only the integer part of the number is retained. 

(2)   Fraction part can’t possibly be fit in an int variable. 

(3)   Narrowing conversion: the truncation involves a loss of info -> lead to bugs. 

3. bool to int / double

(1)   False turns into 0

(2)   True turns into 1.

 

4. int / double to bool

(1)   Only a zero value will convert to false. 

(2)   Everything else, even negative numbers, turns into true.

II. Arithmetic Operators

  Operator Example Result
Addition + 2 + 3 5
Subtraction - 5 - 3 2
Multiplication * 5 * 3 15
Exponentiation None    
Division / 11/4 2.75
Modulo (remainder) % 11%4 3

* Make sure not to use a dot before multiplication and division! Otherwise, the compiler will give you an error. 

 

EX) 

50/6

A: 8

 

50%6

A: 2

 

1/2

A: 0 

 

1%2

A: 1

 

III. Floating Point Division vs. Integer Division Density

1. Floating point division : division with decimal and fractional parts. 

ex) 11 divided by 4 equals 2.75

2. Integer division: division without decimal or fraction

ex) 11 divided by 4 yields a quotient of 2, with remainder 3.

 

EXERCISE) Stopwatch

 

1. Store the total number of seconds in the variable x. 

2. Use integer division to divide x by 60 (60 seconds in a minute) to get the number of whole minutes elapsed; store the number of whole minutes in the variable m. 

3. Use the modulo operator % to get the remainder when x is divided by 60. These are the leftover seconds. Store the leftover seconds in the variable s. 

 

ex) if the hardware reported 3753 seconds, your program should convert this to 1 hour, 2 minutes, and 33 seconds.

 

IV. Relational and Logical Operations

1. Relational Operators in C++

 (1) Relational Operations: check for equality or perform comparison. 

(2) One big difference is that true / false data type in C++ is called a boolean

(3) All these operations results in a bool.

 

  Operator Example Result
Equality == 2 == 3 false
Inequality != 2 != 3 true
Less than  5 < 5 false
Less than or equal <= 5 <=5 true
Greater than  ‘C’ > ‘D’ false
Greater than or equal >= 4.5>=4.5 true

 

2. Logical Operators

 

  Operator Example Result
Logical And && 2 < 3 && 5 >6 false
Logical Or || 2 < 3 || 5 > 6  true
Exclusive Or N/A    
Not ! !(‘a’ == ‘b’) true

 

* Computations with floating point numbers have limited precision, and if enough roundoff error is accumulated, two double values might not be exactly equal anymore.

 

3. Short-Circuit Evaluation

EX)  Predict the output of the following statement: 

EX)  Predict the output of the following statement: 

EX)  Predict the output of the following statement: 

EX)  Predict the output of the following statement: 

EX)  Predict the output of the following statement: 

* 계산 좌측에서 우측 순서 하나하나 차례로 계산함.

A:

V. Branching with If Statements

1. Control Flow

(1) Control flow structures like if, for, and while allow us to structure our code to follow the desired control flow. 

 

2. If Statements

(1) If statements allow branching (also called “selection” statements)

(2) If statements Syntax

3. Why use braces?  => It avoids confusion.

 

IV. Scope

1. Many variables have local scope, also known as block scope. 

2. Block: a chunk of code (sequence of statements) enclosed by curly braces {}. 

(1) {}: These curly braces define a block. The variable y lives inside this block. 

3. A variable can only be used after it’s been declared, and while it’s in scope. 

4. Many variables have a local scope (or block scope) 

 

IIV. Two-way Branching with Else

1. An if statement may have two branches

   (1) A “then” branch - executed if the condition is true. 

   (2) An “else” branch - is executed if the condition is false. 

2. Guarantee: only one branch is chosen. 

3. An if statement may have two branches, only one of which is evaluated. The “then” branch is executed if the condition is true, and the “else” branch is executed if the condition is false. 

 

IIIV. Nested If Statements and Decision Trees

1. Nested if statements

(1)   Control flow structures can be nested within each other. 

(2)   Check if 0 <= x < 5

(1)   Sometimes nesting definitely makes your code cleaner: 

ex) print a report based on status and progress variables:

2. Decision Trees

(1)   We can model an if / else structure using a decision tree. 

 

3. Else if

(1)   In some cases, we want to split into more than two branches. 

(2)   Use the else if pattern to accomplish this

* If we want to split into multiple branches, we can use the else if pattern. The structure of an if / else statement can be modeled using a decision tree. 

 

EXERCISE) Leap Year Calculator

1. The year is exactly divisible by 4 and not divisible by 100 OR

2. The year is exactly divisible by 400. 

 

Write a program to check if the year 2004 is a leap year. 

 IV. Summary  

  1. An implicit conversion happens when a value of one data type is converted by the compiler into a different type. 
  2. An explicit conversion is a type conversion written by the programmer. 
  3. Converting int to double is a widening conversion with no info loss. 
  4. Converting double to int is a narrow conversion where the value is truncated. 
  5. When converting from bool to int or double, false turns into 0 and true turns into 1. 
  6. When converting the other direction, only 0 converts to false; everything else converts to true. 
  7. Basic arithmetic operators in C++ are addition, subtraction, multiplication, division, and modulo. 
  8. Floating point division gives us the exact quotient. 
  9. Integer division gives us the whole number quotient (we can use % to get the remainder). Which kind of division is used depends on the data types of the operands. 
  10. Basic relational operators include equality, inequality, less than, less than or equal, greater than, and greater than or equal. Logical operators include logical and, logical or, and not. 
  11. && and || are evaluated with short-circuit evaluation. 
  12. If, else, and else if statements can be used for branching. They can be modeled using a decision tree. 
  13. Variables can only be used in the scope in which they are declared. Many variables have local scope (or block scope).

댓글