Tuesday, March 27, 2007

WASE BITS-WIPRO SESSION 9 DT:25-03-07

Chapter 11Introduction toProgramming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.

It is a general purpose programming language.

C is not tied to any particular hardware or system.

BCPL and B are type less languages while C is has data types.

C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded

In C % operator can not be applied on float.

In C % operator can not be applied with real operands.

% operator takes the sign of the I operand.

Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.

If one of them is negative then direction of truncation is implementation dependant. That is

-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions

Robust: built in functions, operators, middle level features

Efficient: data types and operators

Extensible: libraries, functions can be added

Portable: Can be run on any machine

Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.

Comments do not effect the execution size and speed.

Comments aid in debugging and testing.

C is a case sensitive language

\n à new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Functionfunction Heading(Argument list)
• Compound statementcompound statement = { …..}{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/

Structure of a C Program
• Documentationnesting of comments not allowed
• Definition symbolic constants
• Link sectionlinks header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }



Structure…
The program will always begin by executing the main function.

The format of a C Program is

main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces

Tokens are smallest individual units of C. There are six tokens: Keywords, Identifiers, strings, special symbols, constants,Operators

Keywords: In ANSI C there are 32 keyword

Identifiers: names of variables, functions and arrays.

Strings: sequence of characters surrounded by double quotes.
keywords
Auto break case char const

char continue default do double

else enum extern float for

goto if int long register

return short signed sizeof static

struct switch typedef union unsigned

void volatile while

Constants and variables
Special symbols: @,#,$,^

Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• NumericIntegerReal
• CharacterSingleString


Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.

Integers may be decimal(0..9), octal(0..7), hex(0..15)

Real: Fractional parts represented using mantissa and
exponent form

Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’

Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.

Backslash character constants: escape sequences like /n, /t, /f.


Variables
Variables are data names for data types.

They change during the execution of programs.

Variable names start with a letter or underscore.

variable length is 31 characters, usage is 8 characters.

variable name must not be a keyword.

White spaces are not allowed.


Data types
ANSI C supports four classes of data types

• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values


Data types.. Sizes and ranges
• Charà 1 byte. -128 to 127
• Intà 2 bytes. -32768 to 32767
• Floatà 4 bytes 3.4e-38 to 3.4e+38
• Doubleà 8 bytes. 1.7e-308 to 1.7e+308


Preprocessor directives
#include

#include indicates to the compiler the nature of the library functions being used like printf().

Stdio.h is a header file consisting of library functions like printf() and scanf()

Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.

#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);

#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);

#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1

Int 2 signed int 2 unsigned int 2

short int 2 long int 4

Float 4

Double 8 long double 10
Data types

Sizeof() is a special operator which gives the size of the data

sizeof(char) 1

sizeof(int) 2

sizeof(float) 4

sizeof(double) 8

File.cà compileà file.objà linkà file.exe

Int data type occupies how many bytes…

.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &amp;width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h

Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch()à does not echo character to screen.

Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x)à %d %e %f %g %i %o

%u %x %D %E %G %O %I %X %U

%field width format specifier printf(“%10f”,num);

%field width.precision format code printf(“%12.5”,num);
ALGORITHM

Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.

Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.

Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
ALGORITHM
Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
ALGORITHM
Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm
FLOWCHART
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:
FLOWCHART SYMBOLS
..\cds lab theory pavan sir's.DOC
Some examples c1.doc
#include

main()

{
clrscr();
printf("%d\n",43);
printf("%d\n",43+59);
printf("%x\n",102);
printf("%o\n",102);
}



#include
int m; /* global variable*/
main()
{
int i; /*local variable*/
float b;
f1();
}
f1()
{
int i; /*local variable*/
}

/* one i does not affect another i */


typedef int a;

typedef float b;

a x,y,z;

b p,q,r;


#include
main()
{
int a=10;
float x=3.142;
clrscr();
printf("%f\n",a);
printf("%d\n",sizeof(x));
printf("%d\n",sizeof(double));
}

#include
main()
{
int x=10;
char y;
clrscr();
y=(x==10?'A':'B');
printf("%d\n",y);
}


#include
main()
{
float i=10.0,k;
clrscr();
k=i%2;
printf("%d\n",k);
}

#include
main()
{ clrscr();
printf("%d",sizeof('8'));
}


include
main()
{
int i=32769;
clrscr();
printf("%d\n",i);
}


#include
main()
{
int i=10,j=20,k;
clrscr();
k=(i>j?30:40);
printf("%d",k);
}
PROGRAM DEVELOPMENT STAGES:

a) Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.
b) Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.
c) Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
d) Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
e) Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
f) Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm.

FLOWCHART:
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:









FLOWCHART SYMBOLS:



Oval Terminal start/stop/begin/end

Making data available for
Input/ processing(Input) or
Parallelogram Output recording of the process


Document Print out Show data output in the
Form of document


Any processing to be done
A process changes or
Rectangle Process moves data. An
assignment
Operation.

Decision or switching type
Diamond Decision of operations.


Used to connect different
Circle Connector parts of flowchart.


Joins two symbols and
Arrow Flow also represents flow of
Execution.


Bracket with Annotation Descriptive comments or
Broken line explanation.



Double sided Predefined Modules or subroutines
Rectangle process specified elsewhere.

Sunday, February 18, 2007

WASE BITS-WIPRO SESSION6 DT:18-02-07

VENUE : WIPRO
AUDIENCE : 2006 BATCH

Chapter 11Introduction toProgramming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.

It is a general purpose programming language.

C is not tied to any particular hardware or system.

BCPL and B are type less languages while C is has data types.

C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded

In C % operator can not be applied on float.

In C % operator can not be applied with real operands.

% operator takes the sign of the I operand.

Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.

If one of them is negative then direction of truncation is implementation dependant. That is

-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions

Robust: built in functions, operators, middle level features

Efficient: data types and operators

Extensible: libraries, functions can be added

Portable: Can be run on any machine

Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.

Comments do not effect the execution size and speed.

Comments aid in debugging and testing.

C is a case sensitive language

\n à new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Functionfunction Heading(Argument list)
• Compound statementcompound statement = { …..}{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/

Structure of a C Program
• Documentationnesting of comments not allowed
• Definition symbolic constants
• Link sectionlinks header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }



Structure…
The program will always begin by executing the main function.

The format of a C Program is

main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces

Tokens are smallest individual units of C. There are six tokens Keywords, Identifiers, strings, special, constants..

Keywords: In ANSI C there are 32 keyword

Identifiers: names of variables, functions and arrays.

Strings: sequence of characters surrounded by double quotes.
Constants and variables
Special symbols:

Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• NumericIntegerReal
• CharacterSingleString


Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.

Integers may be decimal(0..9), octal(0..7), hex(0..15)

Real: Fractional parts represented using mantissa and
exponent form

Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’

Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.

Backslash character constants: escape sequences like /n, /t, /f.


Variables
Variables are data names for data types.

They change during the execution of programs.

Variable names start with a letter or underscore.

variable length is 31 characters, usage is 8 characters.

variable name must not be a keyword.

White spaces are not allowed.


Data types
ANSI C supports four clesses of data types

• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values


Data types.. Sizes and ranges
• Charà 1 byte. -128 to 127
• Intà 2 bytes. -32768 to 32767
• Floatà 4 bytes 3.4e-38 to 3.4e+38
• Doubleà 8 bytes. 1.7e-308 to 1.7e+308


Preprocessor directives
#include

#include indicates to the compiler the nature of the library functions being used like printf().

Stdio.h is a header file consisting of library functions like printf() and scanf()

Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.

#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);

#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);

#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1

Int 2 signed int 2 unsigned int 2

short int 2 long int 4

Float 4

Double 8 long double 10
Data types

Sizeof() is a special operator which gives the size of the data

sizeof(char) 1

sizeof(int) 2

sizeof(float) 4

sizeof(double) 8

File.cà compileà file.objà linkà file.exe

Int data type occupies how many bytes…

.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h

Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch()à does not echo character to screen.

Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x)à %d %e %f %g %i %o

%u %x %D %E %G %O %I %X %U

%field width format specifier printf(“%10f”,num);

%field width.precision format code printf(“%12.5”,num);

Sunday, February 11, 2007

WASE BITS-WIPRO SESSION 5 DT:11-02-07

Audience: wase 2006 batch
venue : wipro gachibowli
resources : Patt Patel ppts

Session 5The LC-3 Program
types

Type of operands : Addresses, numbers, characters, logical data

Type of of operations:
A. Data Transfer: Move, load, store
B. Arithmetic: Add, Subtract
C. Logical: AND, OR, NOT
D. Transfer of Control: JUMP, RET, HALT
E. I/O: Input
F. Conversion: Convert
Addressing Modes
• Immediate
• Direct
• Indirect
• Register
• Register Indirect
• Displacement
• Stack

An addressing mode specifies how to calculate the effective memory address of an operand by using information held in registers and/or constants contained within a machine instruction or elsewhere.
Addressing Modes
• Immediate add reg1 reg2 constant reg1 := reg2 + constant;
MOV AX, 0005H

Operand is present in the register. Immediate addressing is used to declare constants or variables
Addressing modes

b. Direct

load reg, address

MOVE AX, [5000H]à effective address

Disadvantage is limited address space.
Addressing Modes

c. Indirect

MOV AX, [BX]
POINTERS

d. register
MOV BX, AX
e. register Indirect : MOV AX, [BX]
f. displacement : MOV AX, 50H[BX]
g. stack addressing:
LC-3 Overview: Instruction Set
Opcodes
• 15 opcodes
• Operate instructions: ADD, AND, NOT
• Data movement instructions: LD, LDI, LDR, LEA, ST, STR, STI
• Control instructions: BR, JSR/JSRR, JMP, RTI, TRAP
• some opcodes set/clear condition codes, based on result:
Ø N = negative, Z = zero, P = positive (> 0)
Data Types
• 16-bit 2’s complement integer
Addressing Modes
• How is the location of an operand specified?
• non-memory addresses: immediate, register
• memory addresses: PC-relative, indirect, base+offset
Operate Instructions
Only three operations: ADD, AND, NOT

Source and destination operands are registers
• These instructions do not reference memory.
• ADD and AND can use “immediate” mode,where one operand is hard-wired into the instruction.

Will show dataflow diagram with each instruction.
• illustrates when and where data moves to accomplish the desired operation

NOT (Register)
ADD/AND (Register)
ADD/AND (Immediate)
Data Movement Instructions
Load -- read data from memory to register
• LD: PC-relative mode
• LDR: base+offset mode
• LDI: indirect mode

Store -- write data from register to memory
• ST: PC-relative mode
• STR: base+offset mode
• STI: indirect mode

Load effective address -- compute address, save in register
• LEA: immediate mode
• does not access memory
LD (PC-Relative)
LDI (Indirect)
LDR (Base+Offset)
LEA (Immediate)
Control Instructions
Used to alter the sequence of instructions(by changing the Program Counter)

Conditional Branch
• branch is taken if a specified condition is true
Ø signed offset is added to PC to yield new PC
• else, the branch is not taken
Ø PC is not changed, points to the next sequential instruction
Unconditional Branch (or Jump)
• always changes the PC
TRAP
• changes PC to the address of an OS “service routine”
• routine will return control to the next instruction (after TRAP)
Condition Codes
LC-3 has three condition code registers: N -- negative Z -- zero P -- positive (greater than zero)

Set by any instruction that writes a value to a register(ADD, AND, NOT, LD, LDR, LDI, LEA)

Exactly one will be set at all times
• Based on the last instruction that altered a register
Branch Instruction
Branch specifies one or more condition codes.
If the set bit is specified, the branch is taken.
• PC-relative addressing:target address is made by adding signed offset (IR[8:0])to current PC.
• Note: PC has already been incremented by FETCH stage.
• Note: Target must be within 256 words of BR instruction.

If the branch is not taken,the next sequential instruction is executed.
BR (PC-Relative)
TRAP
Calls a service routine, identified by 8-bit “trap vector.”





When routine is done, PC is set to the instruction following TRAP.
(We’ll talk about how this works later.)

Another Example
Count the occurrences of a character in a file
• Program begins at location x3000
• Read character from keyboard
• Load each character from a “file”
Ø File is a sequence of memory locations
Ø Starting address of file is stored in the memory locationimmediately after the program
• If file character equals input character, increment counter
• End of file is indicated by a special ASCII value: EOT (x04)
• At the end, print the number of characters and halt(assume there will be less than 10 occurrences of the character)

A special character used to indicate the end of a sequenceis often called a sentinel.
• Useful when you don’t know ahead of time how many timesto execute a loop.
Flow Chart
Char Count in Assembly Language (1 of 3)
;
; Program to count occurrences of a character in a file.
; Character to be input from the keyboard.
; Result to be displayed on the monitor.
; Program only works if no more than 9 occurrences are found.
;
;
; Initialization
;
.ORIG x3000
AND R2, R2, #0 ; R2 is counter, initially 0
LD R3, PTR ; R3 is pointer to characters
GETC ; R0 gets character input
LDR R1, R3, #0 ; R1 gets first character
;
; Test character for end of file
;
TEST ADD R4, R1, #-4 ; Test for EOT (ASCII x04)
BRz OUTPUT ; If done, prepare the output
Char Count in Assembly Language (2 of 3)
;
; Test character for match. If a match, increment count.
;
NOT R1, R1
ADD R1, R1, R0 ; If match, R1 = xFFFF
NOT R1, R1 ; If match, R1 = x0000
BRnp GETCHAR ; If no match, do not increment
ADD R2, R2, #1
;
; Get next character from file.
;
GETCHAR ADD R3, R3, #1 ; Point to next character.
LDR R1, R3, #0 ; R1 gets next char to test
BRnzp TEST
;
; Output the count.
;
OUTPUT LD R0, ASCII ; Load the ASCII template
ADD R0, R0, R2 ; Covert binary count to ASCII
OUT ; ASCII code in R0 is displayed.
HALT ; Halt machine

Program (1 of 2)
Program (2 of 2)
Problem solving
Problem solving
clarifying description of the problem, analyzing causes, identifying alternatives, assessing each alternative, choosing one, implementing it, and evaluating whether the problem was solved or not.

•Define the problem
•Analyze the problem
•Isolate the task knowledge to solve the problem
•Choose the best problem solving technique

Problem solving
•What is the input
•What should be the output
•Procedure to convert the input to output
•Logic
•Understand the syntax of the tool being used
•The procedure should have a good control strategy


Problem solving techniques
Stepwise refinement
Starting from the requirements, at each step one constructs a more concrete description of the system and verifies it against the specification constructed in the previous step until one arrives at the implementation.

Programming is different from coding.

Programming is a sequence of design decisions concerning the decomposition of tasks into subtasks and of data into data structures.


Stepwise refinement

it is a software development technique that imposes a hierarchical structure on the design of the program. It starts out by defining the solution at the highest level of functionality and breaking it down further and further into small routines that can be easily documented and coded.

It is also called as top down programming

Techniques that impose a logical structure on the writing of a program. Large routines are broken down into smaller, modular routines .
constructs
• Sequential
• Conditional
• Iterative


Back to number system
Converting binary fraction to decimal fraction

1) 0.1101 =

= 1 x 2-1 + 1 x 2-2 + 0 x 2-3 + 1 X 2-4

=1/2 + ¼ + 0 + 1/16

= 0.8125

2) 1101.1010 = ?
NUMBER SYSTEM
CONVERTING DECIMAL FRACTION TO BINARY FRACTION

• 0.8125 =
FRACTION FR X 2 REM INTEGER
0.8125 1.625 0.625 1 MSB
0.625 1.25 0.25 1
0.25 0.50 0.50 0
0.50 1.00 0.00 1LSB



2) 0.635= ?

3) 12.625 = ?
4. Floating Point Numbers
Exponential Notation
• The following are equivalent representations of 1,234
Parts of a Floating Point Number
-0.9876 x 10-3
IEEE 754 Standard
• Most common standard for representing floating point numbers
• Single precision: 32 bits, consisting of...
• Sign bit (1 bit)
• Exponent (8 bits)
• Mantissa (23 bits)
• Double precision: 64 bits, consisting of…
• Sign bit (1 bit)
• Exponent (11 bits)
• Mantissa (52 bits)

Single Precision Format
Normalization
• The mantissa is normalized
• Has an implied decimal place on left
• Has an implied “1” on left of the decimal place
• E.g.,
• Mantissa ®
• Represents…
Excess Notation
• To include +ve and –ve exponents, “excess” notation is used
• Single precision: excess 127
• Double precision: excess 1023
• The value of the exponent stored is larger than the actual exponent
• E.g., excess 127,
• Exponent ®
• Represents…
Example
• Single precision
Hexadecimal
• It is convenient and common to represent the original floating point number in hexadecimal
• The preceding example…

Converting from Floating Point
• E.g., What decimal value is represented by the following 32-bit floating point number?






Converting to Floating Point
• E.g., Express 36.562510 as a 32-bit floating point number (in hexadecimal)


• Step 2
• Normalize

• Step 3
• Determine S, E, and M

• Step 4
• Put S, E, and M together to form 32-bit binary result

• Step 5
• Express in hexadecimal
Chapter 11Introduction toProgramming in C
C: A High-Level Language
Gives symbolic names to values
• don’t need to know which register or memory location
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Compiling and Linking
Various compilers available
• cc, gcc
• includes preprocessor, compiler, and linker

Lots and lots of options!
• level of optimization, debugging
• preprocessor, linker options
• intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc.

Remaining Chapters
A more detailed look at many C features.
• Variables and declarations
• Operators
• Control Structures
• Functions
• Data Structures
• I/O

Emphasis on how C is converted to
LC-3 assembly language.

Also see C Reference in Appendix D.
Chapter 6Programming
Solving Problems using a Computer
Methodologies for creating computer programsthat perform a desired function.

Problem Solving
• How do we figure out what to tell the computer to do?
• Convert problem statement into algorithm,using stepwise refinement.
• Convert algorithm into LC-3 machine instructions.
Debugging
• How do we figure out why it didn’t work?
• Examining registers and memory, setting breakpoints, etc.
Stepwise Refinement
Also known as systematic decomposition.

Start with problem statement:
“We wish to count the number of occurrences of a characterin a file. The character in question is to be input fromthe keyboard; the result is to be displayed on the monitor.”

Decompose task into a few simpler subtasks.

Decompose each subtask into smaller subtasks,and these into even smaller subtasks, etc....until you get to the machine instruction level.
Problem Statement
Because problem statements are written in English,they are sometimes ambiguous and/or incomplete.
• Where is “file” located? How big is it, or how do I knowwhen I’ve reached the end?
• How should final count be printed? A decimal number?
• If the character is a letter, should I count bothupper-case and lower-case occurrences?

How do you resolve these issues?
• Ask the person who wants the problem solved, or
• Make a decision and document it.
Three Basic Constructs
There are three basic ways to decompose a task:
Sequential
Do Subtask 1 to completion,then do Subtask 2 to completion, etc.
Conditional
If condition is true, do Subtask 1;else, do Subtask 2.
Iterative
Do Subtask over and over, as long as the test condition is true.
Problem Solving Skills
Learn to convert problem statementinto step-by-step description of subtasks.
• Like a puzzle, or a “word problem” from grammar school math.
Ø What is the starting state of the system?
Ø What is the desired ending state?
Ø How do we move from one state to another?
• Recognize English words that correlate to three basic constructs:
Ø “do A then do B” Þ sequential
Ø “if G, then do H” Þ conditional
Ø “for each X, do Y” Þ iterative
Ø “do Z until W” Þ iterative
LC-3 Control Instructions
How do we use LC-3 instructions to encodethe three basic constructs?

Sequential
• Instructions naturally flow from one to the next,so no special instruction needed to gofrom one sequential subtask to the next.

Conditional and Iterative
• Create code that converts condition into N, Z, or P.Example: Condition: “Is R0 = R1?” Code: Subtract R1 from R0; if equal, Z bit will be set.
• Then use BR instruction to transfer control to the proper subtask.
Code for Conditional
Code for Iteration
Example: Counting Characters
Refining B
Refining B1
Refining B2 and B3
The Last Step: LC-3 Instructions
Use comments to separate into modules and to document your code.
Debugging
You’ve written your program and it doesn’t work.
Now what?

What do you do when you’re lost in a city?
• Drive around randomly and hope you find it?
PReturn to a known point and look at a map?

In debugging, the equivalent to looking at a mapis tracing your program.
• Examine the sequence of instructions being executed.
• Keep track of results being produced.
• Compare result from each instruction to the expected result.
Debugging Operations
Any debugging environment should provide means to:
• Display values in memory and registers.
• Deposit values in memory and registers.
• Execute instruction sequence in a program.
• Stop execution when desired.

Different programming levels offer different tools.
• High-level languages (C, Java, ...)usually have source-code debugging tools.
• For debugging at the machine instruction level:
Ø simulators
Ø operating system “monitor” tools
Ø in-circuit emulators (ICE)
– plug-in hardware replacements that give instruction-level control
LC-3 Simulator
Types of Errors
Syntax Errors
• You made a typing error that resulted in an illegal operation.
• Not usually an issue with machine language,because almost any bit pattern corresponds tosome legal instruction.
• In high-level languages, these are often caught during thetranslation from language to machine code.
Logic Errors
• Your program is legal, but wrong, so the results don’t match the problem statement.
• Trace the program to see what’s really happening anddetermine how to get the proper behavior.
Data Errors
• Input data is different than what you expected.
• Test the program with a wide variety of inputs.
Tracing the Program
Execute the program one piece at a time,examining register and memory to see results at each step.
Single-Stepping
• Execute one instruction at a time.
• Tedious, but useful to help you verify each step of your program.
Breakpoints
• Tell the simulator to stop executing when it reachesa specific instruction.
• Check overall results at specific points in the program.
Ø Lets you quickly execute sequences to get ahigh-level overview of the execution behavior.
Ø Quickly execute sequences that your believe are correct.
Watchpoints
• Tell the simulator to stop when a register or memory location changes or when it equals a specific value.
• Useful when you don’t know where or when a value is changed.
Example 1: Multiply
This program is supposed to multiply the two unsignedintegers in R4 and R5.
Debugging the Multiply Program
Example 2: Summing an Array of Numbers
This program is supposed to sum the numbersstored in 10 locations beginning with x3100,leaving the result in R1.
Debugging the Summing Program
Running the the data below yields R1 = x0024,but the sum should be x8135. What happened?
Example 3: Looking for a 5
This program is supposed to setR0=1 if there’s a 5 in one ten memory locations, starting at x3100.
Else, it should set R0 to 0.
Debugging the Fives Program
Running the program with a 5 in location x3108results in R0 = 0, not R0 = 1. What happened?
Example 4: Finding First 1 in a Word
This program is supposed to return (in R1) the bit position of the first 1 in a word. The address of the word is in location x3009 (just past the end of the program). If thereare no ones, R1 should be set to –1.
Debugging the First-One Program
Program works most of the time, but if data is zero,it never seems to HALT.
Debugging: Lessons Learned
Trace program to see what’s going on.
• Breakpoints, single-stepping

When tracing, make sure to notice what’s really happening, not what you think should happen.
• In summing program, it would be easy to not noticethat address x3107 was loaded instead of x3100.

Test your program using a variety of input data.
• In Examples 3 and 4, the program works for many data sets.
• Be sure to test extreme cases (all ones, no ones, ...).

Monday, February 5, 2007

wase-bits structured programming session 4 date 04-02-07

resources : patt patel ppts
audience: wase 2006 batch

Chapter 5The LC-3
Instruction Set Architecture
ISA = All of the programmer-visible components and operations of the computer
• memory organization
Ø address space -- how may locations can be addressed?
Ø addressibility -- how many bits per location?
• register set
Ø how many? what size? how are they used?
• instruction set
Ø opcodes
Ø data types
Ø addressing modes
ISA provides all information needed for someone that wants towrite a program in machine language (or translate from a high-level language to machine language).
Instruction Set
Instruction execution means CPU operation.

Instruction set are the functional requirement for the CPU.

With instruction set a programmer becomes aware of register, memory organization, type of data and functionality of ALU.

An instruction consists of OPCODES and Operands. Opcodes specify the operation to be performed.

Collection of instructions is instruction set

Instruction Set
Opcodes use mnemonics like Add, Subtract.

A typical instruction format:

4 bits 6 bits 6 bits
opcode oper1 oper2

1 bit 2 bits 1 bit 3 bits
sign opcode register momory
Instruction format

8 bits 8 bits
Opcode-6 bits d-1bit w-1 bit mod-2 bits reg- 3 bits r/m-3

d === 0 register is source else destination

w=== 0 8bit else 16 bit

mod === 00,01,10,11 + r/m specify the addressing mode
Instruction format

MOV AX, BX


OPCODE D W MOD REG R/M

100010 1 1 11 000 011=== 8BC3H

REGISTER IS DST, LENGTH IS 16 BITS, I OPERAND IS REGISTER, REGISTER IS AX, ADDRESSING IS REGISTER
Instruction types

The number of addresses required may vary but still each instruction has a source, a destn, result, next instr so four -4- addresses may be required.
Next instruction address if implied three -3- addresses are required.
If result stored in the destn two -2- addresses are required.
If accumulator is used one -1- address is required.
If stack are used zero addresses are required.
types

Type of operands : Addresses, numbers, characters, logical data

Type of of operations:
A. Data Transfer: Move, load, store
B. Arithmetic: Add, Subtract
C. Logical: AND, OR, NOT
D. Transfer of Control: JUMP, RET, HALT
E. I/O: Input
F. Conversion: Convert
Addressing Modes
•Immediate
•Direct
•Indirect
•Register
•Register Indirect
•Displacement
•Stack

An addressing mode specifies how to calculate the effective memory address of an operand by using information held in registers and/or constants contained within a machine instruction or elsewhere.
Addressing Modes
•Immediate add reg1 reg2 constant reg1 := reg2 + constant;
MOV AX, 0005H

Operand is present in the register. Immediate addressing is used to declare constants or variables
Addressing modes

b. Direct

load reg, address

MOVE AX, [5000H]à effective address

Disadvantage is limited address space.
Addressing Modes

c. Indirect

MOV AX, [BX]
POINTERS

d. register
MOV BX, AX
e. register Indirect : MOV AX, [BX]
f. displacement : MOV AX, 50H[BX]
g. stack addressing:
Instruction length
8 bit 16 bit 32 bit 64 bit

Programmers want more addresses, more operands

But if we have 64 bits it is a waste of memory.

Opcodes can all be of same length or variable lengths
Instruction Formats

MOV AX, 25H

1011 W REG 16-BIT-DATA

1011 1 000 0025H=== B80025H

LC-3 Overview: Memory and Registers
Memory
• address space: 216 locations (16-bit addresses) 65536 addresses
• addressability: 16 bits

Registers
• temporary storage, accessed in a single machine cycle
Ø accessing memory generally takes longer than a single cycle
• eight general-purpose registers: R0 - R7
Ø each 16 bits wide
Ø how many bits to uniquely identify a register?
• other registers
Ø not directly addressable, but used by (and affected by) instructions
Ø PC (program counter), condition codes
LC-3 Overview: Instruction Set
Opcodes
• 15 opcodes
• Operate instructions: ADD, AND, NOT
• Data movement instructions: LD, LDI, LDR, LEA, ST, STR, STI
• Control instructions: BR, JSR/JSRR, JMP, RTI, TRAP
• some opcodes set/clear condition codes, based on result:
Ø N = negative, Z = zero, P = positive (> 0)
Data Types
• 16-bit 2’s complement integer
Addressing Modes
• How is the location of an operand specified?
• non-memory addresses: immediate, register
• memory addresses: PC-relative, indirect, base+offset
Operate Instructions
Only three operations: ADD, AND, NOT

Source and destination operands are registers
• These instructions do not reference memory.
• ADD and AND can use “immediate” mode,where one operand is hard-wired into the instruction.

Will show dataflow diagram with each instruction.
• illustrates when and where data moves to accomplish the desired operation

NOT (Register)
ADD/AND (Register)
ADD/AND (Immediate)
Using Operate Instructions
With only ADD, AND, NOT…
• How do we subtract?



• How do we OR?


• How do we copy from one register to another?


• How do we initialize a register to zero?
Data Movement Instructions
Load -- read data from memory to register
• LD: PC-relative mode
• LDR: base+offset mode
• LDI: indirect mode

Store -- write data from register to memory
• ST: PC-relative mode
• STR: base+offset mode
• STI: indirect mode

Load effective address -- compute address, save in register
• LEA: immediate mode
• does not access memory
PC-Relative Addressing Mode
Want to specify address directly in the instruction
• But an address is 16 bits, and so is an instruction!
• After subtracting 4 bits for opcodeand 3 bits for register, we have 9 bits available for address.

Solution:
• Use the 9 bits as a signed offset from the current PC.

9 bits:
Can form any address X, such that:

Remember that PC is incremented as part of the FETCH phase;
This is done before the EVALUATE ADDRESS stage.
LD (PC-Relative)
ST (PC-Relative)
Indirect Addressing Mode
With PC-relative mode, can only address data within 256 words of the instruction.
• What about the rest of memory?

Solution #1:
• Read address from memory location,then load/store to that address.

First address is generated from PC and IR(just like PC-relative addressing), thencontent of that address is used as target for load/store.
LDI (Indirect)
STI (Indirect)
Base + Offset Addressing Mode
With PC-relative mode, can only address data within 256 words of the instruction.
• What about the rest of memory?

Solution #2:
• Use a register to generate a full 16-bit address.

4 bits for opcode, 3 for src/dest register,3 bits for base register -- remaining 6 bits are usedas a signed offset.
• Offset is sign-extended before adding to base register.
LDR (Base+Offset)
STR (Base+Offset)
Load Effective Address
Computes address like PC-relative (PC plus signed offset) and stores the result into a register.

Note: The address is stored in the register, not the contents of the memory location.

LEA (Immediate)
Example
Control Instructions
Used to alter the sequence of instructions(by changing the Program Counter)

Conditional Branch
• branch is taken if a specified condition is true
Ø signed offset is added to PC to yield new PC
• else, the branch is not taken
Ø PC is not changed, points to the next sequential instruction
Unconditional Branch (or Jump)
• always changes the PC
TRAP
• changes PC to the address of an OS “service routine”
• routine will return control to the next instruction (after TRAP)
Condition Codes
LC-3 has three condition code registers: N -- negative Z -- zero P -- positive (greater than zero)

Set by any instruction that writes a value to a register(ADD, AND, NOT, LD, LDR, LDI, LEA)

Exactly one will be set at all times
• Based on the last instruction that altered a register
Branch Instruction
Branch specifies one or more condition codes.
If the set bit is specified, the branch is taken.
• PC-relative addressing:target address is made by adding signed offset (IR[8:0])to current PC.
• Note: PC has already been incremented by FETCH stage.
• Note: Target must be within 256 words of BR instruction.

If the branch is not taken,the next sequential instruction is executed.
BR (PC-Relative)
Using Branch Instructions
Compute sum of 12 integers.Numbers start at location x3100. Program starts at location x3000.
Sample Program
JMP (Register)
Jump is an unconditional branch -- always taken.
• Target address is the contents of a register.
• Allows any target address.

TRAP
Calls a service routine, identified by 8-bit “trap vector.”





When routine is done, PC is set to the instruction following TRAP.
(We’ll talk about how this works later.)

Another Example
Count the occurrences of a character in a file
• Program begins at location x3000
• Read character from keyboard
• Load each character from a “file”
Ø File is a sequence of memory locations
Ø Starting address of file is stored in the memory locationimmediately after the program
• If file character equals input character, increment counter
• End of file is indicated by a special ASCII value: EOT (x04)
• At the end, print the number of characters and halt(assume there will be less than 10 occurrences of the character)

A special character used to indicate the end of a sequenceis often called a sentinel.
• Useful when you don’t know ahead of time how many timesto execute a loop.
Flow Chart
Program (1 of 2)
Program (2 of 2)
LC-3 Data PathRevisited
Data Path Components
Global bus
• special set of wires that carry a 16-bit signal to many components
• inputs to the bus are “tri-state devices,”that only place a signal on the bus when they are enabled
• only one (16-bit) signal should be enabled at any time
Ø control unit decides which signal “drives” the bus
• any number of components can read the bus
Ø register only captures bus data if it is write-enabled by the control unit

Memory
• Control and data registers for memory and I/O devices
• memory: MAR, MDR (also control signal for read/write)
Data Path Components
ALU
• Accepts inputs from register fileand from sign-extended bits from IR (immediate field).
• Output goes to bus.
Ø used by condition code logic, register file, memory

Register File
• Two read addresses (SR1, SR2), one write address (DR)
• Input from bus
Ø result of ALU operation or memory read
• Two 16-bit outputs
Ø used by ALU, PC, memory address
Ø data for store instructions passes through ALU
Data Path Components
PC and PCMUX
• Three inputs to PC, controlled by PCMUX
Ø PC+1 – FETCH stage
Ø Address adder – BR, JMP
Ø bus – TRAP (discussed later)

MAR and MARMUX
• Two inputs to MAR, controlled by MARMUX
• Address adder – LD/ST, LDR/STR
• Zero-extended IR[7:0] -- TRAP (discussed later)

Data Path Components
Condition Code Logic
• Looks at value on bus and generates N, Z, P signals
• Registers set only when control unit enables them (LD.CC)
Ø only certain instructions set the codes(ADD, AND, NOT, LD, LDI, LDR, LEA)

Control Unit – Finite State Machine
• On each machine cycle, changes control signals for next phaseof instruction processing
Ø who drives the bus? (GatePC, GateALU, …)
Ø which registers are write enabled? (LD.IR, LD.REG, …)
Ø which operation should ALU perform? (ALUK)
Ø …
• Logic includes decoder for opcode, etc.

Chapter 7Assembly Language
Human-Readable Machine Language
Computers like ones and zeros…

Humans like symbols…


Assembler is a program that turns symbols intomachine instructions.
• ISA-specific:close correspondence between symbols and instruction set
Ø mnemonics for opcodes
Ø labels for memory locations
• additional operations for allocating storage and initializing data
An Assembly Language Program
;
; Program to multiply a number by the constant 6
;
.ORIG x3050
LD R1, SIX
LD R2, NUMBER
AND R3, R3, #0 ; Clear R3. It will
; contain the product.
; The inner loop
;
AGAIN ADD R3, R3, R2
ADD R1, R1, #-1 ; R1 keeps track of
BRp AGAIN ; the iteration.
;
HALT
;
NUMBER .BLKW 1
SIX .FILL x0006
;
.END
LC-3 Assembly Language Syntax
Each line of a program is one of the following:
• an instruction
• an assember directive (or pseudo-op)
• a comment
Whitespace (between symbols) and case are ignored.
Comments (beginning with “;”) are also ignored.

An instruction has the following format:
Opcodes and Operands
Opcodes
• reserved symbols that correspond to LC-3 instructions
• listed in Appendix A
Ø ex: ADD, AND, LD, LDR, …
Operands
• registers -- specified by Rn, where n is the register number
• numbers -- indicated by # (decimal) or x (hex)
• label -- symbolic name of memory location
• separated by comma
• number, order, and type correspond to instruction format
Ø ex: ADD R1,R1,R3 ADD R1,R1,#3 LD R6,NUMBER BRz LOOP
Labels and Comments
Label
• placed at the beginning of the line
• assigns a symbolic name to the address corresponding to line
Ø ex: LOOP ADD R1,R1,#-1 BRp LOOP
Comment
• anything after a semicolon is a comment
• ignored by assembler
• used by humans to document/understand programs
• tips for useful comments:
Ø avoid restating the obvious, as “decrement R1”
Ø provide additional insight, as in “accumulate product in R6”
Ø use comments to separate pieces of program
Assembler Directives
Pseudo-operations
• do not refer to operations executed by program
• used by assembler
• look like instruction, but “opcode” starts with dot
Trap Codes
LC-3 assembler provides “pseudo-instructions” foreach trap code, so you don’t have to remember them.
Style Guidelines
Use the following style guidelines to improvethe readability and understandability of your programs:
• Provide a program header, with author’s name, date, etc.,and purpose of program.
• Start labels, opcode, operands, and comments in same columnfor each line. (Unless entire line is a comment.)
• Use comments to explain what each register does.
• Give explanatory comment for most instructions.
• Use meaningful symbolic names.
• Mixed upper and lower case for readability.
• ASCIItoBinary, InputRoutine, SaveR1
• Provide comments between program sections.
• Each line must fit on the page -- no wraparound or truncations.
• Long statements split in aesthetically pleasing manner.
Sample Program
Count the occurrences of a character in a file.Remember this?
Char Count in Assembly Language (1 of 3)
;
; Program to count occurrences of a character in a file.
; Character to be input from the keyboard.
; Result to be displayed on the monitor.
; Program only works if no more than 9 occurrences are found.
;
;
; Initialization
;
.ORIG x3000
AND R2, R2, #0 ; R2 is counter, initially 0
LD R3, PTR ; R3 is pointer to characters
GETC ; R0 gets character input
LDR R1, R3, #0 ; R1 gets first character
;
; Test character for end of file
;
TEST ADD R4, R1, #-4 ; Test for EOT (ASCII x04)
BRz OUTPUT ; If done, prepare the output
Char Count in Assembly Language (2 of 3)
;
; Test character for match. If a match, increment count.
;
NOT R1, R1
ADD R1, R1, R0 ; If match, R1 = xFFFF
NOT R1, R1 ; If match, R1 = x0000
BRnp GETCHAR ; If no match, do not increment
ADD R2, R2, #1
;
; Get next character from file.
;
GETCHAR ADD R3, R3, #1 ; Point to next character.
LDR R1, R3, #0 ; R1 gets next char to test
BRnzp TEST
;
; Output the count.
;
OUTPUT LD R0, ASCII ; Load the ASCII template
ADD R0, R0, R2 ; Covert binary count to ASCII
OUT ; ASCII code in R0 is displayed.
HALT ; Halt machine

Char Count in Assembly Language (3 of 3)
;
; Storage for pointer and ASCII template
;
ASCII .FILL x0030
PTR .FILL x4000
.END

Assembly Process
Convert assembly language file (.asm)into an executable file (.obj) for the LC-3 simulator.




First Pass:
• scan program file
• find all labels and calculate the corresponding addresses;this is called the symbol table
Second Pass:
• convert instructions to machine language,using information from symbol table
First Pass: Constructing the Symbol Table
•Find the .ORIG statement,which tells us the address of the first instruction.
• Initialize location counter (LC), which keeps track of thecurrent instruction.
•For each non-empty line in the program:
• If line contains a label, add label and LC to symbol table.
• Increment LC.
– NOTE: If statement is .BLKW or .STRINGZ,increment LC by the number of words allocated.
•Stop when .END statement is reached.

NOTE: A line that contains only a comment is considered an empty line.
Practice
Construct the symbol table for the program in Figure 7.1(Slides 7-11 through 7-13).
Second Pass: Generating Machine Language
For each executable assembly language statement,generate the corresponding machine language instruction.
• If operand is a label,look up the address from the symbol table.

Potential problems:
• Improper number or type of arguments
Ø ex: NOT R1,#7 ADD R1,R2 ADD R3,R3,NUMBER
• Immediate argument too large
Ø ex: ADD R1,R2,#1023
• Address (associated with label) more than 256 from instruction
Ø can’t use PC-relative addressing mode
Practice
Using the symbol table constructed earlier,translate these statements into LC-3 machine language.
LC-3 Assembler
Using “assemble” (Unix) or LC3Edit (Windows),generates several different output files.
Object File Format
LC-3 object file contains
• Starting address (location where program must be loaded),followed by…
• Machine instructions

Example
• Beginning of “count character” object file looks like this:
Multiple Object Files
An object file is not necessarily a complete program.
• system-provided library routines
• code blocks written by multiple developers

For LC-3 simulator, can load multiple object files into memory,then start executing at a desired address.
• system routines, such as keyboard input, are loaded automatically
Ø loaded into “system memory,” below x3000
Ø user code should be loaded between x3000 and xFDFF
• each object file includes a starting address
• be careful not to load overlapping object files
Linking and Loading
Loading is the process of copying an executable imageinto memory.
• more sophisticated loaders are able to relocate imagesto fit into available memory
• must readjust branch targets, load/store addresses

Linking is the process of resolving symbols betweenindependent object files.
• suppose we define a symbol in one module,and want to use it in another
• some notation, such as .EXTERNAL, is used to tell assembler that a symbol is defined in another module
• linker will search symbol tables of other modules to resolve symbols and complete code generation before loading

Saturday, January 27, 2007

WASE BITS-WIPRO SESSION 3 DT:28-01-07

VENUE : WIPRO HYDERABAD
AUDIENCE : BITS-WASE 2006 BATCH
RESOURCES : PATTPATEL PPTs AND MORRIS MANO TEXT

Chapter 3Digital LogicStructures
Transistor: Building Block of Computers
Microprocessors contain millions of transistors
• Intel Pentium 4 (2000): 48 million
• IBM PowerPC 750FX (2002): 38 million
• IBM/Apple PowerPC G5 (2003): 58 million

Logically, each transistor acts as a switch
Combined to implement logic functions
• AND, OR, NOT
Combined to build higher-level structures
• Adder, multiplexer, decoder, register, …
Combined to build processor
• LC-3
Digital circuits
Constructed with ICs
IC is a small semiconductor crystal called chip containing gates
Depending on the number of gates we call them SSI,MSI,LSI,VLSI
SSI-10 GATES
MSI-200 GATES e.g. DECODERS,ADDERS,REGISTERS
LSI-1000s OF GATES e.g. PROCESSORS,MEMORY
VLSI- MANY 1000s MEMORY ARRAYS, COMPLEX CHIPS

DIGITAL INTEGRATED CIRCUITS
THE circuit technology/ digital logic family have their own basic electronic circuit upon which more complex digital circuits and functions are developed.
The basic circuit in each technology is either a NAND, a NOR or an inverter gate.
Logic Families
TTL/DTL- SUPPLY IS 5VOLTS, TWO STATES ARE 0,3.5V
ECL-SUPER COMPUTERS, DELAY IN NANOSECS
MOS- UNIPOLAR TRANSISTOR ONLY ONE CARRIER i.e. ELECTRONS(N-CHANNEL) OR HOLES(P-CHANNEL) CALLED AS PMOS AND NMOS
CMOS-PMOS+NMOS IN COMPLEMENTARY FASHION
Decoder
Combination circuit that converts binary information from n inputs to 2n unique outputs
N x m decoder means n inputs and m outputs where m<=2n
3 x 8 decoder can be used for binary to octal conversion

Commercial decoders have enable input E . If E=1 the decoder operates in normal fashion and if E=0 then the outputs are equal to zero

Decoder Expansion:- A 6-to-64 decoder can be constructed using four 4-to-16 decoders
Multiplexer

Combinational circuit that receives binary information from one of 2n input data lines and directs it to a single output line

The selection of a particular input data line for the output is determined by a set of selection inputs.

May have enable input E


Registers
A register consists of group of flip-flops and gates that effect their transition.
Flip-flops are capable of storing one bit of information.
Gates control when and how new information is transformed in to the register.
The transfer of new information into a register is referred to as loading the register.
Memory
A memory unit is a collection of storage cells together with associated circuits needed to transfer information in and out of storage. The memory stores binary information in groups of bits called words. A word in memory is an entity that moves in and out of storage as a unit.

Conventional memory – 1M = 220=20 address lines
= 640k + 384k uma. Addresses are from A0000 to FFFFF

Memories are RAM and ROM
RAM has two operations read and write, data input output lines, address lines, control lines
Memories
The internal structure of a memory unit is specified by the
number of words it contains and the number of bits in
each word. Special input lines called address lines select
one particular word. Each word has one unique address.

A decoder accepts this address and opens the path
needed to select the bits of the specified word.
Logic Gates
The manipulation of binary information is done by logic circuits called gates.

Gates are blocks of hardware that produce signals of binary 1 or 0 when input logic requirements are satisfied.

Each gate has a distinct graphic symbol and its operation can be described by an algebraic expression.

The input-output relationship of the binary variables for each gate can be represented in tabular form by a truth table.

Combinational Circuits
It is a connected arrangement of logic gates with a set of inputs and outputs.

The binary values of the output are a function of the binary combination of the inputs.

It transforms binary information from the given input data to the required output data.

Examples of combinational circuits are Half-Adder and Full-Adder which are arithmetic circuits
Full Adder
It is a combinational circuit that forms the arithmetic sum of three input bits.
It consists of three inputs and two outputs.

When all the input bits are 0, the output is 0.

S is equal to 1 when only one input is equal to 1 or when all three inputs are equal to 1.

C output has a carry of 1 if two or three inputs are equal to 1.
Half Adder
A combination circuit that performs the arithmetic addition of two bits is called a half-adder.

The input variables of a half adder are are called the augend and addend bits. The output variables the sum and carry.

It consists of an exor gate and an and gate.
Sequential circuit
They are storage elements which require that the system be described in terms of sequential circuits.
The most common type of sequential circuit is the synchronous type.
Synchronous sequential circuits employ signals that affect the storage elements only at discrete instant of time.
Synchronization is achieved by a timing device called a clock pulse generator that produces a periodic train of clock pulses.
Storage elements employed in clock sequential circuits are Flip-Flops.

Flip-Flop
It is binary cell capable of storing one bit of information.
It has two outputs, one for the normal value and one for the complementary value of the bits stored in it.
A flip-flop maintains a binary state until directed by a clock pulse to switch states.
The difference among various types of flip-flops is in the number of inputs they possess and in the manner in which the inputs affects the binary state.
The most common types of flip-flops are SR, D, JK, T, Edge-triggered
Simple Switch Circuit
Switch open:
• No current through circuit
• Light is off
• Vout is +2.9V

Switch closed:
• Short circuit across switch
• Current flows
• Light is on
• Vout is 0V
n-type MOS Transistor
MOS = Metal Oxide Semiconductor
• two types: n-type and p-type
n-type
• when Gate has positive voltage,short circuit between #1 and #2(switch closed)
• when Gate has zero voltage,open circuit between #1 and #2(switch open)
p-type MOS Transistor
p-type is complementary to n-type
• when Gate has positive voltage,open circuit between #1 and #2(switch open)
• when Gate has zero voltage,short circuit between #1 and #2(switch closed)
Logic Gates
Use switch behavior of MOS transistorsto implement logical functions: AND, OR, NOT.

Digital symbols:
• recall that we assign a range of analog voltages to eachdigital (logic) symbol





• assignment of voltage ranges depends on electrical properties of transistors being used
Ø typical values for "1": +5V, +3.3V, +2.9V
Ø from now on we'll use +2.9V
CMOS Circuit
Complementary MOS
Uses both n-type and p-type MOS transistors
• p-type
Ø Attached to + voltage
Ø Pulls output voltage UP when input is zero
• n-type
Ø Attached to GND
Ø Pulls output voltage DOWN when input is one

For all inputs, make sure that output is either connected to GND or to +,but not both!
Inverter (NOT Gate)
NOR Gate
OR Gate
NAND Gate (AND-NOT)
AND Gate
Basic Logic Gates
DeMorgan's Law
Converting AND to OR (with some help from NOT)
Consider the following gate:
More than 2 Inputs?
AND/OR can take any number of inputs.
• AND = 1 if all inputs are 1.
• OR = 1 if any input is 1.
• Similar for NAND/NOR.

Can implement with multiple two-input gates,or with single CMOS circuit.
Summary
MOS transistors are used as switches to implementlogic functions.
• n-type: connect to GND, turn on (with 1) to pull down to 0
• p-type: connect to +2.9V, turn on (with 0) to pull up to 1

Basic gates: NOT, NOR, NAND
• Logic functions are usually expressed with AND, OR, and NOT

DeMorgan's Law
• Convert AND to OR (and vice versa) by inverting inputs and output
Building Functions from Logic Gates
Combinational Logic Circuit
• output depends only on the current inputs
• stateless
Sequential Logic Circuit
• output depends on the sequence of inputs (past and present)
• stores information (state) from past inputs

We'll first look at some useful combinational circuits,then show how to use sequential circuits to store information.
Decoder
n inputs, 2n outputs
• exactly one output is 1 for each possible input pattern
Multiplexer (MUX)
n-bit selector and 2n inputs, one output
• output equals one of the inputs, depending on selector
Full Adder
Add two bits and carry-in,produce one-bit sum and carry-out.
Four-bit Adder
Logical Completeness
Can implement ANY truth table with AND, OR, NOT.
Combinational vs. Sequential
Combinational Circuit
• always gives the same output for a given set of inputs
Ø ex: adder always generates sum and carry,regardless of previous inputs
Sequential Circuit
• stores information
• output depends on stored information (state) plus input
Ø so a given input might produce different outputs,depending on the stored information
• example: ticket counter
Ø advances when you push the button
Ø output depends on previous state
• useful for building “memory” elements and “state machines”
R-S Latch: Simple Storage Element
R is used to “reset” or “clear” the element – set it to zero.
S is used to “set” the element – set it to one.







If both R and S are one, out could be either zero or one.
• “quiescent” state -- holds its previous value
• note: if a is 1, b is 0, and vice versa
Clearing the R-S latch
Suppose we start with output = 1, then change R to zero.
Setting the R-S Latch
Suppose we start with output = 0, then change S to zero.
R-S Latch Summary
R = S = 1
• hold current value in latch
S = 0, R=1
• set value to 1
R = 0, S = 1
• set value to 0

R = S = 0
• both outputs equal one
• final state determined by electrical properties of gates
• Don’t do it!
Gated D-Latch
Two inputs: D (data) and WE (write enable)
• when WE = 1, latch is set to value of D
Ø S = NOT(D), R = D
• when WE = 0, latch holds previous value
Ø S = R = 1
Register
A register stores a multi-bit value.
• We use a collection of D-latches, all controlled by a common WE.
• When WE=1, n-bit value D is written to register.
Representing Multi-bit Values
Number bits from right (0) to left (n-1)
• just a convention -- could be left to right, but must be consistent
Use brackets to denote range:D[l:r] denotes bit l to bit r, from left to right






May also see A<14:9>, especially in hardware block diagrams.
Memory
Now that we know how to store bits,we can build a memory – a logical k × m array of stored bits.
22 x 3 Memory
More Memory Details
This is a not the way actual memory is implemented.
• fewer transistors, much more dense, relies on electrical properties
But the logical structure is very similar.
• address decoder
• word select line
• word write enable
Two basic kinds of RAM (Random Access Memory)
Static RAM (SRAM)
• fast, maintains data as long as power applied
Dynamic RAM (DRAM)
• slower but denser, bit storage decays – must be periodically refreshed
State Machine
Another type of sequential circuit
• Combines combinational logic with storage
• “Remembers” state, and changes output (and state) based on inputs and current state

Combinational vs. Sequential
Two types of “combination” locks
State
The state of a system is a snapshot ofall the relevant elements of the systemat the moment the snapshot is taken.
Examples:
• The state of a basketball game can be represented bythe scoreboard.
Ø Number of points, time remaining, possession, etc.
• The state of a tic-tac-toe game can be represented bythe placement of X’s and O’s on the board.
State of Sequential Lock
Our lock example has four different states,labelled A-D:A: The lock is not open, and no relevant operations have been performed.
B: The lock is not open, and the user has completed the R-13 operation.
C: The lock is not open, and the user has completed R-13, followed by L-22.
D: The lock is open.
State Diagram
Shows states and actions that cause a transition between states.
Finite State Machine
A description of a system with the following components:
• A finite number of states
• A finite number of external inputs
• A finite number of external outputs
• An explicit specification of all state transitions
• An explicit specification of what determines eachexternal output value

Often described by a state diagram.
• Inputs trigger state transitions.
• Outputs are associated with each state (or with each transition).
The Clock
Frequently, a clock circuit triggers transition fromone state to the next.





At the beginning of each clock cycle,state machine makes a transition,based on the current state and the external inputs.
• Not always required. In lock example, the input itself triggers a transition.
Implementing a Finite State Machine
Combinational logic
• Determine outputs and next state.
Storage elements
• Maintain state representation.
Storage: Master-Slave Flipflop
A pair of gated D-latches, to isolate next state from current state.
Storage
Each master-slave flipflop stores one state bit.

The number of storage elements (flipflops) neededis determined by the number of states(and the representation of each state).

Examples:
• Sequential lock
Ø Four states – two bits
• Basketball scoreboard
Ø 7 bits for each score, 5 bits for minutes, 6 bits for seconds,1 bit for possession arrow, 1 bit for half, …
Complete Example
A blinking traffic sign
• No lights on
• 1 & 2 on
• 1, 2, 3, & 4 on
• 1, 2, 3, 4, & 5 on
• (repeat as long as switchis turned on)
Traffic Sign State Diagram
Traffic Sign Truth Tables
Traffic Sign Logic
From Logic to Data Path
The data path of a computer is all the logic used toprocess information.
• See the data path of the LC-3 on next slide.

Combinational Logic
• Decoders -- convert instructions into control signals
• Multiplexers -- select inputs and outputs
• ALU (Arithmetic and Logic Unit) -- operations on data
Sequential Logic
• State machine -- coordinate control signals and data movement
• Registers and latches -- storage elements
LC-3 Data Path