ppt

advertisement
CS 105 Lecture 2
Variables
Wed, Jan 19, 2011, 5:07 pm
1
•
•
•
If You Missed Last
Week
Go to www.cs.iit.edu/~cs105/wed_eve,
click on Syllabus, review Lecture 01
notes, course schedule.
Make sure you go to Lab 0.
(Make sure you go to Lab 0 even if didn’t
miss last week :-)
2
Writing a C++ Program
•
•
•
•
•
Write pseudocode (Design)
Translate pseudocode into C++ source
code (Coding)
Edit code
Compile
Link
3
What Is Pseudocode?
•
•
•
English-like written solution to a
programming problem.
Somewhere between informal description
and program written in C++.
How do we get pseudocode?
How do we solve problems?
Design issues apply to almost any
vocation.
•
•
4
Creating Pseudocode
•
•
Steps in creating pseudocode:
Understand the problem.
Decide how to solve the problem.
Write the solution using a logical
sequence of statements.
Typically, we break down large problems
into smaller subproblems and solve
those.
•
•
•
5
•
•
Pseudo vs Source
Code
Source code is the actual program code
that will run once compiled and linked.
Pseudocode should be easily translatable
into source code.
6
•
C++ Required
Elements
Every C++ Program Must Have:
int
main()
{
}
•
•
•
•
7
Your First Program
// Sam Smith
// CS 105
// Section 07
#include <iostream>
using namespace std;
int
main()
{
cout << “Hello World!!” << endl;
return (0);
}
8
Compiler
•
•
•
•
Actually uses multiple programs to
translate source code program into
machine code (executable by hardware).
Preprocessor
Actual compiler
Linker
9
Preprocessing
•
•
•
Preprocessing is the actions taken before
a source file is handed off to the compiler
Outcome of preprocessing must still be a
correct source code file
#include is an example
10
#include
•
•
•
•
•
#include: Replace w/text of specified file.
#include usually occurs at top of
program.
Pound sign (#) must be in first column.
Ex: #include <iostream> for typical input
and output operations in C++
Error if file to include can’t be found.
11
Actual Compiler
•
•
•
Converts source code into an object file
or machine code.
Each change to source file requires a
recompilation before re-execution.
Compiler also looks for malformed
programs — syntax errors a.k.a. “compile
time errors”.
12
Syntax Error
•
•
Syntax error: A non-proper, not allowable,
sequence of characters or words given a
particular language.
Typical syntax errors:
Spelling mistakes
Punctuation mistakes
Wrong type of data for operation
•
•
•
13
•
•
Spelling Errors
Examples
Undefined variable name
C++ is case sensitive
Example: “Hi” >> cout (not COUT).
Unrecognized keyword
Certain “key” words have special
meaning in C++. Example: int.
•
•
•
14
•
•
•
•
Punctuation Error
Examples
Missing, extra, or misplaced parentheses,
braces, commas, semicolons...
Parentheses unbalanced or of wrong
shape.
Comments malformed.
Syntax errors are typically listed at
bottom of screen when compilation is
complete.
15
•
Syntax Error
Messages
Two kinds of syntax error messages:
Warning: Compiler finds possible error,
lets it go by without failing.
Error: Compiler finds an error that
causes compile to fail.
•
•
16
•
•
Syntax Error
Messages
First error in program may “cause” other
errors to show up.
General advice: Fix the first error (and
any obvious errors), then recompile.
17
Linking
•
•
•
Linking connects (i.e. links) your object
code with external libraries (external =
not written as part of this program).
Object library contains already-written
and compiled code to use with other
programs.
Example: Code for iostream includes
definition of “<<“ and “>>”
18
Linking
•
•
•
If linker cannot find the libraries, error
messages are generated.
Successful linking creates an executable
file.
An executable file can be run.
(.exe file in Windows)
•
19
Logic Errors – “Bugs”
•
Also called semantic or run-time errors.
Program compiles, but doesn’t produce
the expected results.
Results wrong, missing, extra.
Program halting wrongly.
Errors may be repeatable or
intermittent.
•
•
•
•
20
Halting Problems
•
•
•
Halts early.
Never halts (infinite loop).
Halts due to bad operation.
Possible example: Dividing by zero.
Compiler does type checking to avoid
wrong kinds of data at runtime.
•
•
21
The “First” Bug
•
•
•
(From Navy website for Adm. Grace
Murray Hopper)
1947: Moth found shorting a relay in early
computer.
“Bugs” and “debugging” already used as
terms, but this is first example of a bug
being caused by an actual bug.
22
The “First” Bug
23
Detecting Bugs
•
•
•
•
Test-run program with different inputs.
Test plan: series of tests (e.g., inputs) that
have predetermined expected outputs.
Test-run program under all potential
conditions.
May need simulator, other tools to look at
data & operations during program run.
24
Debugging
•
•
•
•
Debugging: Finding and removing bugs.
When errors detected, analysis is
needed.
Work backward from symptom: What can
cause this symptom?
Example: We printed x and got the wrong
value. Where did x get set/changed?
Why was x set to a bad value?
25
Comments
•
•
•
Comments are used to help the person
reading the program understand it.
Good comments are invaluable.
Typically two types of comments.
Summary of program or major part of it.
Descriptions of data/variables.
•
•
26
Types of Comments
•
Summary comment typically describes
intent of larger piece of program.
E.g. overall summary at beginning of
program.
With data/variable definition, comments
describe properties, uses of
data/variable.
E.g. x should be ≥ 0 and ≤ y.
•
•
•
27
•
•
What Goes in
Comments?
Don’t generally need to comment “what”
is happening unless it’s especially
complicated.
Comments are good for saying things
you can’t easily infer from the program.
Why are we doing something?
What are the properties of and
relationships between variables?
•
•
28
Comments in C++
•
•
•
Two ways to write comments in C++
// Comment to end of line
/* Comment until star slash */
First occurrence of star slash (not
“matching” like parentheses).
Can be many lines away.
•
•
29
Elements of a Program
•
•
•
•
Summary Comments
Preprocessor statements (e.g., #include)
Namespace declaration
Main Function
30
Main Function
•
•
Main Function:
int main()
{
// statements;
return 0;
}
31
Program Format
•
White Space:
Not recognized by compiler
Used by humans to show program
structure.
Indent (e.g. 3 spaces) for each new
function, selection, or loop
•
•
•
32
Variables
•
•
Variables are names (identifiers) used to
store values that may change.
Every variable has a value and a type.
Type: the kind of value (integer, floating
point, character, etc.) being stored.
Value gets assigned/reassigned as
program runs
•
•
33
•
•
Declarations of
Variables
In C++, we “declare” variables.
Tells compiler to set aside storage
space.
Tells compiler the variable’s type (what
type of value it will hold)
May or may not specify an initial value
for the variable.
Must declare variable before using it.
•
•
•
34
Example
int main()
{ int num1; variable declaration
num1 = 10; variable assignment
cout << num1; variable output
}
•Declaration int num1 includes type and name
of variable (no initial value).
35
•
Variables and Main
Memory
int num;
num
<garbage>
•
num = 10;
•
num = 15;
num
10
num
15
36
Main
Memory
Main Memory
•
•
•
•
•
Storage location of data in a computer.
Used when a program is running.
RAM = “Random Access Memory”
“Wiped clean” when computer rebooted.
Byte: basic unit of storage (8 bits; can
store one letter of English alphabet)
37
Main Memory
•
•
•
Kilobyte (KB): 1000 (or 1024) Bytes
Bug photo was 100 KB
Megabyte (MB): 1,000,000 Bytes
CD holds 700 MB
Gigabyte (GB): 1,000,000,000 Bytes
DVD holds 4.7 GB
•
•
•
38
Initialization/Assignme
nt
•
•
Initialization: Giving a value to a variable
when its space is allocated (specified in
declaration).
Assignment: Giving a value to a variable
after it’s been allocated.
Use assignment statement to do this.
•
39
Variable Initialization
int main()
{ int num1 = 10; variable declaration
with initialization
cout << num1; variable output
}
40
Built-In Datatypes
•
C++ supports some built-in/”primitive”
data types. (Correspond to types of data
typically supported by hardware.)
Various kinds of numbers (integral and
floating-point).
Characters.
•
•
41
Built-In Numeric Types
•
•
•
int: Integer, typically -32768 to 32767 (depends on machine/compiler). No
commas!!
float: Real number, range typically 10-38
to 1038. E.g. 6.02e23 for 6.02 × 10²³.
double: Larger exponents, more
significant digits than float (typically 10e308 to 10e308).
42
Identifiers
•
Can use letters, digits 0–9 and
underscores.
Can’t start with a digit.
Case-sensitive (Example: NumWidgets
is not the same as numwidgets).
Can’t contain spaces or other
characters.
Practical maximum of 32 characters.
Cannot use C++ keywords.
•
•
•
•
•
43
•
•
Naming Variables
(Cont)
Use a meaningful, descriptive name so
that variable’s use is easily understood.
(E.g. counter, second, minute, length,
width.)
Separate internal words with underscores
or with capitalization. (Example:
averageRainfall or average_rainfall, not
averagerainfall.)
44
Scope of a Variable
•
Scope: Area of a program within which a
variable can be referenced.
Typical variable has local scope, within
the { … } in which it was defined.
Later on we’ll see function parameters;
they have local scope too.
•
•
45
Download