1 eecs230 course introduction and a first program ying wu electrical engineering and computer...
TRANSCRIPT
1
EECS230 Course Introduction and a First
ProgramYing Wu
Electrical Engineering and Computer Science
Northwestern [email protected]
EECS230 Lectures Series
3
Course Information Lectures
– M,T,W,F 1-1:50pm, Tech. LR4– Tuesday meetings: TA sessions
Text– C++ How to Program, 4rd (or later) Edition, by H.M.
Deitel and P.J. Deitel, Prentice Hall. Course Web
– http://www.courses.northwestern.edu/ using your ID
Grading– Machine Problems (MPs): 30%– Midterm exam: 30%– Final exam: 40%
4
Why should we study programming?
Think about your new role in 5 years
– A graduate student– An engineer– A manager– …
Programming practice can– Implement your ideas– Motivate you to re-think your ideas– Make you solid, sharp and deep-thinking– Make you more cooperative
5
Eager to Learn C/C++? We shall cover
– C/C++ control structures– Function– Pointers and Array– Stream I/O and string operations– Dynamic memory allocation– Classes– Classes with pointer data members– Linked list– Sort and search
See the course syllabus for a detailed schedule
6
We’ll focus on
Core C/C++ concepts– Such as:
Pointers and referencesCall-by-value v.s. call-by-referenceClassCopy constructor…
Program design Debugging skills
7
The best way in learning C/C++
Deep understanding the concepts, especially– Pointers/references– Functions– Classes
Coding experiences– Do spend time in coding– Reading examples
Debugging– Tools– Skills
8
The GOAL for Week-1/2
Understand all C/C++ data types Understand basic computer architecture
and addressing mechanism Use cin/cout to input/output Grasp six C/C++ control structures Understand array Design by using flowcharts Get a sense of the compiling process DEBUG_1: debugging when you are
coding Do the MP#1 (basic control structures)
9
What to learn today? How does the computer do with my code? What are “int”, “float”, “double”, “bool”? What is a variable? What will happen if you declare a
variable? Arithmetic expressions and calculation? Logical expressions and decision making? How to get inputs and output results?
10
What does the Computer do with my program?
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
Loader
PrimaryMemory
Program is created inthe editor and storedon disk.
Preprocessor programprocesses the code.
Loader puts programin memory.
CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.
CompilerCompiler createsobject code and storesit on disk.
Linker links the objectcode with the libraries,creates a.out andstores it on disk
Editor
Preprocessor
Linker
CPU
PrimaryMemory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
Let’s see an example then.
11
Basic Data Types
int– integer (4 bytes = 32 bits)
float– real decimal number (4 bytes = 32 bits)
double– double precision real decimal number (8
bytes = 64 bits) char
– character (1 byte = 8 bits) bool
– true/false (1 byte), or 0/1
12
ASCII char set
American Standard Code for Information Interchange
A character has a numerical representation (a decimal integer) in computer, e.g., ‘a’ – 97, ‘A’ – 65, ‘1’ – 49, ‘+’ – 43, etc
Check the appendix B of D&D for the table
Question: how many characters can we have?
13
Conversion among Data Types
Priority order– bool and char < int < float < double
The compiler can automatically convert low priority data to higher ones
But it can not do the inverse automatically
Why? – You will lose precisions!
So, you have to do it yourself forcefully– e.g., (int) 3.1415 3
14
What is a variable?
Three Properties– Type
determines the number of bytes of memory that are allocated for this variable by O/S
– Nameis used to address (or retrieve) this
variable in system memory stacks
– Valueis the content and is used for calculation
15
Memory Concepts Variable names
– Correspond to locations in the computer's memory
– Every variable has a name, a type, and a value
– Whenever a new value is placed into a variable, it replaces the previous value
– Reading variables from memory does not change them
A visual representation
integer1 45
16
Addressing? Physically, each byte of physical memory is a set
of registers, each of which corresponds to 0/1. Each byte of memory has a unique “address”.
Generally, we use a hexadecimal number to describe its address, e.g., 0x0012FD8C (32 bits)– Question: how many bytes can a 32-bit machine
manage? In hardware, addressing is realized by sending
such a hexadecimal number to the BUS to get the value of the memory blocks.
In C/C++ language, we do not need deal with such hexadecimal numbers, instead, we deal with the names or pointers of variables.
17
What if you declare a variable?
O/S will allocate (reserve) a memory block to hold the value of the variable.
The value can be changed by “assignment”
The value can be retrieved by “addressing”
No other variables can use such a memory block until you let the O/S to recycle it. (how?)
18
Examples
a = 3;a 3
int a;a
a = 5;a 5
float b;a 5
b
b = a+1;a 5
b 6
19
Arithmetic Expressions Arithmetic calculations
– Use * for multiplication and / for division– Integer division truncates remainder
7 / 5 evaluates to 1 (isn’t it interesting?)
– Modulus operator returns the remainder 7 % 5 evaluates to 2
Operator precedence– Some arithmetic operators act before others
(i.e., multiplication before addition)Be sure to use parenthesis when needed
– Example: Find the average of three variables a, b and cDo not use: a + b + c / 3 Use: (a + b + c ) / 3
20
Arithmetic Operators Arithmetic operators:
Rules of operator precedence:
C++ operation Arithmetic operator
Algebraic expression
C++ expression
Addition + f + 7 f + 7
Subtraction - p – c p - c
Multiplication * bm b * m
Division / x / y x / y
Modulus % r mod s r % s
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Modulus
Evaluated second. If there are several, they re evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to ri ght.
21
Logical Op.: Decision Making
Standard algebraic equality operator or relational operator
C++ equality or relational operator
Example of C++ condition
Meaning of C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
22
What does a logical exp. evaluate?
It evaluates a boolean value, i.e., true/false
Certainly, a boolean variable can be automatically converted to other data types
An interesting examplebool c;
char a = ‘Z’;
c = (a = = 90);
Question: what will be the value of c?
23
“Hello, World!”
std::cout– Standard output stream object– “Connected” to the screen– std:: specifies the "namespace" which cout belongs
tostd:: can be removed through the use of using statements
<< – Stream insertion operator – Value to the right of the operator (right operand)
inserted into output stream (which is connected to the screen)
– std::cout << “Hello, World!\n”; \
– Escape character – Indicates that a “special” character is to be output
24
1. Load <iostream>
2. main
2.1 Print "Welcome"
2.2 Print "to C++!"
2.3 newline
2.4 exit (return 0)
Program OutputWelcome to C++!
1 // Fig. 1.4: fig01_04.cpp
2 // Printing a line with multiple statements
3 #include <iostream>
4
5 int main()
6 {
7 std::cout << "Welcome ";
8 std::cout << "to C++!\n";
9
10 return 0; // indicate that program ended successfully
11 }
Unless new line '\n' is specified, the text continues on the same line.
25
Wanna get an input? >> (stream extraction operator)
– When used with std::cin, waits for the user to input a value and stores the value in the variable to the right of the operator
– The user types a value, then presses the Enter (Return) key to send the data to the computer
– Example:int myVariable;
std::cin >> myVariable;
Waits for user input, then stores input in myVariable
26
1.Load <iostream>
2. main
2.1 Initialize variables integer1,
integer2, and sum
2.2 Print "Enter first integer"
2.2.1 Get input
2.3 Print "Enter second integer"
2.3.1 Get input
2.4 Add variables and put result
into sum
2.5 Print "Sum is" 2.5.1 Output
sum
2.6 exit (return 0)
Program Output
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program
3 #include <iostream>
4
5 int main()
6 {
7 int integer1, integer2, sum; // declaration
8
9 std::cout << "Enter first integer\n"; // prompt
10 std::cin >> integer1; // read an integer
11 std::cout << "Enter second integer\n"; // prompt
12 std::cin >> integer2; // read an integer
13 sum = integer1 + integer2; // assignment of sum
14 std::cout << "Sum is " << sum << std::endl; // print sum
15
16 return 0; // indicate that program ended successfully
17 }
Enter first integer45Enter second integer72Sum is 117
Notice how std::cin is used to get user input.
Variables can be output using std::cout << variableName.
std::endl flushes the buffer and prints a newline.
27
Save your typing …
using statements– Eliminate the need to use the std:: prefix– Allow us to write cout instead of std::cout
– To use the following functions without the std:: prefix, write the following at the top of the program
using std::cout;
using std::cin;
using std::endl;
28
1. Load <iostream>
2. main
2.1 Initialize num1 and num2
2.1.1 Input data
2.2 if statements
1 // Fig. 1.14: fig01_14.cpp2 // Using if statements, relational3 // operators, and equality operators4 #include <iostream>56 using std::cout; // program uses cout7 using std::cin; // program uses cin8 using std::endl; // program uses endl910 int main()11 {12 int num1, num2;1314 cout << "Enter two integers, and I will tell you\n"15 << "the relationships they satisfy: ";16 cin >> num1 >> num2; // read two integers1718 if ( num1 == num2 )19 cout << num1 << " is equal to " << num2 << endl;2021 if ( num1 != num2 )22 cout << num1 << " is not equal to " << num2 << endl;2324 if ( num1 < num2 )25 cout << num1 << " is less than " << num2 << endl;2627 if ( num1 > num2 )28 cout << num1 << " is greater than " << num2 << endl;2930 if ( num1 <= num2 )31 cout << num1 << " is less than or equal to "32 << num2 << endl;33
The if statements test the truth of the condition. If it is true, body of if statement is executed. If not, body is skipped.
To include multiple statements in a body, delineate them with braces {}.
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7
Notice the using statements.
29
2.3 exit (return 0)
Program Output
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
Enter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7
Enter two integers, and I will tell you the relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12
Enter two integers, and I will tell you the relationships they satisfy: 7 77 is equal to 77 is less than or equal to 77 is greater than or equal to 7
30
Summary What we have learnt:
– Basic C++ environment– Basic data types– Variables and addressing– Arithmetic/logical expressions– Basic I/O
Questions remained:– How can we get a “line of characters” as the
input?– Compare to a variable, how will such a line
be stored in memory?– What can we do about that entire line of
input?