+ All Categories
Home > Documents > CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Date post: 18-Jan-2016
Category:
Upload: giles-heath
View: 218 times
Download: 4 times
Share this document with a friend
33
CHAPTER 1 CHAPTER 1 INTRODUCTION TO INTRODUCTION TO COMPUTING COMPUTING 1.1 Introduction 1.1 Introduction
Transcript
Page 1: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

CHAPTER 1CHAPTER 1INTRODUCTION TO INTRODUCTION TO

COMPUTINGCOMPUTING

1.1 Introduction1.1 Introduction

Page 2: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

1.21.2 Computer OrganizationComputer OrganizationThe main components of a computer machine areThe main components of a computer machine are::

Central Processing UnitCentral Processing Unit (CPU): it is the heart of the (CPU): it is the heart of the machine, and it controls all the operations and machine, and it controls all the operations and performs all the arithmetic and logic operationsperforms all the arithmetic and logic operations..Memory UnitMemory Unit: this unit stores instructions and data: this unit stores instructions and data..Control Unit:Control Unit: This unit fetches instructions of the Memory Unit, This unit fetches instructions of the Memory Unit, decodes them and directs the system to execute the decodes them and directs the system to execute the operations indicated by the instructionsoperations indicated by the instructions..Arithmetic-Logic Unit (ALU):Arithmetic-Logic Unit (ALU): This unit is part of the CPU and This unit is part of the CPU and carries out arithmetic and logical operationscarries out arithmetic and logical operations..

The The Memory UnitMemory Unit consists of several components: one of consists of several components: one of these components is used to store the instructions these components is used to store the instructions and data of the programs being executed and has and data of the programs being executed and has many names, including internal, main, primary, and many names, including internal, main, primary, and

random access memoryrandom access memory (RAM) (RAM) . .

Page 3: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Control Unit Arithmetic Logic Unit

Main Memory

Input Devices

Output Devices

External Memory

Figure 1: basic computer components

Page 4: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

1.31.3 Computer LanguageComputer Language

In the very early age of computers, computer programs In the very early age of computers, computer programs were written using the were written using the machine languagemachine language. The . The machine language words are some sort of strings having machine language words are some sort of strings having two parts: opcode and operand and each consist of two parts: opcode and operand and each consist of either 0 or 1 numerals. Later, it became possible to write either 0 or 1 numerals. Later, it became possible to write programs in programs in assembly languageassembly language, which uses names in , which uses names in place of numeric opcodes and variable names in place of place of numeric opcodes and variable names in place of numeric addresses. Nowadays, most computer numeric addresses. Nowadays, most computer programs are written in a programs are written in a high-level-languagehigh-level-language such as such as FORTRAN, and a compiler translates each statement in FORTRAN, and a compiler translates each statement in the program into a sequence of basic machine (or the program into a sequence of basic machine (or assembly language) language instructions. FORTRAN assembly language) language instructions. FORTRAN word is an abbreviation for “word is an abbreviation for “FORFORmula mula TRANTRANslator” and slator” and was one of the first high-level languages to gain was one of the first high-level languages to gain acceptance worldwideacceptance worldwide

Page 5: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

1.41.4 Programming and Problem Programming and Problem SolvingSolving

A minimum of five steps can be identified in A minimum of five steps can be identified in the program development processthe program development process::

1.1. Problem analysis and specificationProblem analysis and specification

2.2. data organization and algorithm designdata organization and algorithm design

3.3. program codingprogram coding

4.4. execution and testingexecution and testing

5.5. program maintenanceprogram maintenance

Page 6: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

BASIC FORTRANBASIC FORTRAN2.1 Introduction2.1 Introduction

FORTRAN provides FORTRAN provides five basicfive basic data types data types::

INTEGERINTEGER

REALREAL

COMPLEXCOMPLEX

CHARACTERCHARACTER

LOGICALLOGICAL

Page 7: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.22.2 Data Types, Constants, and Data Types, Constants, and VariablesVariables::

IdentifiersIdentifiers Identifiers must begin with a letter, which may be followed by up to Identifiers must begin with a letter, which may be followed by up to 30 letters, 30 letters,

digits, or underscores. Thusdigits, or underscores. Thus,,

MassMassRateRateVelocityVelocitySpeed_of_LightSpeed_of_Light

Are valid FORTRAN identifiers, but the following are invalid for the reasons Are valid FORTRAN identifiers, but the following are invalid for the reasons indicatedindicated::

R2-D2R2-D2 (Only letter, digits, and underscores are allowed in identifiers)(Only letter, digits, and underscores are allowed in identifiers)

6Feet 6Feet (Identifiers must begin with a letter)(Identifiers must begin with a letter) . .

Page 8: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Integer costantsInteger costants

An integer is a whole number (positive, An integer is a whole number (positive, negative, or zero) and may be represented negative, or zero) and may be represented in FORTRAN by a string of digits that does in FORTRAN by a string of digits that does not contain commas or a decimal point; not contain commas or a decimal point; negative integer constants must be negative integer constants must be preceded by a minus sign, but a plus sign preceded by a minus sign, but a plus sign is optional for nonnegative integers. Thus is optional for nonnegative integers. Thus 0 , 137 , -2516 , +17745 are valid 0 , 137 , -2516 , +17745 are valid integer constantsinteger constants

Page 9: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

whereas the following are invalid whereas the following are invalid for the reasons indicatedfor the reasons indicated::

9,9999,999 commas are not allowed in numeric commas are not allowed in numeric constantsconstants

16.016.0 integer constants may not contain integer constants may not contain decimal points decimal points

--5--5 only one algebraic sign is only one algebraic sign is allowedallowed

7-7- the algebraic sign must precede the algebraic sign must precede the string of digits.the string of digits.

Page 10: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Real constantsReal constants

Real is another data type and it can be represented as ordinary Real is another data type and it can be represented as ordinary decimal numbers or in exponential notation. When representing a decimal numbers or in exponential notation. When representing a real constant using decimal numbers, a decimal point must be real constant using decimal numbers, a decimal point must be present, but no commas are allowed. Negative real constants must present, but no commas are allowed. Negative real constants must be preceded by a minus sign, but the plus sign is optional for be preceded by a minus sign, but the plus sign is optional for nonnegative reals. Thusnonnegative reals. Thus , ,

1.2341.234.-.-0153601536.+.+5647356473

are valid real constants, whereas the following are invalid for the are valid real constants, whereas the following are invalid for the reasons indicatedreasons indicated::

12,34512,345))Commas are not allowed in numeric constantsCommas are not allowed in numeric constants((

6363))Real constants must contain a decimal pointReal constants must contain a decimal point((

Page 11: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Real constantsReal constants

The exponential representation of a real constant consists The exponential representation of a real constant consists of an integer or decimal number representing the of an integer or decimal number representing the mantissa or fractional part, followed by an exponent mantissa or fractional part, followed by an exponent written as the letter E with an integer constant following. written as the letter E with an integer constant following. For example, the real constant 337.456 may also be For example, the real constant 337.456 may also be written aswritten as3.37456E23.37456E2which means 3.37456x 102, or it may be written in a variety which means 3.37456x 102, or it may be written in a variety of other forms, such asof other forms, such as

0.337456E30.337456E3337.456E0337.456E033745.6E-233745.6E-2337456E-3337456E-3

Page 12: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Character StringsCharacter Strings

Character constants, also called strings, are Character constants, also called strings, are sequences of symbols from the FORTRAN sequences of symbols from the FORTRAN character set. The ANSI standard character set. The ANSI standard character set for FORTRAN is given in the character set for FORTRAN is given in the table belowtable below::

Page 13: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

CharacterMeaningCharacterMeaning

0 ,..…,9digits:Colon

A, ….. , Zuppercase letters=Equal sign

a, ….., zlowercase letters!Exclamation mark

'Apostrophe (single quote)

&Ampersand

"double quote $Dollar sign

)Left parenthesis;Semicolon

(Right parenthesis<Less than

*Asterisk>Greater than

+Plus sign%Percent symbol

-Minus sign?Question mark

/Slash,Comma

blankBlank or space.Period

Page 14: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

VariablesVariablesWhen a variable is used in a FORTAN program, the compiler When a variable is used in a FORTAN program, the compiler associated it with a memory location. The value of a variable at any associated it with a memory location. The value of a variable at any time is the value stored in the associated memory location at that time is the value stored in the associated memory location at that time. Variable names are identifiers; thus, they must follow the rules time. Variable names are identifiers; thus, they must follow the rules for identifiers. In FORTRAN programming the type of any variable for identifiers. In FORTRAN programming the type of any variable

used has to be declaredused has to be declared . .

INTEGER : : INTEGER : : listlistREAL :: REAL :: listlistA comma must separate the names in the list. For instance, the A comma must separate the names in the list. For instance, the statementsstatements::

INTEGER :: NumValues, Factorial, SumINTEGER :: NumValues, Factorial, SumREAL :: Mass, VelocityREAL :: Mass, Velocity

Page 15: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

VariablesVariablesCHARACTER (LEN = n ) : : CHARACTER (LEN = n ) : : listlistOr in a simpler formOr in a simpler form::

CHARACTER(n) : : CHARACTER(n) : : listlist

CHARACTER (LEN = 15) : : FirstName, CHARACTER (LEN = 15) : : FirstName, LastNameLastNameOrOrCHARACTER(15) : : FisrtName, LastNameCHARACTER(15) : : FisrtName, LastName

CHARACTER(15) : : FirstName, CHARACTER(15) : : FirstName, LastName*20, Initial*1, Street, CityLastName*20, Initial*1, Street, City

Page 16: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

IMPLICIT NONE StatementIMPLICIT NONE Statement

FORTRAN Implicit naming convention is applied to any FORTRAN Implicit naming convention is applied to any variable whose type is not explicitly declared in a type variable whose type is not explicitly declared in a type statement. The convention says that: any undeclared statement. The convention says that: any undeclared identifier whose name begins with I, J, K, L, M, or N or identifier whose name begins with I, J, K, L, M, or N or their lowercase equivalents will be typed as integer, and their lowercase equivalents will be typed as integer, and all other will be types as real. FORTRAN 90 provides all other will be types as real. FORTRAN 90 provides the statement IMPLICIT NONE to cancel this naming the statement IMPLICIT NONE to cancel this naming convention. It should be used in every program to guard convention. It should be used in every program to guard against errors caused by implicit typing of a variable to against errors caused by implicit typing of a variable to have a type different than what was intended. have a type different than what was intended. When When using this statement all the types of all named constants using this statement all the types of all named constants and variables (and functions) must be specified explicitly and variables (and functions) must be specified explicitly in type statementsin type statements. Otherwise, when using any . Otherwise, when using any undeclared variable (or function) without declaring it, it undeclared variable (or function) without declaring it, it will be considered an error by the compilerwill be considered an error by the compiler..

Page 17: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Variable InitializationVariable Initialization

As all variables in FORTRAN are initially As all variables in FORTRAN are initially undefined, initial values can be assigned undefined, initial values can be assigned to variables (at compile time) in their to variables (at compile time) in their declarations. For example, to initialize the declarations. For example, to initialize the values for variables W, X, Y, and Z to 1.0, values for variables W, X, Y, and Z to 1.0, 2.5, 7.73, and -2.956, respectively, one 2.5, 7.73, and -2.956, respectively, one could use the following statementcould use the following statement::

REAL :: W = 1.0, X = 2.5, Y = 7.73, Z = REAL :: W = 1.0, X = 2.5, Y = 7.73, Z = -2.956-2.956

Page 18: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Named Constants: the Named Constants: the PARAMETER AttributePARAMETER Attribute

TypeType--specifierspecifier, , PARAMETERPARAMETER :: :: listlistExamplesExamples::

INTEGER, PARAMETER :: Limit = 50INTEGER, PARAMETER :: Limit = 50REAL, PARAMETER :: Pi = 3.141593, TwoPi = 2.0 REAL, PARAMETER :: Pi = 3.141593, TwoPi = 2.0 * Pi* PiCHARACTER(2), PARAMETER :: Units = “cmCHARACTER(2), PARAMETER :: Units = “cm””

The last declaration example can also be writtenThe last declaration example can also be written

CHARACTER(*), PARAMETER :: Units CHARACTER(*), PARAMETER :: Units = “cm= “cm””

XCoordinate = Rate * Cos(TwoPi * Time)XCoordinate = Rate * Cos(TwoPi * Time)

Page 19: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.32.3 Numeric OperationsNumeric OperationsThe following characters are used in FORTRAN as The following characters are used in FORTRAN as denoteddenoted::

* * multiplication, multiplication,

-- subtractionsubtraction

+ + additionaddition

// divisiondivision

** ** exponentiationexponentiationFor example, the equality B2 – 4 A C is written asFor example, the equality B2 – 4 A C is written as

B ** 2 – 4 * A * CB ** 2 – 4 * A * C

Page 20: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Priority RulesPriority Rules

All exponentiations are performed first; All exponentiations are performed first; consecutive exponentiations are consecutive exponentiations are performed from right to left.performed from right to left.

All multiplications and divisions are All multiplications and divisions are performed next, in the order in which performed next, in the order in which they appear from left to right.they appear from left to right.

The additions and subtractions are The additions and subtractions are performed last, the order in which they performed last, the order in which they apear from left to right.apear from left to right.

Page 21: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

The following examples illustrate The following examples illustrate these prioritiesthese priorities::

22 ** ** 33 ** ** 22 = = 22 ** ** 99 = = 5125121010 – – 88 – – 22 = = 22- - 22 = = 001010 / / 55 * * 22 = = 22 * * 22 = = 4422 + + 44 / / 22 = = 22 + + 22 = = 44

22 + + 44 ** ** 22 / / 22 = = 22 + + 1616 / / 22 = = 22 + +88 = = 1010Parentheses can be used to modify the Parentheses can be used to modify the standard order of evaluation, for examplestandard order of evaluation, for example::

) ) 55) * ) * 1111 – – 55 ** ( ** (22 * ( * (44 + + 99) = ) = 55 * * 66 ** ** 22 * ( * (44 + +99 = = 180180 * * 44 + + 99 = = 720720 + + 99 = = 729729

Page 22: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Mixed-Mode ExpressionsMixed-Mode Expressions

3.0 + 8 / 5 »» 3.0 + 1 »» 4.03.0 + 8 / 5 »» 3.0 + 1 »» 4.0

3.0 + 8.0 / 5.0 »» 3.0 + 1.6»» 4.63.0 + 8.0 / 5.0 »» 3.0 + 1.6»» 4.6

The last two examples show the use of The last two examples show the use of mixed-mode operations is considered as mixed-mode operations is considered as a poor practice.a poor practice.

Note the following two expressionsNote the following two expressions

2.0 ** 3 »» 2.0 * 2.0 * 2.0 »» 8.02.0 ** 3 »» 2.0 * 2.0 * 2.0 »» 8.0

(-4) ** 2 »» (-4) * (-4) »» 16(-4) ** 2 »» (-4) * (-4) »» 16

Page 23: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

More ExamplesMore Examples

7.0 ** (1.0 / 2.0) »» 7.0 ** (0.5)7.0 ** (1.0 / 2.0) »» 7.0 ** (0.5)

7.0 ** ( 1 / 2 ) »» 7.0 ** 0 = 1.07.0 ** ( 1 / 2 ) »» 7.0 ** 0 = 1.0

Page 24: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Table 2.2 Some FORTRAN functions

FunctionDescription

ABS(x)Absolute value of x

COS(x)Cosine of x radians

EXP(x)Exponential function

INT(x)Integer part of x

FRACTION(x)M of x part (mantissa) of x

LOG(x)Natural logarithm of x

MAX(x1, ….., xn)Maximum of x1, ….., xn

MIN(x1, …., xn)Minimum of x1, ……., xn

MOD(x , y)x(mod y): x – INT(x/y) * y

NINT(x)x rounded to nearest integer

REAL(x)Conversion of x to real type

SIN(x)Sine of x radians

SQRT(x)Square root of x

TAN(x)Tangent of x radians

Page 25: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Examples on Numeric FunctionsExamples on Numeric Functions

SQRT(7.0)SQRT(7.0)

SQRT(B ** 2 – 4 * A * C)SQRT(B ** 2 – 4 * A * C)

X ** (1.0 / REAL (N))X ** (1.0 / REAL (N))

REAL(NUM) ** (1.0 / REAL(N))REAL(NUM) ** (1.0 / REAL(N))

Page 26: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.62.6 Input / OutputInput / OutputFORTRAN provided two types of input/output statements: list-directed FORTRAN provided two types of input/output statements: list-directed and formatted. The list directed method is simpler and has the and formatted. The list directed method is simpler and has the following simplest formfollowing simplest form::

PRINT * , PRINT * , output-listoutput-listOrOrWRITE (* , *) WRITE (* , *) output listoutput listExamplesExamples::PRINT *, “At time”, Time, “secondsPRINT *, “At time”, Time, “seconds””

PRINT *, “the vertical velocity is”, Velocity , “m / PRINT *, “the vertical velocity is”, Velocity , “m / secsec””

PRINT *, “and the height is”, Height , “metersPRINT *, “and the height is”, Height , “meters””

Page 27: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.62.6 Input / OutputInput / OutputThe PRINT and WRITE statement may be used The PRINT and WRITE statement may be used to produce a blank line of output as shown in to produce a blank line of output as shown in the following examplethe following example::

PRINTPRINT* * OrOr

WRITEWRITE(* , * ) (* , * ) The simplest form of list-directed input statement The simplest form of list-directed input statement isis

READ *, READ *, input-listinput-listOrOrREAD (* , *) READ (* , *) input-listinput-list

Page 28: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

ExampleExample::

The following line of input dataThe following line of input data

100.0100.0 , ,90.090.0 , ,4.54.5can be used to respond to the following statementcan be used to respond to the following statement : :

READ*, InitialHeight, InitialVelocity, TimeREAD*, InitialHeight, InitialVelocity, TimeThat means 100.0 value will be assigned to the variable InitialHeight, That means 100.0 value will be assigned to the variable InitialHeight, the value 90.0 will be assigned to the variable InitialVelocity and the the value 90.0 will be assigned to the variable InitialVelocity and the value 4.5 will be assigned to the variable Time. Spaced can also be value 4.5 will be assigned to the variable Time. Spaced can also be used as separators in place of the commas so that the line of input used as separators in place of the commas so that the line of input data will be as followsdata will be as follows::

100.0100.0 90.090.0 4.54.5or more than one line of data could be usedor more than one line of data could be used::

100.0100.0 , ,90904.54.5

Page 29: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.72.7 Program Composition and Program Composition and FormatFormat

The general form of a FORTRAN computer The general form of a FORTRAN computer program isprogram is::

headingheading Specification partSpecification part Execution partExecution part Subprogram partSubprogram part END PROGRAM statementEND PROGRAM statementThe The program headingprogram heading has the form has the form

PROGRAM PROGRAM namename

Page 30: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

execution partexecution part of a program of a program..

The last statement in every program must The last statement in every program must be the be the END PROGRAM statementEND PROGRAM statement. This . This statement indicates to the compiler the statement indicates to the compiler the end of the program. It also halts execution end of the program. It also halts execution of the program. Execution can also be of the program. Execution can also be terminated with a terminated with a STOP statementSTOP statement of the of the formform

Page 31: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

Program FormatProgram FormatIn FORTRAN90 programming the main rules that must be followed are:In FORTRAN90 programming the main rules that must be followed are:A line may A line may have a maximum of 132 charactershave a maximum of 132 characters..A line may contain more than one statement, provided the statements are separated A line may contain more than one statement, provided the statements are separated

by by semicolons (;).semicolons (;). It is good practice, however, to consider at most one It is good practice, however, to consider at most one statement per line.statement per line.

An An ampersand (&)ampersand (&) must be placed at the end of each line that is to be continued to must be placed at the end of each line that is to be continued to the next line. At most 39 continuation lines are permitted.the next line. At most 39 continuation lines are permitted.

: for example:: for example:

PRINT * , “Enter the initial height (m) and &PRINT * , “Enter the initial height (m) and &&the initial velocity (m/sec): “&the initial velocity (m/sec): “Any characters following an Any characters following an exclamation mark (!)—exclamation mark (!)—except within a string except within a string

constant—and running to the end of the line form a comment. For example,constant—and running to the end of the line form a comment. For example,

INTEGER :: NumberINTEGER :: Number ! Number of data values read! Number of data values readIf a statement requires a statement label, this label must precede the statement and If a statement requires a statement label, this label must precede the statement and

must be separated from it by at least one blank. Statement labels must be must be separated from it by at least one blank. Statement labels must be integers in the integers in the range 1 through 99999.range 1 through 99999.

Page 32: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

2.82.8 Types of ErrorsTypes of ErrorsThere are different Errors that a programmer may face There are different Errors that a programmer may face

during compilation or running of a computer program. during compilation or running of a computer program. Errors in the program’s syntax, such as incorrect Errors in the program’s syntax, such as incorrect punctuation or misspelled key words, will be detected punctuation or misspelled key words, will be detected during compilation. Such errors are called during compilation. Such errors are called syntax syntax errors or compile-time errors and usually errors or compile-time errors and usually make it impossible to complete the make it impossible to complete the compilation and execution of the program.compilation and execution of the program. Other errors, such as an attempt to divide by zero in an Other errors, such as an attempt to divide by zero in an arithmetic expression, may not be detected until arithmetic expression, may not be detected until execution of the program has begun. Such errors are execution of the program has begun. Such errors are called called run-time errorsrun-time errors.. There are other errors that are more subtle and difficult There are other errors that are more subtle and difficult to identify. These are to identify. These are logic errorslogic errors that arise in the that arise in the design of the algorithm or in the coding of the program design of the algorithm or in the coding of the program that implements the algorithm.that implements the algorithm.

Page 33: CHAPTER 1 INTRODUCTION TO COMPUTING 1.1 Introduction.

ExamplesExamples


Recommended