11-2 identify the parts of the “main” function, which include preprocessor directives main...

28

Upload: luke-daniels

Post on 16-Dec-2015

229 views

Category:

Documents


0 download

TRANSCRIPT

11-2

• Identify the parts of the “main” function, which include

• Preprocessor Directives• main function header• main function body which includes

• Declaration statements• Executable statements which include

• Assignment statements• Function statements,

e.g. printf(...),scanf(...)(a.k.a. expression statements)

Related Chapters: ABC Chapters 2 & 8.1, 8.2 & 11.1, 11.2

11-3

1. Requirements Specification (Problem Definition)Write a simple C program to request the users’ SSN and print the message “Hello (SSN)!” (where SSN is the value the user supplied) to the screen of the computer monitor.

2. Analysis---Refine, Generalize, Decompose the problem definition

(i.e., identify subproblems, I/O, etc.) Input = SSN

Output= A prompt for the SSN then“Hello (SSN)!”

11-4

/* C Program to greet the user */#include <stdio.h> /* makes the function printf “known” */

/* to the C compiler */ void main(void){ int ssn; /* variable ssn declared */ printf(“Please enter your SSN (no dashes):”); scanf(“%i”,&ssn); /* read the SSN */ printf(”Hello (%i)!\n”,ssn); /* print the message */}

3. Design---Develop Algorithm

Pseudo-code Algorithm

print “Enter SSN (no dashes)”read SSNprint “Hello (SSN) !”

4. Implementation --- Write the "Program" (Code)

11-5

#include ... /* preprocessor directive */ . . .void main(void) /*function header*/

{ . . /* function body */ . }

In the following set of slides we will define the component parts of the main function.

11-6

#include ... /* preprocessor directive */ . . .void main(void){ . . . }

Statements beginning with the symbol # are called preprocessor directives. The #include directives allow the C program to access libraries of functions that are not available directly in C. These libraries are referred to as header files:

stdio.h standard input-output functions math.h math functions

stdlib.h a “standard” library of functions

11-7

#include ... . . .void main(void) /*function header*/

{ . . . }

The “initial” input is any value(s) passed at initial execution, e.g.>./a.out 1.0 3.5Typing the above at the Unix prompt attempts to pass the values 1.0 and 3.5 to main. At this point we will not do this. See p. 48 in ABC if you really want to know how.The header for the programs in some C programs is of the form: int main(void)and there is a corresponding statement in the function body: return (0);however, again, we won’t need this feature of main in CS101.

main has no “initial” input values. (see below)

main function returns no value

11-8

#include ... . . .void main(void)

{ . . /* function body */ . }

• The body of a function is all the declarations and executable statements between the braces (in the block). The declarations must precede the executable statements in this block.

• When you run a program, the first statement executed is the first (from the top of the file) executable statement in main. The execution of statements proceeds until the terminating “}” right brace is encountered or a return statement is executed.

a “block” in C is defined by a set of curly braces.

11-9

One form of a declaration in C :

data-type variable_name ;

#include <stdio.h>

void main(void){ int ssn; /* variable ssn declared */ printf(”Please enter your SSN (no dashes):”); scanf(”%i”,&ssn); printf(”Hello (%i)!\n”,ssn); }

11-10

Fixed Point(Integers) Floating Point Charactershort float charint doublelong long double

See ABC Chapter 3.2 p. 110 for a complete list of the numeric data-types.

Character strings in C are implemented as arrays. See ABC Chapter 6.10 p. 270.

11-11

Variable Names - reference to memory locations storing data values. A variable name is one example of an identifier in C.

An identifier can use a combination of letters, numerical digits, and the underscore ( _ ) that starts with a letter. Only the first 31 characters of an identifier are recognized by most compilers. Identifiers cannot be the same as a reserved word or keyword, such as void, float, or return. (ABC Chapter 2.4 p. 77 list the reserved words)

Use descriptive variable names.

Examples: x sum force2 rate_Of_Change

Examples of invalid variable names (why?):

2force rate-of-change x.5 return

C case-sensitive, so that the following three names all represent different variables (i.e., different storage locations):

time Time TIME

11-12

#include <stdio.h>

void main(void){ int ssn; printf(”Please enter your SSN (no dashes):”); scanf(”%i”,&ssn); printf(”Hello (%i)!\n”,ssn); }

The printf and scanf functions appear in ‘expression’ statements.

1st executablestatement

3rd executablestatement

2nd executablestatement

11-13

Statements are grouped by their type:

• assignment statement• expression statement• do-while and while statements• for statement• if and if-else statements• switch statement• return statement

Every executable statement in C must be followed by a “ ; “ semicolon.

selection statements

loop statements

11-14

• Interpretation: compute the value on the right-hand-side of the = and put this value in memory at location named (or tagged) by the name variable .

• an expression can be a constant, a variable or operators with operands.

variable = expression;

11-15

Literal Constants(examples)

Numeric: 3 6.248 -7.25 1.5e4 (=15000)

Single Character: 'A' 'a' '9' '+' ' '

Character String: “Enter a positive number: ”

Symbolic Constants(example)

#define PI 3.14159265 /* preprocessor directive */

By default, constants declared in #define are of type double.

Standard practice is to use all upper-case letters for the constant name, to avoid confusion with a variable name.

A “constant” means you cannot change the value, e.g.

PI = 3.0;

will generate a compiler error from gcc.

11-16

- for integer arithmetic, the / operator yields an integer result, and % gives the remainder after dividing two integers. E.g.,

5 / 3 1 5 / 6 0 -5%3 -2

5 % 3 2 5 % 6 5 5%-3 2

(Note: division by 0 creates an "overflow" run-time error.)

- use arithmetic operators, with parentheses for grouping; e.g., (a - b) / (2 * c)e.g, without parentheses, the example above would evaluate b/2 first, then do the multiplication, then the subtraction.

+, - , * , / , % (modulus) (no ^ operator as in Matlab)

11-17

( ) Higher

*, /, % (left to right for tie)+, - (left to right for tie)

Lower

(see ABC p. 705 Appendix E for a complete list of operators and their precedence)

Examples,

x = 3 + 2 * 3; /* x now has the value 9 */

y = 3 * 2 % 3; /* y now has the value 0 */

- Precedence Order for Arithmetic Operators:

11-18

• Example

int time;

time = time+1;

. . .

time = 0;

time = time+1;

.1time

1200A

dd

ress

Main Memory

Memory map after the assignment statement

time = time+1;is executed

.unknowntime

1200

Ad

dre

ss

Main Memory

Memory map before the assignment statement

time = time+1;is executed

11-19

• Example

double force;

force = 5.0;

. . .

force = force * 3.0;

.15.0force

1400

Main Memory

Memory map after the assignment statement

force = force * 3.0; is executed

.5.0force

1400

Ad

dre

ss

Main Memory

Memory map before the assignment statement

force = force * 3.0; but after

force = 5.0;is executed

11-20

Individual characters may be assign to variables of data-type char.

Example: Write a program to prompt the user for a Y/ N response. Print the users response to the screen.

#include <stdio.h>

void main(void)

{

char letter; printf(“Please enter a response (Y/N):”);

scanf(“%c”,&letter);

printf(“Your response was: %c \n”,letter);

}

11-21

One form of a expression statement in C :

function(argument list) ;

11-22

accepts input from standard input device, usually a keyboard

scanf("format string", &var1, &var2, ...);

The number of conversion specifiers should match the number of variables that follow the “format string”.

%i - integer

%f - float

%lf - double(where lf="long float")

%c - character%s - character string

where “format string” is the string of conversion specifiers for the various data types in the variable list.

11-23

sends output to standard output device, usually a video monitor

printf("format string", output-list);

where ”format string” can contain characters to be output and the conversion specifiers indicating type and position of the output values. For output, we specify formats conversion specifiers) a little differently than we do for input. For example:

%i -integer %f -float%lf -double%c -character%s -character string

11-24

Each is represented by an escape sequence, which is a backslash (\) and an escape character.Examples are: (see pp. 112-114 in ABC)

\" - output double quotes

\t – horizontal tab

\’ - output single quote

\\ - output backslash character (\)

\n - new line

11-25

The number of print positions to be used in the output of display values. Examples:int x = 1;int y = 12;printf(“%3i%7i”, x , y );displays,

double w = 1.3333333;double z = 1.3399999;printf(“%7.2lf%7.2lf”, w , z);displays,

1 1 2

1 . 3 3 1 . 3 4

11-26

Example:

int n; float a; double c; char x;

scanf("%i %f %lf %c", &n, &a, &c, &x);

Example: printf("The output is: \n"); printf("n = %i a = %f\n",n, a);

11-27

Comments in C are of the general form:

/* . . . */

Comments can be inserted anywhere you can put a space (blank). Comments are ignored by the C compiler and not included in the executable file.

The */ can be on the next line but then every character between the /* and the */ is ignored by the C compiler.

You cannot nest comments:/* /* . . . */ */

11-28

Syntax Errors

Run-time Errors

Logical Errors

The gcc compiler will catch these errors and give you Error messages.Example: x + 1 = x; (should be x = x+1; for a valid assignment statement)

The gcc compiler will not catch these errors. Example: User types: scanf(“%i”, x); and omits the &.

The gcc compiler will not catch these errors. Program will run and not generate any error messages but results outputted by the program are incorrect.Example: User programs solution using an incorrect formula.