I. C++, Machine Code, Compilers
1. Interpreted Languages
(1) MATLAB: interpreted language.
* The code doesn’t run on your computer.
* MATLAB (the program) runs on the computer and processes the code line-by-line, telling the computer what to do.
2. Machine Languages
(1) Computers can only directly run programs written in “machine code”.
(2) Different kinds of computers also have different machine languages.
(3) Machine code is not human-friendly.
3. Compiling Source Code
(1) Write source code in a language like C++ and use a program called a compiler to translate it to machine code.
4. Compiling vs. Running
(1) Step 1: Compile - Translate a source code file into an executable file
(2) Step 2: Run the program – Take an executable program file and actually run it on the computer.
5. Summary
(1) MATLAB: interpreted language. MATLAB process the code line-by-line.
(2) C++: compiled language. It uses a complier to translate a source code file into an executable file (ex. Machine code)
EXERCISE)
(1) Source code: Program code that someone might actually write to solve a problem.
(2) Compile: Translate a source code file into an executable file (ex. Machine code).
(3) Machine code: Code that can be executed directly on a computer, but that is not generally human-friendly.
(4) Run: Take an executable program file and actually run it on the computer.
(5) Interpreter: A program that acts as an intermediary to run source code line-by-line (ex. MATLAB)
II. Writing Up The Hello World Program
1. Creating a first program in C++
(1) Error: I must put ‘hello.cpp’ file into the current directory.
(2) Printing out “Hello World!”
· To open a terminal in Mac, press [Control ^] + [` (~)]
· To compile and execute the file
· Never to this
2. Summary
(1) Step 1: Compile
g++ program.cpp helper.cpp -o program
· program & helper: The names of files containing the source code.
· -o followed by the name of the executable program you want to create. This is the output of the compiler, and what you use to run your program.
(2) Step 2: Run the program
./program
· Must match executable name from step 1
(3) Never to this:
g++ program.cpp helper.cpp -o program.cpp
· Accidentally specify the source file as the destination for the machine code. The compiler will overwrite it.
III. C++ Syntax and Types
1. Statements
(1) We use sequences of statements to give instructions for what we want our program to do.
(2) In C++, all statements must end with a semicolon ;.
2. Variable Declarations
(1) In C++, you are required to declare variables before you can use them.
(2) A declaration lets the compiler know about the variable:
· Its name.
· Its type.
· An optional initializer expression.
3. Basic Types
Type | Description | Example |
int | A signed integer (can be negative) | int x = 3; |
double | A floating point number. (has a fractional part) | double y = 2.5; |
bool | A Boolean (logical) value. 1: true, 0: false |
bool z = true; |
char | A single character. | Char c = ‘w’; |
string | A sequence of characters. | string word = “hello”; |
4. Variables and Memory
(1) Declaring a variable basically requests memory space to store some data.
· Data is stored in bytes, which consist of eight binary digits. (ones and zeros)
· The type determines how much space
· The name allows you to refer to that memory throughout the rest of the code.
(2) If you don’t provide an initializer, the value of the variable is undefined until you assigned something into it.
(3) The value is just based on whatever memory junk was there previously.
5. Expressions in C++
(1) Expressions may consist of:
· Literals Ex) 3, 7.5
· Variables Ex) x,y,z
· Function Calls Ex) sin(3), sqrt(x)
(2) To find out the type of the expression, we need to see the declarations of x and y.
6. Comments in C++
(1) Two different styles:
· Single-line – anything after a // on a line becomes a comment.
· Block – anything between a /* and a*/ becomes a comment.
7. Summary
(1) All statements must end with a semi-colon.
(2) You must declare it by telling the complier its name, its type, and an initializer expression.
(3) Common data types: ints, doubles, bools, chars, and strings.
(4) If you don’t initialize a variable, then the value of the variable is based on whatever memory junk was in that memory location previously.
(5) Single-line comments: // block comments: /* and */
EXERCISE)
Declare and initialize five variables.
(1) numPieces: an integer representing the number of pieces of candy you have (5)
(2) cost: a double representing the cost per piece of candy (3.25)
(3) name: a string representing the name of the candy (“peeps”)
(4) category: a character representing the category of the candy (“K”)
(5) isGood: a Boolean representing whether the candy taste good (false)
IV. User Input / Output
1. Printing Output
(1) To print out in C++, we need to send it to the “standard output stream”.
(2) cout is a variable that represents this stream. (pronounced “C out”, two words)
(3) The << operator sends output and can be “chained” to send many different pieces on one line.
2. User Input
(1) When the user types input at the terminal, it comes in via the “standard stream”, represented by cin.
(2) The >> operator reads input from a stream.
(3) Input is interpreted according to the type of the target variable.
3. Summary
(1) cout can be used to print a message to the terminal. (ex. “Hello World!”).
(2) cin can be used to pause a program and wait for input from the user. To send it, the user just types sth and his the <enter> key.
When the user types input at the terminal, it comes in via the “standard stream”, represented
EXERCISE) User Input via cin
OUTPUT should be:
==================================
$ g++ candy. cpp -o candy
./candy
What is your favorite candy?
$ Peeps
How many would you buy right now?
$ 5
How much does each piece cost?
$ 3.25
5 peeps will cost you 16.25
==================================
V. Compile Errors and Runtime
1. Compile Errors
(1) Translate a source code file into an executable file (ex. Machine code) and analyze the code for errors.
(2) If the compiler finds an error, no executable file is produced.
(3) The compiler can catch errors for you, but you can’t run the program until you fix them.
2. Compile Errors: Syntax
(1) Missing semicolon.
(2) Missing quote for string literal.
(3) Missing closing curly brace.
3. Compile Errors: Semantics
(1) Undeclared variable y.
(2) Can’t divide a string by an int. (operation we requested doesn’t make sense.
(3) Duplicate definition of x.
(4) cout doesn’t exist. (Forgot to use #include <iostream> above)
4. Compile Errors: Type Errors
(1) There are two main kinds of type errors:
· Invalid operations
· Invalid conversions
5. Static vs. Dynamic Typing
(1) Statically typed: C++
· A variable’s type is known at compile-time, based on its declaration.
· A variable’s type is fixed and never changes.
· The compiler can check for all type errors before the program runs.
· (값을 업데이트 하는 것은 가능인데 한 번 declare하면 또 다시 declare 할 수 없음. 업데이트 시 변수만 사용, declare 시 type 및 변수 모두 사용)
(2) Dynamically typed: MATLAB
· A variable’s type can change at runtime.
· It’s type just depends on the type of value it is currently holding.
· Can’t check up front.
· A variable can end up holding any type of value.
· Only discover type errors at runtime.
6. Compile-time vs. Runtime
(1) Compile-time: things known then compiling the code.
· Are there syntax errors in the code?
· Are all variables declared before they are used?
· What is the type of this variable? Are all operations on it valid?
(2) Runtime:
· What value did the user enter?
· Did your program accidentally divide by zero and crash?
7. Runtime Errors
(1) The compiler can’t always predict things that could go wrong.
=> If the user enters 0 for y, the divide by zero causes a runtime error and the program crashes.
EXERCISE) Compile and Runtime Errors
(1) undeclared variable: semantic error (compile-time error)
(2) runtime error: cannot divide by zero
(3) missing curly brace: syntax error (compile-time error)
(4) string value cannot be assigned to an int variable: type error (compile-time error)
IV. Application: Temperature Converter
The formula to convert Celsius (C) to Fahrenheit (F): F = 9/5*C +32.
Your program should:
· Prompt the user for a temperature in Celsius.
· Read the temperature from the standard input stream (ex. cin)
· Compute the temperature in Fahrenheit and print it.
==========
* You need to write 9 and 5 as 9.0 and 5.0 to get an accurate result!
* Set type as “double” rather than “int”.
'[Umich] COE Core > ENGR 101 (Matlab, C++)' 카테고리의 다른 글
[Notes] Ch.14 Iteration (Runestone) (0) | 2022.11.18 |
---|---|
[Notes] Ch.13 More C++ Basics and Branching (Runestone) (0) | 2022.11.18 |
==Incomplete== [Notes] Ch.11 Applying Computing to Society (Runestone) (0) | 2022.11.18 |
==Incomplete== [Notes] Ch.10 MATLAB Tables (Runestone) (0) | 2022.11.18 |
==Incomplete== [Notes] Ch.9 Strings and Cell Arrays (Runestone) (0) | 2022.11.18 |
댓글