Discussion - PowerPoint PPT Presentation

1 / 76
About This Presentation
Title:

Discussion

Description:

Holiday. Tue. 24 July. HW 4 (CH 10-12) 13. Control Structures. 11. Fri. 20 ... 9 For do we not read that God is the same yesterday, today, and ... Define a ... – PowerPoint PPT presentation

Number of Views:89
Avg rating:3.0/5.0
Slides: 77
Provided by: paulr7
Category:
Tags: discussion

less

Transcript and Presenter's Notes

Title: Discussion


1
Schedule
2
No Variables
  • Mormon 99
  • 9 For do we not read that God is the same
    yesterday, today, and forever, and in him there
    is no variableness neither shadow of changing?
  • Moroni 746-47
  • 46 Wherefore, my beloved brethren, if ye have not
    charity, ye are nothing, for charity never
    faileth. Wherefore, cleave unto charity, which is
    the greatest of all, for all things must fail
  • 47 But charity is the pure love of Christ, and it
    endureth forever and whoso is found possessed of
    it at the last day, it shall be well with him.

3
Chapter 11 - Intro to Programming in C
4
Remember levels of abstraction?
Problems
Algorithms
High Level Languages
Language
Assembly code
Machine (ISA) Architecture
Machine code
Microarchitecture
LC-3 Architecture
Circuits
Logic gates, multiplexers, memory, etc.
Devices
Transistors
5
Levels of Abstraction
  • The closer a language is to your original
    specification, the easier the program is to
    write.
  • Many, many programming languages
  • LISP - LISt Processing
  • PROLOG - logic programming
  • MATLAB - matrix and vector manipulations
  • BASIC interpreter for small computers
  • APL matrix and vectors
  • FORTRAN formula translation
  • COBOL business and accounting
  • PASCAL - procedural
  • .

6
High Level Languages
  • Allow us to give symbolic names to values
  • Programmer simply assigns each value a name
  • Allow us to ignore many memory details, the
    compiler takes care of
  • register usage
  • variable allocation
  • loads and stores
  • stack management for subroutine calls

7
High Level Languages
  • Provide abstraction of underlying hardware
  • Hide low level details (ISA) from programmer
  • Uniform interface (not tied to ISA) to program
  • Portable software (works on different ISAs)
  • The compiler generates the correct machine code

if ((a lt 9) (a gt 0)) sum sum
10 sum sum (a - 0) else ...
8
High Level Languages
  • Provide expressiveness
  • Human-friendly orientation
  • Express complex tasks with small amount of code
  • English-like and human readable
  • if-then-else
  • while
  • for...
  • switch

if(isCloudy) get(umbrella) else
get(sunglasses)
9
High Level Languages
  • Enhance code readability
  • Can read like a novel
  • if written with readability in mind
  • Readability.. is very important
  • life cycle costs are more important than
    initialprogramming costs
  • Easier to debug
  • Easier to maintain

main() readInput() checkForErrors()
doCalculation() writeOutput()
10
High Level Languages
  • Provide safeguards against bugs
  • Rules can lead to well-formed programs
  • structured programming is an example (no GOTO
    stmts)
  • Compilers can generate checks
  • array bounds checking
  • Many languages provide explicit support for
    assertions
  • something that should be true - if it isnt gt
    error

assert(accountBalance gt 0)
11
Compilation vs. Interpretation
  • Interpretation An interpreter reads the program
    and performs the operations in the program
  • The program does not execute directly, but is
    executed by the interpreter.
  • Compilation A compiler translates the program
    into a machine language program called an
    executable image.
  • The executable image of the program directly
    executes on the hardware.

The interpreter and compiler are themselves
programs
12
Compilation
Algorithm
The assembly language stage is often
skipped Compiler often directly generates
machine code.
compiler
Assembly language program ADD r0,r1,r2
13
Compilation
  • Convert high-level code to machine code
  • compile once, execute many times
  • resulting machine code is highly optimized
  • high performance when executed
  • Is an assembler considered a compiler?
  • assemblers do convert higher level code to
    machine code
  • they are usually in a class by themselves

14
Interpretation
Algorithm
15
Interpretation
  • Program code is interpreted at runtime
  • lines of code are read in
  • interpreter determines what they represent
  • requested function is performed

Interpretation is common LISP BASIC
Perl Java Matlab LC-3 simulator
UNIX shell MS-DOS command
line Interpretation can be slow...
Interpret() while(3 lt 4) // do forever
readInputLine() if(line0..3 mult)
doMultiply() else if(line0..3 add)
doAdd() else ...
16
The C Programming Language
  • Invented 1972 by Dennis Ritchie at Bell Labs
  • C developed for use in writing compilers and
    operating systems (UNIX)
  • A low-level high-level language
  • Many variants of C
  • 1989, the American National Standards Institute
    standardized C (ANSI C, most commonly used C)
  • The C Programming Language by Kernighan and
    Ritchie is the C Bible
  • C is predecessor to C and Java.

17
Compiling a Program
C Source Code
Source Code Analysis
Symbol Table
Code Generation
18
A First Program
Tells compiler to use all the definitions found
in the standard I/O library. A .h file is
called a header file and contains definitions and
declarations.
include ltstdio.hgt int main()
printf(\nHello, World!)
All programs must have a main() routine. This
one takes no arguments (parameters).
printf() is a subroutine from the standard I/O
library. The name stands for formatted
print. \n signifies a newline character.
Without it, the text printed would not have a
newline after it.
19
Compiling/Running Our First Program
cc hello.c a.out Hello, world cc -o hello
hello.c hello Hello, world
20
More Compiling/Running
cc -c hello.c cc -o howdy hello.o
howdy Hello, world
21
A Second Program
include ltstdio.hgt define STOP 0 int main(int
argc, char argv) int counter int
startPoint printf("\nEnter a positive number
") scanf("d", startPoint) for(counter
startPoint counter gt STOP counter--)
printf("\nCount is d", counter) return 0
Print a prompt
22
Compiling/Running a Program
cc second.c a.out Enter a positive number
3 Count is 3 Count is 2 Count is 1 Count is
0 cc -o second second.c second
Call the C compiler on the input file second.c
It will generate second.o and then link that
into a.out
Call the C compiler on the input file second.c
Tell it to call the resulting executable second
Execute it
23
More Compiling/Running
cc -c second.c cc -o count second.o
count Enter a positive number 3 Count is
3 Count is 2 Count is 1 Count is 0
Compile second.c into second.o but dont
create an executable.
Link second.o into executable called count
24
Formatting, Comments
  • Use lots of comments
  • / This is a comment /
  • Comment each procedure telling/----------------
    ------------------// ProcedureName what it
    does // Parameters
    // Param1 what param1 is //
    Param2 what param2 is // Returns
    // What is returned, if
    anything //----------------------------------
    /
  • Use lots of whitespace (blank lines)

25
Indenting Style
  • Each new scope is indented 2-3 spaces from
    previous
  • Put on end of previous line, or start of next
    line
  • Line matching up below

Style is something of a personal matter.
Everyone has their own opinions What is
presented here is similar to that in common use
and a good place to start...
26
More On Indenting Style
  • For very long clauses, you may want to add a
    comment to show what the is for

if(a lt b) / Lots of code here... /
/ end if(a lt b) / else / Lots of code
here... / / end else /
27
The C Preprocessor
  • define symbol code
  • The preprocessor replaces symbol with code
    everywhere it appears in the program below
  • define NUMBER_OF_MONKEYS 259
  • define MAX_LENGTH 80
  • define PI 3.14159
  • include filename.h
  • The preprocessor replaces the include directive
    itself with the contents of header file
    filename.h
  • include ltstdio.hgt / a system header file
    /
  • include myheader.h / a user header file /

Preprocessor command are not terminated with
28
Doing Output in C
  • printf( format_string, parameters )
  • printf(\nHello World)
  • printf(\nd plus d is d, x, y, xy)
  • printf(\nIn hex it is x, xy)
  • printf(\nHello, I am s., myname)
  • printf(\nIn ascii, 65 is c., 65)
  • Output
  • Hello world
  • 5 plus 6 is 11
  • In hex it is b
  • Hello, I am Bambi.
  • In ascii, 65 is A.

29
Doing Input in C
  • scanf( format_string, destination_parameters )
  • scanf(c, nextChar)
  • Reads in one character. Assigns it to nextChar
  • scanf(f, radius)
  • Reads in one floating point number. Assigns it to
    radius.
  • scanf(d d, length, width)
  • Reads in two decimal integers, separated by
    whitespace. Assigns them to length and width.

Wait for chapter 16 to learn why we use the
30
Example Program ftoc.cA Fahrenheit to Celsius
program
/ File ftoc.c Date 24 May 2006 Author
Joe Coder Description Output a table of
Fahrenheit and Celsius temperatures. / include
ltstdio.hgt define LOW 32 / Starting
temperature / define HIGH 100 / Ending
temperature / / main() / int main() int
f / Temperature in fahrenheit / float
c / Temperature in celsius / / Loop
through all the temperatures, printing the table.
/ for(f LOW f lt HIGH f) c (f -
32) / 1.8 printf("\nf d, c .1f", f,
c)
The celsius temperature will only have 1 digit to
the right of the decimal point.
31
Example Program ftoc2.c
/ File ftoc2.c Date 24 May 2006 Author
Joe Coder Description Prints out a table of
Fahrenheit and Celsius temperatures.
Reads the starting and ending values from the
terminal. / include ltstdio.hgt / main()
/ int main() int low, high / Starting
and ending temperatures / int f
/ Temperature in fahrenheit / float c
/ Temperature in celsius /
printf("\nEnter starting and stopping
temperatures ") scanf("d d", low,
high) / Loop through all the temperatures,
printing the table. / for(f low f lt high
f) c (f - 32) / 1.8 printf("\nf
d, c .1f", f, c)
Parameters to scanf() must have a in front of
them. We will learn why later...
32
Example Program ftoc3.c
/ File ftoc3.c Date 24 May 2006 Author
Joe Coder Description Prints out a table of
Fahrenheit and Celsius temperatures.
Reads the starting and ending values from the
terminal. Will print an error
message if input is not integer
values. / include ltstdio.hgt / main() / int
main() int f, low, high, readCnt float
c printf("\nEnter starting and stopping
temperatures ") readCnt scanf("d d",
low, high) if(readCnt ! 2)
fprintf(stderr, "\nError on input, expecting two
integers...") exit(1) / Loop
through all the temperatures, printing the table.
/ for(f low f lt high f) c (f -
32) / 1.8 printf("\nf d, c .1f", f,
c)
scanf() returns the number of things successfully
read in. Should be 2 in this case...
There are 3 standard files you can use stdin
- terminal input stdout for printf()
stderr for error msgs You use fprintf() to
print to files other than stdout.
33
Chapter 12 Variables and Operators in C
First chimp in space
34
Variables Operators
  • Variables are symbolic names that can hold
    values.
  • Variable declarations give
  • Symbolic name
  • Type (int, char, double)
  • Scope (code region where the variable is defined)
  • Variables can be stored in memory or in
    registers.
  • The compiler keeps track of
  • Where a variable value is currently stored
  • When it needs to be moved from memory to a
    register, orfrom a register to memory
  • Operators are ways to manipulate on those values.

35
Comments in C
/ Comments start with slash-star, and end with
star-slash / / Multi-line comments are OK.
When you have a lot to say, you can always
write this way! / / Some like this different
style. Rather than an ugly pile, you put
new star on every line to make your comments
look just fine. / /----------------------------
---------// Or build a comment box,
// that stylishly talks... //
Some prefer rectangular features // to
describe their C procedures!
//-------------------------------------/
Note Poetry is not required for good commenting
36
C Variable Types
int a signed integer variable,
native word-size (16 or 32 bits, 16 bits in
LC-3)
char an 8-bit character (16 bits in LC-3)
float a 32-bit floating point
double a 64-bit floating point
long int a signed integer variable, size
varies by machine, usually 32 or 64 bits
short int a signed integer variable, size
varies by machine, often 16-bits
37
Variable Declarations
int i,j,k / declaring more than
one variable / int i1, i2, i3, c3po /
numbers OK, except for first letter / int
bananas 10 / using an initializer
/ int monkey_count 0 / two ways of
doing ... / int monkeyCount 0 / ...
multi-word names / int ab, Ab, aB, AB /
case sensitive names / int _compilerVar
/ compiler uses _ as first char / char newline
\n / a character with an initializer
/ char lineBuffer100 / an array of 100
chars (a string) / double bananasPerMonkey
/ floating point declarations / double
hugeNumber 1.0E100 / positive exponent
/ double tinyNumber 1.0E-100 / negative
exponent / double fractionThing 3.33333 / no
exponent /
38
Scope Local versus Global
  • Local Variables
  • Declared at the beginning of a block
  • Stored on the stack
  • Scope is from point of declarationto the end of
    the block
  • Un-initialized
  • Global Variables
  • Declared at beginning of program
  • Store in Global Data Section of memory
  • Scope is entire program
  • Initialized to zero

/ begin block / int chimp ...
39
Literals
  • int literals
  • float and double literals
  • char literals

1234 -5678 --Decimal0x2faced 0xFFFE
--Hexadecimal
3.14159 -1.414 --Fixed-point6.55E23
-7.35E51 --Fraction, exponent19.9E-5 -5.28E-21
A B a b --Characters\0 \030
\377 --ASCII (in octal)\n
--newline
40
Style recommendations
  • Make your variable names meaningful.
  • Encapsulate your variables.
  • Avoid global variables.
  • Keep declarations as close as you can to where
    you use the variables keep the scope as small as
    you can.
  • Its better to explicitly pass parameters to
    procedures, rather than use global variables to
    pass data. Ditto for procedure results.

41
Operators
  • Assignment ()
  • changes the values of variables
  • Arithmetic (, -, , /)
  • add, subtract, multiply, divide
  • Bitwise (, , , )
  • AND, OR, XOR, NOT, and shifts on Integers
  • Relational (, gt, lt, gt, lt, !)
  • equality, inequality, less-than, etc.
  • Logical (!, , )
  • NOT, AND, OR on Booleans
  • Increment/Decrement (, --)

C supports a rich set of operators that allow the
programmer to manipulate variables
42
Operators and Expressions
  • Expressions are formed by combining variable and
    literal values with operators.
  • Expressions ALWAYS return a value in C.
  • A statement is a complete sentence in C and
    often includes an expression, but not always.
    Statements ALWAYS end in either a semicolon
    or a closing brace .
  • int i
  • int i 4
  • i 5
  • i lt j
  • a (a lt b)
  • while(0)

43
The Assignment Operator
  • The operator symbol is the equal sign

variable expression
  • The expression on the right-hand side is
    evaluated
  • The value is assigned to the left-hand variable
  • Different meaning than in Mathematics
  • In Math, X Y asserts that X and Y are the same
    value
  • In C, X Y changes the value of X to be the same
    as Y

44
The Assignment Operator
AND R2, R2, 0 ADD R2, R2, 9 STR R2, R6,
-3 ... LDR R2, R6, -3 ADD R2, R2, 4 STR R2,
R6, -3
45
Arithmetic Operators
x y x y x y x / y x y
  • Add
  • Subtract
  • Multiply
  • Divide /
  • int integer division 5 / 3 1 (truncated to
    int)
  • float 5.0 / 3.0 1.66666666
  • Modulus
  • int remainder after integer division 5 3 2

46
Coercion
  • How do expressions with different types get
    evaluated?

int num1 5 double num2 1.5 int num3
num1/num2
What will be the value of num3?
47
Coercion
  • When executing expressions of mixed types, C
    automatically converts integer to floating point
    and back again as needed.

48
Coercion
  • How do expressions with different types get
    evaluated?

int num1 5 double num2 1.5 int num3
num1/num2
What will be the value of num3?
num1 gets promoted to a double 5.0 / 1.5 gt
3.33333333 num3 is an int the division is
truncated gt 3
49
Order of Evaluation
  • Precedence
  • The order in which operators and expressions are
    evaluated
  • Associativity
  • The order which in which operators of the same
    precedence are evaluated
  • Left to Right for , , , /,
  • Right to Left for some other operators
  • Parentheses ( )
  • Override the evaluation rules

50
Order of Evaluation
  • Precedence (, /, ) gt (, )

a - b / c d e f
Even with precedence, use of parentheses can make
code more readable. Stylistically, it is
preferable to use parentheses even when they are
not needed.
51
Bitwise Operators Logical
  • Perform logical operations across individual bits
    of a value.
  • AND
  • OR
  • XOR
  • NOT

x 1 0 1 0 (binary) y 1 1 0 0
(binary) x y 1 0 0 0 (binary) x y 1 1 1 0
(binary) x y 0 1 1 0 (binary) x 0 1 0 1
(binary)
52
Bitwise Operators Shifts
  • SHIFT LEFT ltlt
  • SHIFT RIGHT gtgt

x ltlt y shift x y-places to the left
add zeros on the right x gtgt y shift x y-places
to the right sign extend on the left
53
Relational Operators
  • Relational operators return Boolean values
  • 0 if relation is False
  • 1 if relation is True
  • Comparisons
  • x y equality
  • x ! y inequality
  • x lt y less-than
  • x lt y less-than-or-equal
  • x gt y greater-than
  • x gt y greater-than-or-equal
  • Used most often in if-statements
  • if(expression) statement

54
Mistake 1 Beware!
if(x 1) / assign x to 1, and ... /
statement / always execute statement /
if(x 1) / if x is 1 then ... /
statement / execute statement /
Most of you will make this mistake this semester.
Some of you will spend hours trying to find it.
55
Logical Operators
  • Dont confuse with Bitwise operators
  • Logical Operators take Boolean inputs and produce
    Boolean outputs
  • Boolean inputs (how values are interpreted)
  • Value ! 0 ? True
  • Value 0 ? False
  • Boolean outputs
  • True ? 1
  • False ? 0

56
Logical Operators
  • AND
  • OR
  • NOT !

f g f g !f
(10 20) ? 1(10 0) ? 0 if(!x)
statementif(x 0) statement
if(x) statementif(x ! 0) statement
57
More Examples with Logical Ops
char x / print x only if it is a letter / if(
((a lt x) (x lt z)) ((A lt x)
(x lt Z)) ) printf(c, x) if( a lt x
lt z ) statement / wrong / if( (a lt x)
(x lt z)) statement
58
Increment and Decrement Operators
  • x post-increment
  • x pre-increment
  • x-- post-decrement
  • --x pre-decrement

59
Combination Assignment Operators
  • Arithmetic and bitwise operators combined with
    the assignment operator.

x y ?? x x yx - y ?? x x
yx y ?? x x yx / y ?? x
x / yx y ?? x x yx y ??
x x yx y ?? x x yx
y ?? x x yx ltlt y ?? x x ltlt
yx gtgt y ?? x x gtgt y
60
Conditional Expressions
  • The conditional expression does a multiplexor
    operation in C

x ? y z This expression returns the value of
y if x!0otherwise it returns the value of z
61
Conditional Expressions
  • The conditional expression simplifies an if
    else structure

if (x gt 0) y 1 else y 2
y (x gt 0) ? 1 2
62
Literals, Constants, and Symbolic Values
  • Literals
  • Unnamed constant values used in programs
  • area 3.14159 radius radius
  • Constants
  • Variable declarations with prefixed with the
    const qualifier
  • const double pi 3.14159
  • area pi radius radius
  • Symbolic Values
  • Created using preprocessor directive define
  • define PI 3.14159
  • area PI radius radius

63
Operator Precedence and Associativity
64
Operator Precedence
  • Evaluate the following expressions

x 10 y 2 z 3
x y 1
x y z-- 2
65
Operator Precedence
  • Evaluate the following expressions

x 10 y 2 z 3
x y 1
x y z-- 2
x x (y 1) x 10 (2 1) x 30
y 3 x x (y z 2) x 10 (3 3
2) x 10 (11) x 110 z 2
66
The C Symbol Table
  • The C compiler keeps track of variables in a
    program with a symbol table
  • A symbol table entry is created when a variable
    is declared.
  • Each entry contains
  • Variable name
  • Variable type (int, float, char, etc.)
  • Variable storage class (auto, static)
  • Where in memory variable is stored (an offset)
  • An identifier to indicate the variables scope

67
Compiling a Program
C Source Code
Source Code Analysis
Symbol Table
Code Generation
68
LC-3 Memory Layout
0x0000
Trap Vector Table
0x0100
Interrupt Vector Table
0x0200
Trap / Interrupt Routines
Operating System
0x3000
Program Code
Global Data Section(Global and Static vars)
Heap(Dynamically allocated vars)
Run-Time Stack(Local and Auto vars)
0xFE00
I/O Space
0xFFFF
69
Frames
  • A frame (also called an activation record) is a
    local data storage area allocated on the stack
    each time a subroutine is called.
  • A frame is allocated immediately following the
    register storage.
  • Frame variables are for temporary storage and are
    lost when the subroutine returns.
  • R5 is the designated frame pointer register.
  • Data is stored and retrieved via indexed R5
    instructions.
  • LDR R1, R5, -6 get L0 variable
  • STR R1, R5, -7 make copy in L1

70
Allocating Space for LC-3 Variables
  • Static storage class
  • Global Variables
  • Static Variables
  • Automatic storage class
  • Local Variables

An activation record is a block of memory on the
stack that is created when a function is
called.It contains all the local variables for a
given invocation of a function.It will be
covered in detail in chapter 14.
71
LC-3 C Compiler Conventions
  • Register usage
  • R0 parameter passing
  • R1-R3 scratch registers
  • R4 global frame pointer
  • R5 frame pointer (to activation record)
  • R6 stack pointer
  • R7 return address

72
C to LC-3 Assembly Example 1
AND R0, R0, 0 ADD R0, R0, 7 STR R0, R5, 0
0(FP)x AND R0, R0, 0 ADD R0, R0, 5 STR
R0, R5, -1 -1(FP)y AND R0, R0, 0 LDR R1,
R5, 0 R1 lt- x LDR R2, R5, -1 R2 lt-
y LOOP BRZ DONE mul loop ADD R0, R0,
R1 ADD R2, R2, -1 BR LOOP DONE STR R0, R5,
-2 -2(FP)z
unsigned int x 7 unsigned int y 5
unsigned int z z x y ...
73
C to LC-3 Assembly Example 2
LDR R0, R5, 0 Get value of x ADD R0, R0, 4
Compute x4 STR R0, R5, 0 Save result in x
x x 4
74
C to LC-3 Assembly Example 3
R4
0x0000
inGlobal
Global Data
int inGlobal int
main()
int inLocal int
outLocalA int
outLocalB
.
.
.
Activation Record
outLocalB
outLocalA
0xFFFF
R5
inLocal
75
C to LC-3 Assembly Example 3
/ Initialize / inLocal 5
AND R0, R0, 0
ADD R0, R0, 5
STR R0, R5, 0
inGlobal 3 AND R0,
R0, 0
ADD R0, R0, 3
STR R0, R4, 0 / Compute /
outLocalA inLocal inGlobal LDR R0,
R5, 0
LDR R1, R4, 0
NOT R1, R1
AND R2, R0, R1
STR R2, R5, -1
76
C to LC-3 Assembly Example 3
outLocalB (inLocal inGlobal) LDR
R0, R5, 0
LDR R1, R4, 0
ADD R0, R0, R1 (inLocal
inGlobal) LDR R2, R5, 0
LDR R3, R4, 0
NOT R3
ADD R3, R3,
1 ADD
R2, R3, R2
NOT R2
ADD R2, R2, 1
ADD R0, R0, R2
STR R0, R5, -2 / Print
results / printf(outLocalA d,
outLocalBd\n, ltcode to call outLocalA,
outLocalB) printfgt
ltfinish-up
codegt
RET
Write a Comment
User Comments (0)
About PowerShow.com