carme.cs.trinity.educarme.cs.trinity.edu/thicks/ctextbook/chap04-user... · web viewfrom 1950 to...

225
Structuring Program Logic Introduction to Computer Science With C: Programming, Problem Solving, & Data Structures Thomas E. Hicks Douglas W. Nance Thomas L. Naps

Upload: others

Post on 10-Mar-2020

67 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

Structuring ProgramLogic

Introduction to Computer Science With C:Programming,

Problem Solving,& Data Structures

Thomas E. HicksDouglas W. NanceThomas L. Naps

Copyright Pending for West Publishing Co.

Page 2: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [2]

Memory Management &Functions for Problem Solving

Page 3: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [3]

Page 4: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [4]

Advances in software engineering are often expected to keep pace with advances in computer hardware. The writing of software has indeed become more complex. Programs are expected to be more user-friendly, faster, more stable, and more portable than ever before. Most major projects are designed by teams of computer scientists and implemented by even larger teams of highly trained individuals.

This chapter is designed to help us more efficiently reach computer solutions by successively subdividing a problem until we have directly solvable tasks to code and implement. Section 4.1 explains the need for modularity and structure. Section 4.2 introduces both (a) the scope of global and local variables and (b) user-defined explicit-functions. Section 4.3 introduces user-defined void-functions, memory maps, and execution program execution flow. Section 4.4 introduces the passing of value variables to functions. Section 4.5 introduces pointers and the dereferencing of pointers. Section 4.6 provides suggestions for subprogram documentation, program documentation, and the writing of quality subprograms. Section 4.7 introduces stubs, drivers, and their construction.

A computer program is only as good as its design. This chapter will help to lay a sound foundation on which to build quality software.

Page 5: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [5]

Page 6: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [6]

Page 7: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [7]

Modularity

We have previously discussed and illustrated the process of solving a problem by top-down design. Top-down design is even more important when creating a large computer program, sometimes called a system. Using this method, we divide the main task into major subtasks, and then continue to divide the subtasks (stepwise refinement) into smaller subtasks until all subtasks can be easily performed. Once an algorithm for solving a problem has been developed using top-down design, the programmer then writes code to translate the general solution into a C program.

As you have seen, code written to perform one well-defined subtask is referred to as a subprogram. Collections of related subprograms are often grouped in a file called a module. Theoretically, one should be able to design, code, and test each subprogram with a small test driver program independently from the rest of the system. In this sense, a subprogram contains all definitions and declarations needed to perform the indicated subtask. Everything required for the subtask (but not needed in other parts of the program) should be created in the subprogram. Consequently, the definitions and declarations have meaning only when the subprogram is being used.

A program that has been created using subprograms to perform various tasks is said to possess modularity. In general, modular programs are easier to test, debug, maintain, and correct than programs that are not modular because each independent subprogram can be tested by running it from a test driver. An example of such a driver may be found in function main of program Cube.c (section 4.2). Once the subprograms are running correctly, they can be integrated into a longer program.

Page 8: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [8]

Page 9: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [9]

Structured Programming

Structured programming is the process of developing a program where emphasis is placed on the correspondence between independent subprograms. Structured programming breaks program logic, regardless of complexity, into sequence, selection, and iteration (see Structured Programming Note of Interest). Connections between these subprograms are specified in parameter lists. Structured programming is especially suitable to large programs being worked on by teams. By carefully designing the subprograms and specifying what information is to be received by and returned from the subprogram, a team of programmers can independently develop and test their subprogram and then have it connect to the complete program. From a compiler construction view, all subprograms are functions; however, most structured programming languages define a function to be a subprogram which explicitly returns information and a procedure to be a subprogram which does not explicitly return information. C is indeed a functional language, but not all C subprograms have an explicit return. For organizational purposes, it is best to separate subprogram with explicit returns from those with no explicit returns. This text shall refer to subprograms with no explicit returns as void-functions and those subprograms with explicit returns as explicit-functions. Functions printf, scanf, abs, sin, cos, sqrt, ceil, floor, fabs, pow, and log are among the explicit-functions that have been previously described.

A NOTE OF INTEREST

Page 10: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [10]

Page 11: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [11]

Structured Programming

From 1950 to the early 1970s programs were designed and written on a linear basis. A program written and designed on such a basis can be called an unstructured program. Structured programming, on the other hand, organizes a program around separate semi-independent subprograms that are linked together by a single sequence of simple commands.

In 1964, mathematicians Corrado Bohm and Guiseppe Jacopini proved that any program logic, regardless of complexity, can be expressed by using sequence, selection, and iteration. This result is termed the structure theorem. This result, combined with the efforts of Edger W. Dijkstra, led to a significant move toward structured programming and away from the use of GOTO statements.

The first time structured programming concepts were applied to a large-scale data processing application was the IBM Corporation "New York Times Project'' from 1969 to 1971. Using these techniques, programmers posted productivity figures from four to six times higher than those of the average programmer. In addition, the error rate was a phenomenally low 0.0004 per line of coding.

Page 12: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [12]

Page 13: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [13]

4.2Global vs Local User-DefinedFunctions

Page 14: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [14]

Page 15: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [15]

Local Variables

Program blocks are a bounded collection of code; they begin with a left brace ({) and end with a right brace (}). Each subprogram, including main, begins and ends with braces; therefore, each function forms at least one programming block. Program Local1.c has one programming block; this block begins at line 3 and ends at line 10.

PROGRAMLocal1.c

1- # include <stdio.h> 2 main()3- {/* <------------------------------------------------ Beginning of Block 1 */4- int5- W = 5;6- 7- printf ("W = %d\n",W); 8- W++; 9- printf ("W = %d\n",W); 10- }/* <------------------------------------------------------ End of Block 1 */

Several of the examples in this chapter include line numbers for easier reference; they must be removed prior to compilation.

Local Variables are those variables (of data types int, float, char, etc.) declared and initialized at the top of any programming block. Memory, for local variables, is allocated by the memory manager at the beginning of a block; these local variable exists until its memory is deallocated (returned to the memory manager) at the end of the block. A Local variable may be used, changed, within its block.

When line 3 of program Local1.c is executed, the memory manager allocates two bytes of memory for local variable W (it is initialized to 5). Local variable W may be used, printed, or changed only within its block.

Programming blocks may be nested (i.e. they be inserted within other programming blocks). Program Local2.c has two blocks; they are nested.

PROGRAMLocal2.c

1- # include <stdio.h> 2 main()3- {/* <----------------------------------------------- Beginning of Block 1 */4- int5- X = 5;6- 7- printf ("X = %d\n",X); 8- {/* <----------------------------------- Beginning of Block 2 */9- int10- Y = 8;11- 12- printf ("X = %d Y = %d\n",X,Y); 13- X++; 14- Y++; 15- printf ("X = %d Y = %d\n",X,Y); 16- }/* <--------------------------------------- End of Block 2 */17- printf ("X = %d\n",X); 18- }/* <---------------------------------------------------- End of Block 1 */

Block 1 extends from the opening brace on line 3 to its corresponding closing brace on line 18; local variable X may be used, printed, or changed within this

Page 16: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [16]

block. Block 2 extends from the opening brace on line 8 to its corresponding closing brace on line 16; local variable Y may be used, printed, or changed only within this block. A compile error would be generated if line 17 attempted to print the value of Y; it does not exist beyond the closing brace in line 16. Program blocks may be nested several levels deep; consult your compiler manual for exact specifics. A local variable exists only within the block in which it is declared.

Most variables will be declared at the beginning of the subprogram. When a subprogram has more than one block, the code should be indented to help identify the scope of the blocks and the intended logic.

Page 17: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [17]

Page 18: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [18]

Global Variables

Most programming languages support some type of global variables. As previously mentioned in chapter 3, global variables are variables whose symbolic names and contents are available within any of the program's subprograms (including main); in the C programming language global variables are declared at the bottom of Section II.

PROGRAMGlobal.c

1- # include <stdio.h> 2- int3- A = 2;4- 5 main()6- {/* <------------------------------------------------ Beginning of Block 1 */7- int8- B = 9;9- 10- printf ("A = %d B = %d\n",A,B); 11- A++; 12- B++; 13- printf ("A = %d B = %d\n",A,B); 14- }/* <------------------------------------------------------ End of Block 1 */

Just as a submerged submarine can only see that portion of the topside world visible in the periscope at any given instant in time, well-written computer programs are capable of accessing (print, change, etc.) only a portion of all of the variables that exist in the program at any given instant in time. Those global and local variables that can be accessed are said to be in-scope or visible; all other variables are said to be out-of-scope or invisible. In Global.c, A is a global variable; it is declared in section II. Global variables are in-scope to all functions that do not have a local variable or a parameter with the same symbolic name. Since function main has no local variable or parameter named A, global variable A may be used, changed, or printed from function main; it is in-scope. Function main has a local variable named B and no parameters.

Other subprograms could be added to Global.c; any other subprogram, that has no local variable or parameter named A, would be able use, change, or print global variable A as well.

One of the guidelines of good structured programming is to keep global variables to a minimum. Programs Global.c, Cube.c, PizaCost2.c, and AddProb.c are included in the text only to illustrate the scope of global variables. Although most well-written programs will have no global variables, it is important for students to understand the scope of both global and local variables.

If you have programmed in ANSI BASIC, all variables were global. The disadvantages of global variables are not always obvious to students writing small programs. Large computer programs, called systems, of today are generally constructed by teams of computer scientists. Each team completes and tests their own part of the system. The working parts are then combined to form a complete system. Imagine the problems that arise when multiple teams have used the same names for global variables; code which once worked independently is suddenly filled with errors. Programs that include global variables tend to be more difficult to maintain.

Page 19: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [19]

Page 20: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [20]

User-Defined Explicit-Functions

Section 3.5 illustrates many calls to standard library explicit-functions. Each of these functions explicitly return information. Notice that in explicit-function calls

x = fabs(-25);y = sqrt (25);w = sqrt (fabs(-20–5));

essential information is passed/transmitted (within parentheses) to the function. One or more arguments, sometimes called actual parameters, will normally be passed to an explicit-function. These arguments may be variables, constants, pointers (to addresses in memory), and/or expressions.

y = sqrt (25); /* Constant */y = sqrt (No); /* Variable */y = sqrt (20+10); /* Expression */y = sqrt (*Ptr) /* Pointer - section 4.5 */

It is relatively easy to envision the need for functions that are not on the list of standard mathematical functions available in C. For example, if you must frequently cube numbers, it would be convenient to have a user-defined function Cube so you could make an assignment such as

Total = Cube(No); /* First user-defined function */

In this example, the integer argument No is passed to explicit-function Cube in the function call above; if No contains 3, then the function call would replace the contents of integer Total with 27. When a function has more than one argument, they are separated by commas.

In business, a motel might like to have available a function to determine a customer's bill given the number in the party, the length of stay, and any telephone charges. Similarly, a hospital might like a function to compute the room charge for a patient given the type of room (private, ward, and so on) and various other options, including telephone (yes or no) and television (yes or no). Functions such as these are not standard functions. However, in C, we can create user-defined functions to perform these tasks.

Page 21: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [21]

Page 22: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [22]

Form for User-Defined Functions (explicit return)

Subprograms are generally placed in logical clusters after function main. The explicit-return-type for user defined functions may be a int, short int, long int, float, double, long double, char, pointer, etc. The form for a function is

Page 23: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [23]

Heading

Explicit-Return-Type FunctionName (parameter list)

Page 24: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [24]

Declaration Section

{ Define Local Variables User-Defined Data types}

Page 25: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [25]

Executable Section { (function statements)}

Page 26: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [26]

The parameter list in the explicit-function will generally contain one or more parameters, sometimes called a formal parameters; there will generally be one parameter associated with each and every argument passed. One solution to function cube might be

int Cube (int X) /* Function Header */{ /* <---------------------------------------------------- Beginning of Function */int /* Local Variables */CubedNo;

CubedNo = X * X * X; /* Body of Function */return (CubedNo); /* Body of Function */

} /* <---------------------------------------------------- End of Function */

Function Cube, above, has one parameter. We shall return to examine function Cube in Example 4.1.

Page 27: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [27]

Page 28: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [28]

Function Prototypes

Since C allows subprograms to be randomly placed within the executable section of the program, a prototype for each void–function and explicit-function (except main) must be placed at the bottom of the global declaration section of the program (Section II).

For beginning C programmers, the prototype is created by adding a semicolon the end of a copy of the subprogram header. The prototype for function Cube, above, would be

int Cube (int X);

The subprogram header should match the prototype. The most common prototype error that beginners make is forgetting the semicolon at the end. Beginners also make the mistake of placing a semicolon at the end of the subprogram header.

Page 29: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [29]

Page 30: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [30]

Function Guidelines

1. "FunctionName'' is any valid identifier.2. The function name should be descriptive.3. There will almost always be at least one element in the parameter list; thus,

sqrt(Y) and fabs (-21) are appropriate.4. In the calling program, the function name cannot be used on the left side of an

assignment statement.5. "Parameter list'' is a list of formal parameters. The number and order of

parameters in the parameter list should match the number and order of variables used when calling the explicit–function from subprograms.

6. The data type of parameters should match the corresponding data type of variables or values used when calling the explicit–function from subprograms. Casting these arguments is sometimes the easiest way to create matching data types.

7. "Return Type'' declares the data type for the required explicit return. This indicates what type of value will be returned to the calling function.

8. Explicit-functions can be used in expressions and assignment statements; for example,

X = sqrt(Y) - sqrt(Z);

9. Explicit-functions can be used in output statements; for example,

printf ("%8.3f\n", sqrt(3));

Page 31: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [31]

Page 32: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [32]

Explicit Function Example 4.1

Suppose we have an engineering application that requires the cubing of integers in more than a dozen of the calculations. Let us write a function to compute and explicitly return the cube of an integer.

This explicit-function is to return an integer with a return statement. Let us build a small program which tests function Cube. Section I contains the include for stdio.h.

PROGRAMCube.c

# define <stdio.h> /* Section I */

Section II contains global variable Total and the prototype for explicit-function Cube.

int Total = 10; /* Section II */int Cube (int X);

A small main program which can be used to test explicit-function cube is as follows:

main (){intNo = 3;

/* ------------------------------ Memory Map Cube-1 -----------------------------*/Total = Cube (No);printf ("Total = %d\n", Total);

/* ------------------------------ Memory Map Cube-4 -----------------------------*/}

A memory map includes a snapshot of all variables in-scope at some instant in time. Program execution begins with function main. Memory Map Cube-1 contains all of the variables that are in-scope at that instant in time:

Page 33: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [33]

Page 34: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [34]

When the line

Total = Cube (No);

is executed, execution flow transfers to function Cube. The code for function Cube is

int Cube (int X){intCubedNo;

/* ------------------------------ Memory Map Cube-2 -----------------------------*/CubedNo = X * X * X;

/* ------------------------------ Memory Map Cube-3 -----------------------------*/return (CubedNo);

}

X is the only parameter in the parameter list of function Cube. It is called a value parameter because the memory manager allocates two bytes of contiguous memory for local integer X and copies the value passed into the new variable. Since function Cube is called by line

Total = Cube (No); -> Total = Cube (3);

the value 3 is placed in value parameter X. The memory manager also allocates two bytes of contiguous memory for local integer variable CubedNo. Local variables X and CubedNo will be in-scope until the flow of execution exits function Cube. Memory Map Cube-2 contains

Page 35: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [35]

Page 36: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [36]

Notice that No, from main, is not in-scope at this time. The calculation fills CubeNo with X * X * X. Memory Map Cube-3 reflects the variables in-scope after the calculation.

Page 37: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [37]

Page 38: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [38]

As execution exits function Cube, the memory allocated for X and CubeNo is de-allocated; this memory is returned to the memory manager to be used as needed; variables X and CubeNo cease to exist. The return statement explicitly returns the value stored in CubeNo (27) into Total (in main). The printf statement prints

Total = 27

Memory Map Cube-4 reflects those variables in-scope after the printf statement.

Page 39: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [39]

Page 40: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [40]

There are often many ways to solve a problem. The code below is also a more efficient alternative for function Cube.

int Cube (int X){return (X * X * X);

}

Combinations of constants, expressions, variables, or cast values serve as arguments in the function call. The code fragment below contains several different types of function calls to Cube; these function calls may be placed in any subprogram, including main.

long int K = 400;

float L = 45.5;

int A, B, C, D, E, X = 5, Y = 6, Side = 7;

A = Cube(5);B = Cube(3) + Cube(X) + fabs(Y);printf ("The Volume = %d cubic units\n", Cube(Side));C = fabs(Cube(-3) + X) + pow(3,4);D = Cube ((int) K);E = Cube ((int) L);

Example 4.2Let's write an explicit-function which accepts a rectangles Length and Width

as parameters and explicitly returns its area.

float AreaRectangle (float Length, float Width){floatArea;

Area = Length * Width;return (Area);

}or

float AreaRectangle (float Length, float Width){return (Length * Width);

}

Explicit-function AreaRectangle, above, has two parameters; a coma is used to separate the two value parameters in the parameter list. The header specifies the data type for each parameter immediately to the left. When the first line of this function is executed, the memory manager will allocate two bytes of contiguous memory for integer value parameter Length; Length is initialized with the value of the first argument in the call statement. The memory manager will also allocate two bytes of contiguous memory for integer value parameter Width; Width is initialized with the value of the second argument of the call statement.

Typical calls to this function from main (or any other subprogram) would be

Area1 = AreaRectangle(5,3);

Page 41: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [41]

Area1 = AreaRectangle(Length1,Width1);printf ("The Area = %f square units\n", AreaRectangle(3,4));C = fabs(Cube(-3) + X) + AreaRectangle (3,4);

Example 4.3Let's write a function which accepts the Radius of a circle as a parameter and

explicitly returns the area of the circle.

# define PI 3.14float AreaCircle (float Radius){return (PI * Radius * Radius);

}

Typical calls to function AreaCircle from main (or any other subprogram) would be

Area1 = AreaCircle(4);Area2 = AreaCircle(5.3);TotalArea2 = 2 * AreaCircle (Radius1);printf ("The Area = %f square units\n", AreaCircle(3.4));

Example 4.4ANSI C does provide a power function (pow) for exponenation. However, now

that you know how to write a function, let us use the built-in functions log and exp to write our very own power function. Before writing this, however, let's consider how these functions can be used to produce the desired result.

First, exp and log are inverse functions in the sense that

exp(log(X)) = X

for all positive X. Thus, we have

3= exp( log(3))

Using properties of logarithms,

log (a) = b * log(a)

Hence,

exp( log(3) = exp ((2.5) * log (3))

Since each of these operations can be performed in ANSI C, we can compute

3= exp( log(3)) = exp ((2.5) * log (3))

or more generally,

A= exp( log(A)) = exp ((X) * log (A))

If we let Base denote the base A and Exponent denote the exponent X, we can now write an explicit-function Power as

double Power (double Base, double Exponent){return (exp(Exponent * log(Base)));

}

Page 42: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [42]

This can be called from the main function by

Base = 3;Exponent = 2.5;Num1 = Power(Base, Exponent);Num2 = Power(2, 8);

Exercises 4.21. Explain the difference between local and global variables.

2. State the advantages of using local variables.

3. Indicate which of the following are valid explicit-function headings. Explain what is wrong with those that are invalid.

a. void RoundTenth (float X)

b. float MakeChange (X : integer, Y: real)

c. int Max (int M1, float M2, char M3 )

d. char Sign (Num float);

4. Find all errors in each of the following functions.

a. int Average (int N1, N2 ); {int

Avr; Avr = (N1 + N2) / 2 }

b. int Total (int L1; int L2)int

Sum;{

Sum = L1 + L2RETURN (Sum)

}

c. float AreaTriangle (float Height; float Base)int

Area;{

Area = 1/2 * Height * Base:return (area);

}

5. Write an explicit-function for each of the following:

a. Round a real to the nearest tenth.b. Round a real to the nearest hundredth.c. Convert degrees Fahrenheit to degrees Celsius.d. Compute the charge for cars at a parking lot; the rate is 75 cents per hour

or fraction thereof.

Page 43: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [43]

6. Write function Square and function Cube. Use them in a program to print a chart of the integers 1 to 5 together with their squares and cubes. Output from this program should be

Number Number Squared Number Cubed------ -------------- ------------ 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125

7. Explicit-functions SurfaceArea and Volume perform rectangular prism calculations on Length, Width, and Height parameters. The main program shall print a header and all calculations for the partially completed chart below:

Length Width Height Surface Area Volume------ ------ ------ ------------ ------- 10.0 10.0 10.0 60.00 1000.00 15.0 15.0 15.0 510.4 811.4 218.9 999.9 888.8 777.7

8. The factorial of a positive integer n is /* Super Challenge Problem - Try to write a function which calls itself */

n! = n * (n –1) * ... * 2 * 1.

Write a function (Factorial) that will compute and explicitly return n!.

Page 44: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [44]

Page 45: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [45]

The void-function and the explicit-function are identical in form with the exception of the heading; the Explicit-Return-Type is replaced by the keyword void to indicate that nothing is explicitly returned. Some C programmers call these procedures.

Page 46: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [46]

Heading

void FunctionName (parameter list)

Page 47: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [47]

Declaration Section

{ Define Local Variables User-Defined Data types}

Page 48: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [48]

Executable Section { (function statements)}

Page 49: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [49]

Page 50: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [50]

Page 51: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [51]

Void-functions Without ParametersExample 4.5

Some void-functions are written without parameters because they require no data transmission to or from the main function (or any other subprogram). Void-functions are often used to print headings or closing messages for output. For example, suppose you are writing a program for Our Lady of Mercy Hospital and you wish the billing statement for each patient to have the heading

////////////////////////////////////////////////////////////// //// Our Lady of Mercy Hospital //// -------------------------- //// //// Our Lady of Mercy Hospital //// 1306 Central City //// Phone (416) 333-5555 //// //// //////////////////////////////////////////////////////////////

A void–function, called DisplayHeading, can be written to print this message and you can then call it from main. Function main is as follows:

main () { DisplayStatementHeading();}

The code for void–function DisplayStatementHeading could be as follows:

void DisplayStatementHeading(void){printf ("\n\n%s\n",MARKS);printf ("%s\n",EDGE);printf ("// Our Lady of Mercy Hospital //\n");printf ("// -------------------------- //\n");printf ("%s\n",EDGE);printf ("// Our Lady of Mercy Hospital //\n");printf ("// 1306 Central City //\n");printf ("// Phone (416) 333-5555 //\n");printf ("%s\n",EDGE);printf ("%s\n",EDGE);printf ("%s\n",MARKS);

}

The reserved word void at the beginning of the subprogram header indicates that this subprogram has no explicit return; it is a void–function. The word void, between the parentheses, indicates that no parameters are passed to this void–function. The prototype for the DisplayStatementHeading is

void DisplayStatementHeading(void);

Program Mercy.c places each of the program fragments above into a working program.

PROGRAMMercy.c

Page 52: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [52]

/* Section I - Preprocessor Directives - Includes and Global Defines */# include <stdio.h># define MARKS "////////////////////////////////////////////////////////////"# define EDGE "// //"

/* Section II - Global User Defined Data types, Prototypes, & Global Variables */void DisplayStatementHeading(void);

/* Section III - Execution Section - Function Main & All Other Subprograms */

main () {DisplayStatementHeading();

}

void DisplayStatementHeading(void){printf ("\n\n%s\n",MARKS);printf ("%s\n",EDGE);printf ("// Our Lady of Mercy Hospital //\n");printf ("// -------------------------- //\n");printf ("%s\n",EDGE);printf ("// Our Lady of Mercy Hospital //\n");printf ("// 1306 Central City //\n");printf ("// Phone (416) 333-5555 //\n");printf ("%s\n",EDGE);printf ("%s\n",EDGE);printf ("%s\n",MARKS);

}

Preprocessing is the work done by the compiler prior to actual compilation of the program. Preprocessing directives are written one to a line and the first non-white space character is #. The include statement and the define statements are both preprocessing directives. During preprocessing, the file of code associated with each of the include statements is automatically inserted into memory just as if you had typed it into your program yourself. During preprocessing, the define values will automatically replace all references.

Let us walk through the execution of this program. Program Mercy.c has one include statement; the code from file stdio.h will be inserted at the top of the program. The program has two defines; during preprocessing, the respective slashes and blanks will replace all symbolic references to EDGE and MARKS. Function main has only one subprogram call; when DisplayStatementHeading is executed, the commercial is displayed.

Let us return to the PizaCost1.c program from chapter 2. By using global variables, the three components of the pizza problem can be solved with three void-functions that have no parameters.

PROGRAMPizaCost2.c

# include <stdio.h># define PI 3.14

floatDiameter, Price, PricePerInch;

void GetData (void);void PerformComputations (void);

Page 53: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [53]

void PrintResults (void);

main () {GetData ();PerformComputations ();PrintResults ();

}

void GetData (void){printf ("Enter the pizza cost and press <RETURN> : $");scanf ("%f",&Price);printf ("Enter the pizza size (diameter inches) and press <RETURN> : ");scanf ("%f",&Diameter);

}

void PerformComputations (void){ floatRadius, Area;

Radius = Diameter / 2.0;Area = PI * Radius * Radius;PricePerInch = Price / Area;

} void PrintResults (void){printf("\n");printf ("The price per square inch is $%6.2f \n", PricePerInch);

}

Output from Program PizaCost2.c is as follows:

Enter the pizza cost and press <RETURN> : $10.50Enter the pizza size (diameter inches) and press <RETURN> : 16

The price per square inch is $ 0.05

Diameter, Price, and PricePerInch are global variables; they may be used, changed, or printed within main, GetData, PerformComputations, or PrintResults.

A prototype is required for each of the three void-functions. Notice that the parentheses, containing the word void, must be included in both the prototype and the function header; this tells the compiler that there nothing is passed to the void-function. The word void does not appear in the call.

PizaCost3.c, section 4.5, illustrates a much better solution to the pizza problem; it does not use global variables.

Page 54: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [54]

Page 55: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [55]

Program Execution

One of the advantages of well written subprograms is that they may be called many times (from different places) within a single program. Program AddProb.c has two void-functions, each of which are called twice.

1. Get Problem 1.1 gets username 1.2 scanf Addend1, Addend2

2. Display Problem 2.1 display addition problem

In order to better understand memory management and the execution of C programs, let us now step behind the scenes and walk, step-by-step, through program AddProb.c

PROGRAM AddProb.c

I. Source file AddProb.c is loaded into memory.

1- /* Internal Program Documentation */ 2- # include <stdio.h> 3- # define MARKS "////////////////////////////////////////////////////////////" 4-

II. During preprocessing, the code for stdio.h replaces the directive at line 2. During preprocessing, both references to character constant MARKS (lines 18 & 22) are replaced by the appropriate string of forward slashes.

Although the blank lines help readability of the program code, they are ignored by the compiler. Comment lines are also ignored by the compiler. Neither the comment lines, nor the blank lines, increase the size of the binary object code generated by the compiler.

5- void GetProblem(void); /* Prototypes */ 6- void DisplayProblem(void); 7-

III. All user defined data types are loaded into memory; since this program has no user defined data types, only int, char, float, double, and their variations will be recognized. In the future, a user defined data type might include EmployeeType (has sub-components of Name, Age, SocialSecurityNo, RatePerHour all bundled together within one structure).

IV. The prototypes will be loaded into a table for future reference so that the return values and the parameters may be checked for correctness. Even though the actual code for GetProblem and DisplayProblem has not been processed, the calls to these void-functions in main can be managed correctly because of the prototypes.

8- int /* Global Variables */ 9- Addend1 = 10,10- Addend2 = 20;11-

Page 56: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [56]

V. In addition to assigning a symbolic name by which the global variable can be referenced, the declaration statement may also initialize the global variable. Global integer variables Addend1 and Addend2 are allocated and initialized to 10 and 20 respectively.

12- main () 13- {14- int15- No = 3; /* Memory Map AddProb-1 - After this line */

VI. Execution flow of all C programs begins with function main. a. The memory manager assigns memory for the local variable as each

block is entered. In addition to assigning a symbolic name by which the memory can be referenced, the declaration statement may also initialize the variable.

At lines 14-15, the memory manager allocates 2 bytes of contiguous memory for local variable No; it is initialized to 3. Examine memory map AddProb-1 below. As mentioned previously, the actual addresses within all memory maps are assigned by the memory manager; your addresses will probably be different.

Page 57: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [57]

Page 58: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [58]

16- GetProblem(); /* Memory Map AddProb-2c - After This Line */

b. Void-function GetProblem is called from within main. Before control passes to the GetProblem, the following set of information is pushed to a stack: (1) symbolic references to local variables (No), (2) symbolic references to parameters (none) passed to the calling subprogram (main), and (3) the return address (where to return to when finished with GetProblem - end of line 16). The stack data structure will be discussed later; for the moment let us suffice to say that the stack is an information container in which the last collection of information pushed to the stack will be the first collection of information popped (retrieved) from the stack. The stack helps to maintain the scope of variables and maintain execution flow from subprogram to subprogram. Execution flow is now transferred to the GetProblem void–function. Take a moment to examine the code at the bottom of this program (lines 24-36).

GetProblem begins. The memory manager allocates ten bytes of contiguous memory for local character string variable Name. The content of Name is unknown. Memory Map AddProb-2a reflects the contents just after the declaration of local variable Name. Local variables (No) and Parameters ( ) of the calling subprogram (main) are not visible within GetProblem. The stack contains (a) references to all parameters passed to main (none), (b) references to all local variables of main (No-2236646) and (c) the return address (end of line 16).

Page 59: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [59]

Page 60: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [60]

As the execution flow continues through GetProblem; the user interactively fills global variables Addend1 and Addend2. Let us assume that the Input/Output (I/O) from void–function GetProblem are as follows:

Enter Name : BobEnter Addend1 : 276Enter Addend2 : 385

Page 61: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [61]

Page 62: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [62]

Memory Map AddProb-2b reflects memory just prior to exiting GetProblem. As the block is exited, the memory provided for variable Name is de-allocated.

When the execution flow reaches the bottom of GetProblem, the last set of information is popped (removed) from the stack. This stack information brings local variables (No) and parameters passed (none) into view and directs the execution flow to continue at the end of line 16.

Memory Map AddProb-2c is taken immediately prior to executing line 17 of main.

Page 63: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [63]

Page 64: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [64]

17- DisplayProblem(); /* Memory Map 3c - After This Line */

c. Void Function DisplayProblem is now called from main. Before control passes to DisplayProblem, symbolic references to local variables (No) and parameters (none) passed to the calling function (main) are pushed on a temporary stack and become invisible. The return address (end of line 17) is pushed on a temporary stack. Execution flow is now transferred to DisplayProblem.

DisplayProblem begins. The memory manager provides two bytes of contiguous memory for local integer variable Sum . The content of Sum is unknown. Notice in Memory Map AddProb-3a that local variable No (from main) is not in-scope. Neither is Name, from GetProblem, in-scope.

Page 65: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [65]

Page 66: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [66]

Execution flow continues through DisplayProblem; the addition problem is displayed on the monitor (stdout).

276 385 + ____ 661

Page 67: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [67]

Page 68: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [68]

Memory Map AddProb-3b reflects memory just prior to exiting DisplayProblem. As the block is exited, the memory provided for local variable Sum will be de-allocated.

When the execution flow reaches the bottom of DisplayProblem, the last set of information is popped (removed) from the stack. This stack information brings local variables (No) and parameters passed (none) into view and directs the execution flow to continue at the end of line 17.

Memory Map AddProb-2c is taken immediately prior to executing line 18 of main.

Page 69: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [69]

Page 70: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [70]

18- printf ("\n%s\n\n",MARKS);

d. The following is displayed on the monitor (stdout):

////////////////////////////////////////////////////////////

19- No = No + 1;

e. The contents of local variable No become 4.

20- GetProblem(); /* Memory Map 4c - After This Line */

f. Function GetProblem is once more called from within main. Before control passes to function GetProblem, (1) symbolic references to local variables (No), (2) parameters (none) passed to the calling function (main), and (3) the return address (end of line 20) are pushed to the stack. Execution flow is now transferred to GetProblem.

GetProblem begins. The memory manager once more allocates ten bytes of contiguous memory for local character string variable Name. The memory allocated to Name need not be the same as that allocated on previous calls to GetProblem. The content of Name is unknown. Memory Map AddProb-4a reflects the contents just after the declaration of local variable Name.

Page 71: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [71]

Page 72: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [72]

Execution flow continues through GetProblem; the user interactively fills global variables Addend1 and Addend2. Let us assume that the Input/Output (I/O) from GetProblem are as follows:

Enter Name : CarolEnter Addend1 : 23Enter Addend2 : 177

Page 73: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [73]

Page 74: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [74]

Memory Map AddProb-4b reflects memory just prior to exiting GetProblem. As the block is exited, the memory provided for local variable Name will be de-allocated.

When the execution flow reaches the bottom of GetProblem, the last set of information is popped (removed) from the stack. This stack information brings local variables (No) and parameters passed (none) into view and directs the execution flow to continue at the end of line 20.

Memory Map AddProb-4c is taken immediately prior to executing line 21 of main.

Page 75: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [75]

Page 76: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [76]

21- DisplayProblem(); /* Memory Map 5c - After This Line */

g. Function DisplayProblem is once more called from within main. Before control passes to function, (1) symbolic references to local variables (No), (2) parameters (none) passed to the calling function (main) and (3) the return address are pushed to the stack. Execution flow is now transferred to DisplayProblem.

DisplayProblem begins. The memory manager provides two bytes of contiguous memory for local integer variable Sum . The content of Sum is unknown. Notice in Memory Map AddProb-5a that local variable No (from main) is visible within DisplayProblem.

Page 77: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [77]

Page 78: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [78]

Execution flow continues through DisplayProblem; the addition problem is displayed on the monitor (stdout).

23 177 + ____ 200

Page 79: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [79]

Page 80: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [80]

Memory Map AddProb-5b reflects memory just prior to exiting DisplayProblem. As the block is exited, the memory provided for local variable Sum will be de-allocated.

When the execution flow reaches the bottom of DisplayProblem, the last set of information is popped (removed) from the stack. This stack information brings local variables (No) and parameters passed (none) into view and directs the execution flow to continue at the end of line 21.

Memory Map AddProb-5c is taken immediately prior to executing line 22 of main.

Page 81: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [81]

Page 82: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [82]

22- printf ("\n%s\n\n",MARKS);23- }

h. Once more MARKS is printed and the program terminates with the closing brace [LINE 22] of function main.

The following is displayed on the monitor (stdout):

////////////////////////////////////////////////////////////

24- void GetProblem(void)25- { 26- char27- Name[10];28- /* Memory Map AddProb-2a & 4a */29- printf ("\nEnter Name : ");30- gets (Name);31- printf ("Enter Addend1 : ");32- scanf ("%d",&Addend1);33- printf ("Enter Addend2 : ");34- scanf ("%d",&Addend2);35- fflush (stdin);36- } /* Memory Map AddProb-2b & 4b */

37- void DisplayProblem(void)36- { 39- int40- Sum;41- /* Memory Map AddProb-3a & 5a */42- Sum = Addend1 + Addend2;43- printf ("\n\n%10i\n%10i\n + ______\n%10i\n",Addend1, Addend2, Sum);44- } /* Memory Map AddProb-3b & 5b */

i. Notice that the blank lines used to separate compiler directives, prototypes, and functions help to increase the readability of the code. The blank line after the local variables of each function also make the program more readable.

j. The statement numbers, representing the execution flow from this program, are

1,2,3,4,5,6,7,8,9,10,11, 12,13,14,15,16, 24,25,26,27,28,29,30,31,32,33,34,35,36,17, 37,38,39,40,41,42,43,44, 18,19,20, 24,25,26,27,28,29,30,31,32,33,34,35,36,21, 37,38,39,40,41,42,43,44, 22, 23

Exercises 4.31. Discuss the difference between a void–function and a function.

2. Review the following program:

int X = 44;T = 33; /* 860300 */

char

Page 83: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [83]

Ch = 'A';

main () 1{ 2int 3

A = 1, /* 860400 */ 4B = 2; /* 860402 */ 5

float 6X = 3.3; /* 860404 */ 7

char 8Ch = 'B'; /* 860408 */ 9

10/* ------------- Memory Map 1 ---------------- */ 11

Sub1 (); 12/* ------------- Memory Map 4 ---------------- */ 13

Sub2 (); 14/* ------------- Memory Map 7 ---------------- */ 15} 16 17void Sub1 (void) 18{ 19int 20

B1 = 4; /* 860500 */ 21/* ------------- Memory Map 2---------------- */ 22

T = X + T; 23T++; 24printf ("%c",-- Ch); 25

/* ------------- Memory Map 3 ---------------- */ 26} 27 28

void Sub2 (int X, int Y) /* 860600, 860604 */ 29{ 30float 31

A = 3.14; /* 860608 */ 32char 33

C = 'D'; /* 860412 */ 34/* ------------- Memory Map 5 ---------------- */ 35

Ch = C; 36X = A; 37

/* ------------- Memory Map 6 ---------------- */ 38} 39

a. List all global variables.b. Write the prototypes for the program.c. The numbers in comments beside each of the declarations represent the

addresses assigned by the memory manager. Notice that the comments contain the desired locations for the seven memory maps and the starting addresses for provided by the memory manager. Construct Memory Maps 1–7.

d. Write the statement numbers representing the execution flow from this program. Use the line numbers on the far right.

Page 84: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [84]

Page 85: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [85]

4.4Passing Value Variables

Page 86: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [86]

Page 87: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [87]

Parameters & ArgumentsExample 4.6

Passing arguments to void-functions is no different than passing information to explicit-functions. The arguments passed to void-functions may be variables, constants, pointers (to addresses in memory), and/or expressions.

DisplayAdditionProblem (3, 22); /* Constant */DisplayAdditionProblem (Add1, Add2); /* Variable */DisplayAdditionProblem (2+3, 12-X+Y); /* Expression */DisplayAdditionProblem (2, Add2); /* Constant & Variable */DisplayAdditionProblem (*Ptr1, *Ptr2); /* Pointers-Section 4.5 */

void DisplayAdditionProblem ( int FirstNumber, int SecondNumber){/* Code Necessary To Complete The Task */

}

When the first line of this function is executed, the memory manager will allocate two bytes of contiguous memory for integer value parameter FirstNumber and initialize it with the integer value of the first argument. The memory manager will also allocate two bytes of contiguous memory for integer value parameter SecondNumber and initialized with it with the integer value of the second argument.

Page 88: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [88]

Page 89: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [89]

Program PrtNum.c will provide an opportunity to examine the scope of variables in the selective memory maps embedded within the code.

PROGRAMPrtNum.c

# include <stdio.h>

void PrintNum (int N1, int N2 ,float N3); /* prototype */

main () {intNum1, Num2;

floatNum3 ;

Page 90: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [90]

Page 91: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [91]

Num1 = 5;Num2 = 8; Num3 = Num2 / Num1; /* Note Integer Division */

Page 92: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [92]

Page 93: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [93]

PrintNum (Num1, Num2, Num3);

Page 94: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [94]

Page 95: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [95]

}

/************************************************/

void PrintNum (int N1, int N2 ,float N3){

Page 96: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [96]

Page 97: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [97]

printf ("N1 = %3d\n", N1);printf ("N2 = %3d\n", N2);printf ("N3 = %6.2f\n", N3);N1 = N1 * N2;

Page 98: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [98]

Page 99: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [99]

}

The output from PrtNum.c is as follows:

N1 = 5N2 = 8N3 = 1.00

The formal parameters of PrintNum are N1, N2, and N3. Subprogram PrintNum is called from main; Num1, Num2, and Num3 are arguments (actual parameters) in this call statement. Let us now examine the relationship between the parameter list in the header

void PrintNum (int N1, int N2 ,float N3)

and the call

PrintNum (Num1, Num2, Num3);

In this case, Num1 corresponds to N1, Num2 corresponds to N2, and Num3 corresponds to N3. Notice that both the number and data type of variables in the parameter list correspond with the number and type of variables listed in the call.

As previously explained, N1 (&2655332) is a copy of Num1 (&2477876); changes made to N1 within PrintNum have no effect on Num1 (out-of-scope). Changing N1 to 40 had no effect on Num1! See memory map PrtNum-5.

Exercises 4.41. Indicate which of the following are appropriate void–function headings.

Explain the problem with those that are inappropriate.

a. void Prac1 (int A , Y );

b. void Error (char Ch1; char Ch2 )

c. void Prac2 (int A, float B, char C, long int D, double E)

d. void Prac3 ( int A,int B,

float S,float T.char Ch)

2. Listed below are header statements for three void-functions. There are many ways in which these void-functions could be called from function main. Write at least one void–function call for each of the following void-functions that could be used in main.

a. void Prob5 (int A, int B , char Ch)

b. void PrintHeader(void)

c. void PrintMax (int N1, int N2, int NewMax)

3. Suppose a program contains the following void–function:

void Switch (int A, int B )

Page 100: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [100]

{int

Temp;

printf ("Start => A = %d B = %d \n", A, B);Temp = A;A = B;B = Temp;printf ("End => A = %d B = %d \n", A, B);

}

Indicate the output from each of the following fragments of code in the main

a. main () { int

Num1 = 5,Num2 = 10;

printf ("Num1 = %d Num2 = %d \n", Num1, Num2);Switch (Num1, Num2);printf ("Num1 = %d Num2 = %d \n", Num1, Num2);Switch (Num1, Num2);

printf ("Num1 = %d Num2 = %d \n", Num1, Num2);}

b main () { int

N = 3,M = 20;

printf ("N = %d M = %d \n", N, M);Switch (N, M);printf ("N = %d M = %d \n", N, M);Switch (N, M);

printf ("N = %d M = %d \n", N, M);}

4. Write a void–function for each of the following and indicate how it would be called from the main function.

a. Print the heading for the output.

Acme National Electronics Board of Directors Annual Meeting

b. Print Volume of a Sphere; real number Radius is passed to the void–function.

5. Explain the difference between parameters and arguments.

1- # define PI 3.14 2- int 3- Max;

Page 101: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [101]

4- 5- main () 6- { 7- int 8- a=1,b=2,c=3; 9- /* Memory Map A */10- Mod1(a,b,c);11- /* Memory Map C */12- }13- 14- void Mod1 ( int x, int y, int z)15- {16- int17- Sum;18- 19- Sum = x + y + z;20- printf ("Sum = %d\n", Sum);21- /* Memory Map B */22- }

6. In the program above,

a. List the preprocessor directives.b. List the global variables.c. List the variables local to the main function.d. List the variables local to the Mod1 void–function.e. List the arguments passed to Mod1.f. List the parameters of Mod1.g. Sketch Memory Maps A, B, & C. As memory manager, begin assigning

addresses with location 1200000.h. List the statement numbers representing the flow of the program.i. List the program fragment that could be inserted into void–function Mod1

that would print the memory map information for all parameters, local variables, and global variables within void–function Mod1.

j. List the program fragment that could be inserted into void–function Mod1 that would print the memory map information for all local variables and global variables within main.

7. Review the following program:

int 1T = 33; /* 830300 */ 2

3main () 4{ 5int 6

A = 1, /* 830400 */ 7B = 2; /* 830402 */ 8

float 9X = 3.3; /* 830404 */ 10

char 11Ch = 'A'; /* 830408 */ 12

/* ------------------ Memory Map 1 ------------------- */ 13Sub1 (B); 14

/* ------------------ Memory Map 4 ------------------- */ 13Sub2 (A, B); 16

Page 102: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [102]

/* ------------------ Memory Map 7 ------------------- */ 13Sub3 (Ch); 18

/* ------------------ Memory Map 10 ------------------ */ 13} 20

21void Sub1 (int Z) /* 830500 */ 22{ 23int 24

B1 = 4; /* 830504 */ 25/* ------------------ Memory Map 2 ------------------- */ 13

Z = B1 + Z; 27

T++; 28B1++; 29

/* ------------------ Memory Map 3 ------------------- */ 13} 31

32void Sub2 (int X, int Y) /* 830600, 830604 */ 33{ 34float 35

A = 3.14; /* 830608 */ 36char 37

Ch = 'D'; /* 830412 */ 38/* ------------------ Memory Map 5 ------------------- */ 13

X = X + Y; 40

Y = A ++; 41Ch++; 42

/* ------------------ Memory Map 6 ------------------- */ 13} 44void Sub3 (char X) /* 830700 */ 45{ 46/* ------------------ Memory Map 8 ------------------- */ 13

X++; 48

T++; 49/* Memory Map 9 */ 50} 51

a. List all global variables.b. Write the prototypes for the program.c. The numbers in comments beside each of the declarations represent the

addresses assigned by the memory manager. Construct Memory Maps 1–10).

d. Write the statement numbers representing the execution flow from this program. Use the line numbers on the far right.

8. Write a test program to find what happens if the parameter lists in the prototype does not match void–function call in the main function. Investigate the following:

a. Correct number of parameters (correct data types) , wrong orderb. Correct number of parameters (wrong data types) , right orderc. Incorrect number of parameters

Page 103: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [103]

Page 104: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [104]

4.5Pointers &De-referencing

Page 105: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [105]

Page 106: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [106]

Pointer Declaration and Assignment

Some high-level languages allow two-way passing of variables called passing by reference. Pascal is one such language. When a variable is passed by reference, changes made in a subprogram actually change the original variable. Although C has no mechanism for passing by reference, we will learn to change original variables by passing pointers.

The concept of pointers is very important in most programming languages. Knowledge of pointers in C is critical; pointers shall be used with arrays, strings, files, and the passing of parameters.

In C we can display addresses associated with symbolic variables in several ways. In review, we have already printed out the address associated with symbolic variable N1 with printf statements like the following:

int N1;

printf("The Hex Address Associated with N1 = %X\n",&N1);printf("The Address Associated with N1 = %lu\n",&N1);

We have already allowed the scanf function to fill the address associated with N1 with a statement like:

scanf("%d",&N1);

Let us declare the following local variables in function main:

intAge = 18,*PtrToAge;

The first variable, Age, is an integer; the memory manager allocates two bytes of contiguous memory for Age and the compiler initializes Age to 18. The second variable is a pointer to an integer; PtrToAge shall be used to hold the address of some integer variable; the content of this variable is unknown (Memory Map A). The memory manager will allocate the number of bytes necessary to store a pointer variable.

Page 107: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [107]

Page 108: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [108]

Since the contents of a pointer is an address in memory, pointers need be only large enough to store the largest address possible for the specific computer. The number of bytes allocated to a pointer will vary because (1) all computers do not have the same memory capacity and (2) all computers do not use the same addressing. The following line of code will allow you to determine the size of a pointer on your computer.

printf("Pointers Are Allocated %ld bytes\n",sizeof(PtrToAge));

Pointers Are Allocated 4 bytes

Four-byte pointers are common; the thirty-two bits would allow the computer memory to be expanded to 2bytes (4,294,967,296). We shall assume a four-byte pointer size throughout this text.

PtrToAge = &Age;

Pointers may be assigned to an address (of matching data type) or another pointer (of matching data type). The pointer assignment statement above places the address, associated with symbolic integer variable Age, into variable PtrToAge. Examine Memory Map B. Age is stored at address 1196538 (abbreviated &1196538). A compilation error will be generated if PtrToAge were assigned to the address of a float variable or the address of a char variable; the data types must match.

Page 109: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [109]

Page 110: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [110]

The arrow, on memory map above, is used to illustrate the relationship between the pointer and the variable to which it points. The following code segment could be used to display the critical components of the memory map above.

printf ("%14s%20s\n","Age[int]","PtrToAge[int *]");printf (" -------------- --------------\n");printf (" |%6d | |%10p |\n",Age,PtrToAge);printf(" -------------- --------------\n");printf ("%11p-%d%17p-%d\n",&Age,sizeof(Age),

&PtrToAge,sizeof(PtrToAge)); Output:

Age[int] PtrToAge[int *] -------------- -------------- | 18 | | 1196538 | -------------- -------------- 1196538-2 1196534-4

Let us now create Memory Map Ptr-1 for the following declarations:

floatPayPerHour = 7.50,*PayPtr;

charMiddleInitial = 'E',*InitialPtr;

Page 111: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [111]

Page 112: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [112]

Without looking at Memory Map Ptr-2, attempt to show the memory map as it would be after the following pointer assignment statements:

InitialPtr = & MiddleInitial;PayPtr = & PayPerHour;

Now check your work!

Page 113: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [113]

Page 114: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [114]

Let us now create Memory Map Quantity-1 for the following declarations and assignments:

unsigned long intQuantityInStock= 200000;

floatPayPerHour = 7.50;

unsigned long int*QuantityPtr1,*QuantityPtr2;

QuantityPtr1 = &QuantityInStock;QuantityPtr2 = QuantityPtr1;

Page 115: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [115]

Page 116: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [116]

The address in one pointer may be assigned to the address in another pointer (of matching data types). In the illustration above, both QuantityPtr1 and QuantityPtr2 point to QuantityInStock.

Page 117: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [117]

Page 118: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [118]

De-referencing Pointers

Thus far we have printed the addresses of pointers and the addresses contained within pointers. We have also assigned pointers to the address of a variable (of appropriate data type). We have transferred the address contained in one pointer to another pointer (of like data type). It is now time to use the pointer to change the contents of the original memory location; we shall do this by dereferencing the pointer.

As previously mentioned, all parameters passed to C subprograms are passed by value. Pointers are a valid data type and may be included within the parameter list. In program Switch.c, the main function has two local integer variables X, and Y.

Let us examine a program which uses a void–function, SwitchIntegers, to switch the contents of variables X and Y.

PROGRAMSwitch1.c

# include <stdio.h>

void SwitchIntegers (int *FirstPtr, int *SecondPtr);

main () {intX=5, Y=8;

printf ("%d - %d\n",X,Y);SwitchIntegers (&X,&Y);printf ("%d - %d\n",X,Y);

}

void SwitchIntegers (int *FirstPtr, int *SecondPtr){intTemp;

Temp = *FirstPtr;*FirstPtr = *SecondPtr;*SecondPtr = Temp;

}

Output from Switch1.c is as follows:

5 - 88 - 5

The addresses of X and Y are arguments in the call to function SwitchIntegers. The argument (&X) is matched with the parameter pointer (FirstPtr) and the argument (&Y) is matched with parameter pointer (SecondPtr). It is by dereferencing these pointers that the contents X and Y are exchanged.

Program Switch2.c provides a memory dump that might help you to better understand what has happened in program Switch1.c. This type of memory dump will be quite helpful in debugging errors related to the transfer of information between subprograms.

Page 119: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [119]

PROGRAMSwitch2.c

# include <stdio.h>

void SwitchIntegers (int *FirstPtr, int *SecondPtr);main () {intX=5, Y=8;puts("------------------ Beginning of main ---------------------\n");printf ("%14s%16s\n","X[int]","Y[int]");printf (" -------------- --------------\n");printf (" |%6d | |%6d |\n",X,Y);printf(" -------------- --------------\n");printf ("%11p-%d%17p-%d\n\n",&X,sizeof(X),&Y,sizeof(Y));

SwitchIntegers (&X,&Y);

puts("-------------------- End of main ------------------------\n");printf ("%14s%16s\n","X[int]","Y[int]");printf (" -------------- --------------\n");printf (" |%6d | |%6d |\n",X,Y);printf(" -------------- --------------\n");printf ("%11p-%d%17p-%d\n\n",&X,sizeof(X),&Y,sizeof(Y));

}

void SwitchIntegers (int *FirstPtr, int *SecondPtr){intTemp = 0; /* Initialized to 0 for memory map output only - not efficient */

puts("------------- Beginning of SwitchIntegers ---------------\n");printf ("%16s%18s%16s\n","FirstPtr[int]","SecondPtr[int]","Temp[int]");printf (" -------------- -------------- ---------------\n");printf (" |%10p | |%10p | |%6d |\n",FirstPtr,SecondPtr,Temp);printf (" -------------- -------------- ---------------\n");printf (" |->%4d | |->%4d |\n",*FirstPtr,*SecondPtr);printf(" -------------- --------------\n");printf ("%11p-%d%17p-%d%17p-%d\n\n",&FirstPtr,sizeof(FirstPtr),

&SecondPtr,sizeof(SecondPtr),&Temp,sizeof(Temp));

Temp = *FirstPtr;*FirstPtr = *SecondPtr;*SecondPtr = Temp;

puts("---------------- End of SwitchIntegers -----------------\n");printf ("%16s%18s%16s\n","FirstPtr[int]","SecondPtr[int]","Temp[int]");printf (" -------------- -------------- ---------------\n");printf (" |%10p | |%10p | |%6d |\n",

FirstPtr,SecondPtr,Temp);printf (" -------------- -------------- ---------------\n");printf (" |->%4d | |->%4d |\n",*FirstPtr,*SecondPtr);printf(" -------------- --------------\n");printf ("%11p-%d%17p-%d%17p-%d\n\n",&FirstPtr,sizeof(FirstPtr),

Page 120: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [120]

&SecondPtr,sizeof(SecondPtr),&Temp,sizeof(Temp));}

Output from Switch2.c is as follows:

------------------ Beginning of main ---------------------

X[int] Y[int] -------------- -------------- | 5 | | 8 | -------------- -------------- 1349514-2 1349512-2

------------- Beginning of SwitchIntegers ---------------

FirstPtr[int] SecondPtr[int] Temp[int] -------------- -------------- --------------- | 1349514 | | 1349512 | | 0 | -------------- -------------- --------------- |-> 5 | |-> 8 | -------------- -------------- 1349504-4 1349508-4 1349494-2

---------------- End of SwitchIntegers -----------------

FirstPtr[int] SecondPtr[int] Temp[int] -------------- -------------- --------------- | 1349514 | | 1349512 | | 5 | -------------- -------------- --------------- |-> 8 | |-> 5 | -------------- -------------- 1349504-4 1349508-4 1349494-2

-------------------- End of main ------------------------

X[int] Y[int] -------------- -------------- | 8 | | 5 | -------------- -------------- 1349514-2 1349512-2

Variable Temp was initialized to 0 only for display purposes. The printf statements that provide the memory dumps could be better accomplished using one or more subprograms; this will be left to the student.

The dereferencing of pointers is the same for void-functions and explicit-functions. Memory maps will prove to be helpful in debugging until you are comfortable with the concept.

Not all of the parameters in the parameter list must be pointers. This next program illustrates a subprogram whose parameter list contain value parameters and pointers. Function main initializes Score1 and Score2 to 150 and 200. The purpose of Stats1 is to assign the sum of these two scores to integer variable Sum and the average of these scores to float variable Average.

In order to change the contents of both Average and Sum via a single subprogram, dereferencing of pointers must be used. Selective memory maps have been embedded within the code for program Stats.c to illustrate the scope of pointer variables.

Page 121: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [121]

PROGRAM Stats.c

# include <stdio.h>

void Stats1 (int N1, int N2 , int *S, float *A); main () {intScore1 = 150,Score2 = 200,Sum = -1;

floatAverage;

Page 122: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [122]

Page 123: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [123]

Stats1 (Score1, Score2 , &Sum, &Average); printf ("Bowling Scores : %i, %i,\n", Score1, Score2);printf ("Sum : %i,\n", Sum);printf ("Average : %6.2f,\n",Average);

Page 124: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [124]

Page 125: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [125]

}/*******************************************************************************/void Stats1 (int N1, int N2 , int *S, float *A) {

Page 126: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [126]

Page 127: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [127]

*S = N1 + N2;*A = *S / 2.0;

Page 128: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [128]

Page 129: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [129]

}

The output from program Stats.c is as follows:

Bowling Scores : 150, 200,Sum : 350,Average : 175.00,

Perhaps a more readable solution to void-function Stats1 would be

void Stats1 (int No1, int No2 , int *Sum, float *Average) {*Sum = N1 + N2;*Average = *Sum / 2.0;

}

It is important to note that the variable Sum (&1196270) of function main would not cause compiler confusion with pointer variable *Sum in function Stats1; examination of the memory maps reflect that these two variables are never in-scope at the same time.

Page 130: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [130]

Page 131: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [131]

Functional Abstraction

The purpose of using all types of functions is to simplify reasoning. During the design stage, as a problem is subdivided into tasks, the problem solver (you) should have to consider only what a function is to do and not be concerned about details of the function. The function name and comments at the beginning of the function should be sufficient to let other computer scientists know what the function does. Developing functions in this manner is referred to as functional abstraction.

Functional abstraction is the first step in designing and writing a function. The list of parameters and comments about the action of the function should precede writing the function body. This forces clarity of thought and aids design. Using this method might perhaps cause you to discover that your design is not sufficient to solve the task and that redesigning is necessary. Therefore, abstraction often helps to reduce design errors and save time when writing code.

Functional abstraction becomes especially important when teams work on a project. Each member of the writing team should be able to understand the purpose and use of functions written by other team members without having to analyze the body of each function. This is analogous to the situation in which you use a predefined function, such as sqrt, without really understanding how the function works.

In summary, functional abstraction means that, when writing or using functions, you should think of them as single, clearly understood units that each accomplishes a specific task.

We close this section with the final revision of the of the pizza cost program. The structure chart for this problem is given in Figure 4.1.

Page 132: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [132]

Figure 4.1 (a)Structure ChartPizza Problem

Page 133: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [133]

There are some software engineers that insist that the hierarchy structure chart should include specific parameters. This does provide a much better foundation for software systems that are to be constructed by teams of computer scientists; the modular interface and data flow are two of the more difficult tasks facing computer scientists whose individual subprograms must fit together to form a whole system. Figure 4.1(b) illustrates this much more visual flow of the data.

Figure 4.1 (b)

Page 134: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [134]

Page 135: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [135]

Once the logic flow is mapped out on the hierarchy chart, the problem is partitioned into well-defined subprograms. As our systems become more complex, individual blocks within the hierarchy chart will often represent single subprograms, or collections of subprograms; these diagrams will tend to become less specific. Figure 4.1(c) illustrates our subprogram grouping.

Figure 4.1 (c)

Page 136: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [136]

Page 137: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [137]

Subprogram specifications for the main subprograms are

1. Get Data SubprogramData received : NoneInformation returned : Price

DiameterLogic: Have the user enter price and diameter.

2. Perform Computation Subprogram Data received : Price DiameterInformation returned : PricePerInchLogic : Given the diameter, find the radius. Compute the area using Area = Pi * Radius * Radius. Price per square inch is found by dividing Price by Area.

3. Print Results SubprogramData received : PricePerInchInformation returned : NoneLogic : Print the price per square inch.

The complete program for this problem follows. Selective memory maps have been embedded within the code to illustrate that the symbolic name Diameter can be used as a floating point number in function main and as a pointer to that floating point number in function GetData.

PROGRAMPizaCost3.c

# include <stdio.h># define PI 3.14

void GetData (float * Price, float * Diameter);void PrintResults (float PricePerInch);void PerformComputations (float Price, float Diameter, float * PricePerInch);

main () {floatDiameter, Price, PricePerInch;

Page 138: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [138]

Page 139: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [139]

GetData (&Price, &Diameter); PerformComputations (Price,Diameter, &PricePerInch);

PrintResults (PricePerInch);

Page 140: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [140]

Page 141: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [141]

}

void GetData (float * Price, float * Diameter){

Page 142: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [142]

Page 143: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [143]

Page 144: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [144]

printf ("Enter the pizza cost and press <RETURN> : $");scanf ("%f",Price);printf ("Enter the pizza size (diameter inches) and press <RETURN> : ");scanf ("%f",Diameter);

}

void PerformComputations (float Price, float Diameter, float * PricePerInch){ floatRadius, Area;

Page 145: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [145]

Page 146: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [146]

Page 147: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [147]

Radius = Diameter / 2.0;Area = PI * Radius * Radius;*PricePerInch = Price / Area;

} void PrintResults (float PricePerInch){

Page 148: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [148]

Page 149: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [149]

printf("\n");printf ("The price per square inch is $%6.2f \n", PricePerInch);

}

Output from program Pizza3.c is as follows:

Enter the pizza cost and press <RETURN> : $10.50Enter the pizza size (diameter inches) and press <RETURN> : 16

The price per square inch is $ 0.05

Exercises 4.51. Indicate which of the following parameters are pointers.

a. void Demo1 (int X, int * Y, float * Z)

b. void Demo2 (char W, float * X, float Y, int * Z)

c. void Demo3 (char * W, int * X, float Y, int * Z)

2. Indicate which of the following are appropriate void-function headings. Explain the problem with those that are inappropriate.

a. void Prac1 (int *A , *Y );

b. void Error (char * Ch1; char * Ch2 )

c. void Prac2 (int *A, float *B, char C, long int *D)

d. void Prac3 ( int A,int *B,

float *S,float *T.char Ch)

3. Indicate how each of the following void-functions would be called from main

a. void Prob5 (int *A, int B , char *Ch)

b. void PrintTitle(void)

c. void DetermineMax (int N1, int N2, int *NewMax)

d. void Switch (float * X, float *Y)

4. Suppose a program contains the following void-function:

void Switch (int * A, int * B ){intTemp;

Temp = *A;*A = *B;*B = Temp;

Page 150: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [150]

}

Indicate the output from each of the following fragments of code in the main a. main ()

{ int

Num1 = 5,Num2 = 10;

printf ("Num1 = %d Num2 = %d \n", Num1, Num2);Switch (&Num1, &Num2);printf ("Num1 = %d Num2 = %d \n", Num1, Num2);Switch (&Num1, &Num2);

printf ("Num1 = %d Num2 = %d \n", Num1, Num2);}

b. main () { int

N = 3,M = 20;

printf ("N = %d M = %d \n", N, M);Switch (&N, &M);printf ("N = %d M = %d \n", N, M);Switch (&N, &M);

printf ("N = %d M = %d \n", N, M);}

5. Write a void-function for each of the following and indicate how it would be called from the main function.

a. Find the sum and average of three reals. Both values are to be returned to main.

b. Find the difference of two integers. The difference is to be returned to main..

6. Assume a main contains

intNum1, Num2;

float X, Y;

charCh1, Ch2;

Furthermore, suppose the same program contains the following prototype

void Demo (int * N1, int * N2, float X1, char Ch );

Indicate which of the following are appropriate calls to the void-function Demo. Explain those that are inappropriate.

a. Demo (Num1, Num2);b. Demo (&Num1, &Num2);

Page 151: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [151]

c. Demo (&Num1, &Num2, X);d. Demo (Num1, Num2, X, Ch1);e. Demo (&Num1, &Num2, &X, &Ch1);f. Demo (&Num1, &Num2, X, Ch1);g. Demo (&X, &Y, Num1, Ch2);h. Demo (&Num2, &X, Y, Ch1);i. Demo (Num1, Num2, Ch2);j. Demo;k. Demo (&Num2, &Num1, Y, Ch1);

7. Review the following program:

int J = 5; /* 750300 */

main () 1{ 2int 3

A = 1, /* 750400 */ 4B = 2; /* 750402 */ 5

float 6X = 3.3; /* 750404 */ 7

char 8Ch = 'A'; /* 750408 */ 9

/* ---------------- Memory Map 1 -------------------- */ 10Sub1 (&B); 11

/* ---------------- Memory Map 4 -------------------- */ 12Sub2 (&A, &B); 13

/* ---------------- Memory Map 7 -------------------- */ 14} 15

16void Sub1 (int * Z) /* 750500 */ 17{ 18int 19

B1 = 4; /* 750504 */ 20/* ---------------- Memory Map 2 -------------------- */ 21

*Z = B1 + *Z; 22/* ---------------- Memory Map 3 -------------------- */ 23} 24

25void Sub2 (int *X, int *Y) /* 750600, 750604 */ 26{ 27float 28

A = 3.14; /* 750608 */ 29char 30

Ch = 'D'; /* 750412 */ 31/* ---------------- Memory Map 5 -------------------- */ 32

*X = *X + *Y; 33printf ("%d %d\n",(*Y)++, J--); 34*Y = *Y + Ch + --J; 35

/* ---------------- Memory Map 6 -------------------- */ 36} 37

a. List all global variables.b. Write the prototypes for the program.

Page 152: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [152]

c. The numbers in comments beside each of the declarations represent the addresses assigned by the memory manager. Construct Memory Maps 1–7).

d. Write the statement numbers representing the execution flow from this program. Use the line numbers on the far right.

8. Review the following program:

main () 1{ 2int 3

A = 1, /* 970400 */ 4B = 2; /* 970402 */ 5

/* ---------------- Memory Map 1 -------------------- */ 6Sub5 (&B); 7

/* ---------------- Memory Map 4 -------------------- */ 8Sub3 (&A, &B); 9

/* ---------------- Memory Map 7 -------------------- */ 10} 11

12void Sub5 (int * Z) /* 970500 */ 13{ 14int 15

B1 = 4; /* 970504 */ 16/* ---------------- Memory Map 2 -------------------- */ 17

B1++; 18Sub3 (Z,&B1); 19

/* ---------------- Memory Map 3 -------------------- */ 20} 21

22void Sub3 (int *X, int *Y) /* 970600, 970604 */ 23{ 24int 25

Temp = 10; /* 970608 */ 26/* ---------------- Memory Map 5 -------------------- */ 27

*X = *X * Temp; 28*Y = *Y + Temp; 29

/* ---------------- Memory Map 6 -------------------- */ 30} 31

a. List all global variables.b. Write the prototypes for the program.c. The numbers in comments beside each of the declarations represent the

addresses assigned by the memory manager. Construct Memory Maps (1–7).

d. Write the statement numbers representing the execution flow from this program. Use the line numbers on the far right.

Page 153: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [153]

Page 154: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [154]

Page 155: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [155]

Subprogram Length and Design

The costs associated with computer software are escalating. In order to increase efficiency and reduce software costs, software engineers offer the following guidelines for subprograms:

(1) Write Subprograms which do one task and do it well. Many of the subprograms which do a task well can be incorporated into other programs; it is not cost-effective to re-create the wheel over and over. With practice, subprograms can often be generic enough to solve families of similar problems.

(2) A computer scientist. familiar with the language, should be able to read through and understand any single subprogram in 30 minutes or less. The total number of lines of code is not a good measure of how long to make subprograms. A subprogram to print a report may consist of one hundred and fifty printf statements; this subprogram would be easily understood by a beginning computer scientist in minutes. Another subprogram that contains forty lines of complicated equations might be too much for one subprogram. The idea is to break complicated tasks into smaller subtasks which can be easily understood and systematically completed.

(3) Although there are times when one line void-functions are appropriate, a multitude of very short subprograms are often discouraged in large interactive systems. Some graphics void-functions are examples of very appropriate short functions.

In order to clear the monitor screen, move the cursor about the screen, plot points on the screen, plot lines on the screen, create and manipulate windows about a screen, and/or generate graphics on a screen, issues related to both hardware and the operating system tool boxes must be addressed. A variety of terminals and microcomputers may serve as terminals for one central computer. The information sent to the monitor to clear the screen on the Macintosh will be different than the information sent to the monitor to clear the screen on an IBM super VGA monitor; the ANSI C standards committee did not establish function calls for the graphics. When using LightSpeed C on the Macintosh, the following function will clear the screen on the monitor:

void ClearScreen (void){printf ("\f");

}

When using Turbo C on the IBM, the following function will clear the screen on the monitor:

void ClearScreen (void){ clrscr();

}

When using Microsoft C on the IBM, the following function will clear the screen on the monitor:

void ClearScreen (void){

Page 156: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [156]

_clrscrscreen(_GCLEARSCREEN); }

ClearScreen is one of the generic subprograms listed in Appendix 7. The screen might be cleared hundreds of times in a large interactive program. Programmer John inserts the appropriate line(s) of code necessary to clear the screen on his type of computer monitor directly into the code where needed. When Programmer John transfers this program to a computer requiring a different sequence to clear the screen, he has to search for and change each and every one of the hundreds of calls to clear the screen.

Programmer Jane knows that monitor graphics are hardware driven and creates an appropriate ClearScreen function for his/her environment. This subprogram is called hundreds of times in the large interactive program. When Programmer Jane transfers this program to a computer requiring a different sequence to clear the screen, she makes one change to the ClearScreen subprogram. This is much more cost-effective and stress-free. Eventually Programmer Jane will combine the graphics subprograms (ClearScreen, MoveCursorTo, PlotPoint, DrawLine, etc.) into a graphics module; dual graphics modules will be created for the necessary hardware platforms. A high degree of portability is gained when the computer scientist transfers all but the graphics subprograms to the different computer. Despite the fact that the graphics must be dealt with systematically, C is still the most portable of all languages. We shall use the ClearScreen void-function throughout the remainder of this text without including the code and documentation in the program source listing. Students interested in generic graphics are encouraged to research "Curses".

Page 157: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [157]

Page 158: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [158]

Documenting Subprograms

Designing and documenting high quality subprograms helps to reduce the rising costs associated with software production. If good generic subprograms are to be placed in a library for other computer scientists to use on other projects, some documentation is essential for optimal usage. Although there is no one set of guidelines which meets the needs of all companies, certain comments are essential.

(1) Subprogram Name - this identifier provides a very brief description of what the subprogram does.

(2) Purpose - this brief description will tell what the subprogram was intended to do.

(3) Modules/Subprograms Required - since a computer scientist will need to gather any other modules and subprograms called by this subprogram from the library, this helps to provide a quick shopping list.

(4) Global Variables - the computer scientist needs to know the data type for any global variables required for this subprogram and what their expected values should be. He/she will have to declare and fill these global variables. He/she will have to make sure that the symbolic names for these global variables do not conflict with any other global variables already in the program.

(5) Headers Required - The computer scientist needs to make sure that my program has the necessary headers defined at the top of the program.

(6) Defines Required - The computer scientist needs to make sure that my program has the necessary constants defined at the top of the program.

(7) Limitations - many subprograms have limitations. Among the limitations for the GetData subprogram within the PizaCost2.c program would be "the user must enter valid numerical data - the user is not given an opportunity to re-enter the data if he/she accidentally enters an l (el) instead of a1 (one). The computer scientist may or may not be willing to accept these limitations within my program. If a subprogram does a substantial portion of the needed task, the computer scientist may choose to fetch and modify the existing subprogram as opposed to starting from scratch.

(8) Computer Scientist Name - the person who created this subprogram is probably the best person to provide me with (a) insights into it's inner working , (b) testing documentation, and (c) possible test data sets.

(9) Creation Date - the date might better help trace the subprogram history.(10) Compiler Name and Version - some C compilers offer non-ANSI functions; if

this subprogram uses any of these functions, the computer scientist may not be able to use the subprogram on a different compiler without extensive work.

(11) Computer - certain hardware related routines, such as the screen graphics, will not necessarily be compatible on my computer.

/***************************************************************************************************************************************************************** Void-function GetProblem **** **** Purpose : Interactively Prompt the User to Fill Addend1 **** and Addend2 **** Modules Required : None **** Globals Required : int Addend1, Addend2 **** Headers Required : stdio.h **** Defines Required : None **** Limitations : Interactive Integer Input is Not User-Friendly - No **

Page 159: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [159]

** precautions are taken to make sure that the user **** enters valid integer data. **** Written By : Carol Ann Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/

This subprogram documentation is generally inserted as a comment immediately preceding the code; past experience reveals that most paper documentation is seldomly updated and often not easily accessible. A number of companies prefer to document subprograms with double borders and use single border comments for internal comments. Programs can be written which will prompt the computer scientist for program source file name, the compiler, computer scientist name, computer and date; at that time the program will complete all portions of the documentation except the purpose and the limitations. This helps to automate the process. A less sophisticated approach would be to generate a blank template on a file, paste the template into the source code prior to the subprogram, and fill in the blanks in the template.

Some subprograms are so generic and universal that they may be plugged into new systems with very little or no effort. Some subprograms can be used, but must be modified to satisfy the current need. At some point it is more efficient to create a new subprogram than to modify an existing subprogram. The ten documentation items above provide the systems analyst (head computer scientist responsible for designing the system) and programmers with the ability to select appropriate library subprograms.

With the rising cost of software, it is essential that new applications work for some period of time. The software life-cycle spans from its conception to its extinction. During the life-cycle of most software, it is normal to add new features, new fields, new options, new reports, etc.; these tasks are performed more efficiently on well documented systems.

Documentation efforts have been increasing and improving across the nation. The number of companies that write code with little or no internal documentation is decreasing rapidly. Programmers and systems analysts tend to change positions every few years in order to gain upward mobility. Systems are often designed to last a decade or two; the programmers and systems analysts who created the system are often in other positions during the life cycle of such systems. Within many companies, the teams that create software systems are not the teams that maintain those systems. Software maintenance includes correcting errors, adding new options, adding new features, operating system upgrades, etc. Approximately seventy to eighty percent of all programming is modification; research has shown that well documented programs are much easier and cheaper to maintain.

Many educational programs find printing time and paper to be in great demand. Please consult your instructor to identify your documentation standards.

Page 160: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [160]

Page 161: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [161]

Program Documentation

The documentation block at the beginning of each program often consists of at least the following:

(1) Program Name (2) Purpose (3) Systems Analysts Name (Who Designed The System)(4) Programming Team(s) Names(5) Creation Date (6) Compiler Name and Version (7) Computer

/***************************************************************************************************************************************************************** Program AddProb.c **** **** Purpose : Interactively Prompt the User for Two Addends and **** Display the Corresponding Addition Problem on the **** Monitor. **** **** Systems Analyst : Carol Ann Date : xx/xx/xx **** **** Programmers : John Alan, Donna Sue, Bobby Joe, Billy D **** **** **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/

Exercises 4.6 1. Write and test void-function ClearScreen() for your system! (Mainframe/Mini

users may need to consult your instructor for a handout or manual on Curses)

2. Write and test void-function MoveCursorTo (int Row, int Col) for your system! (Mainframe/Mini users may need to consult your instructor for a handout or manual on Curses)

3. Why should graphics instructions be written as self-contained subprograms in the C programming language?

4. Write and test the following functions:

a. float AreaSquare (float Side)

b. float AreaRectangle (float Length, float Width)

c. float AreaTrapezoid (float Height, float HighBase, float LowBase)

d. float VolumeCone (float RadiusBase, float Height)

e. float VolumeCube (float Side)

f. float VolumeRectangularPrism (float Height, float Width, float Length)

5. Code and document program Pizza3.c

Page 162: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [162]

Page 163: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [163]

When should you use an explicit-function rather than a void-function in a program? A general rule is to think of a function as a construct that returns only one value; thus, an explicit-function would be used when a single value is to be explicitly returned. Explicit-functions are often used for error checking and verification.

Page 164: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [164]

Page 165: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [165]

When Should Pointers Be Passed?Example 4.7

Take a moment and examine explicit functions Sum1 and Sum2 below.

int Sum1 (int Addend1, int Addend2){intSum;

Sum = Addend1 + Addend2;return (Sum);

}

int Sum2 (int *Addend1, int *Addend2){return ((*Addend1) + (*Addend2));

}

main(){int No1 = 3, No2 = 4, Sum;

Sum = Sum1(No1, No2);Sum = Sum2(&No1, &No2);

}

Both Sum1 and Sum2 provide functions which explicitly return the value 7 to the memory referenced by symbolic name Sum. In subprogram Sum2 a copy is made of the two arguments (Addend1 contains a copy of No1 and Addend2 contains a copy of No2); it is not possible to accidentally destroy the contents of either No1 or No2. In subprogram Sum2, the contents of No1 and No2 could be destroyed by accident.

For example, suppose the print statement

printf ("The Sum Of The Two Addends = %d\n", Addend1++, Addend2);

were placed into Sum1 (immediately before the return statement); the print statement erroneously changes the copy of Addend1, but does not change the original. The returned Sum is still correct.

Suppose the print statement

printf ("The Sum Of The Two Addends = %d\n", (*Addend1)++,(*Addend2));

were placed into Sum1 (immediately before the return statement); the print statement erroneously changes the original No1 (in main).

An excellent guideline for young computer scientists is to use a pointer with a function only when the function needs to be able to alter the contents of the memory associated with the pointer; otherwise use value parameters. Although this suggestion may not generate the fastest code, it makes programs easier to debug when subprograms are unable to accidentally alter the variables which should not be altered.

A NOTE OF INTEREST

Page 166: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [166]

Page 167: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [167]

Niklaus Wirth received his doctorate from the University of California, Berkeley, in 1963. He began his work in the computing field by taking a course in numerical analysis at Laval University in Quebec, Canada. However, the computer (Alvac III E) was frequently out of order and the hexadecimal code programming exercises went untested.

After other early experiences in programming, it became apparent to Wirth that computers of the future had to be more effectively programmable. Consequently, he joined a research group that worked on developing a compiler for an IBM 704. This language was NELIAC, a dialect of ALGOL 58. In rapid succession, he developed or contributed to the development of Euler, ALGOL W, and PL360. In 1967, he returned to Switzerland and established a team of three assistants with whom he developed and implemented the language Pascal.

One of the main purposes of Pascal was its use as a language for teaching. This was particularly successful because it allowed the teacher to focus on structures and concepts rather than features and peculiarities.

A decade later, Wirth's attention turned to hardware design. In order to continue his work and incorporate advances in technology, he developed yet another language, Modula-2. This was an offspring of Pascal and Modula. It was developed for use with the Lilith, a computer designed with all systems written in a single language.

Modula-2 compilers have been in use since 1979. Recent versions are so efficient that their code is approximately five thousand lines long compared to Ada compilers of several hundred thousand lines.

Page 168: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [168]

Page 169: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [169]

Using Stubs & Drivers

The young computer scientist often struggles to get programs involving several subprograms to work. Approximately thirty percent of the project time should be spent on the design (hierarchy charts and pseudocode). Getting the flow of information into and out of the subprograms to match the design is critical. The stub and driver approach is helpful both to young and experienced computer scientists.

As programs get longer and incorporate more subprograms, a technique frequently used to get the program running is stub programming. A stub program is a no-frills, simple version of what will be a final program. It does not contain details of output and full algorithm development. It does contain a rough version of each subprogram and all parameter lists. When the stub version runs, you know that some of your logic is correct and that values are appropriately being passed to and from subprograms. Then you can fill in necessary details to get a complete program.

Function main is sometimes used as the driver to call other subprograms. The driver function to test other functions is sometimes called a harness. When subprograms are used in a simple program, this driver can be modified to check subprograms in a sequential fashion.

Let us return to PizaCost3.c to see how stubs and drivers might have been used to test the passing of information to and from functions and void-functions. Examine the following code:

# include <stdio.h># define PI 3.14

void GetData (float * Price, float * Diameter);void PrintResults (float PricePerInch);void PerformComputations (float Price, float Diameter, float * PricePerInch);

main () {floatDiameter=1, Price=1, PricePerInch=1;

printf ("1- D= %f P= %f PSI = %f\n", /* XX */Diameter,Price,PricePerInch);

GetData (&Price, &Diameter);

printf ("2- D= %f P= %f PSI = %f\n", /* XX */

Diameter,Price,PricePerInch);

PerformComputations (Price,Diameter, &PricePerInch);

printf ("3- D= %f P= %f PSI = %f\n", /* XX */Diameter,Price,PricePerInch);

PrintResults (PricePerInch);

printf ("4- D= %f P= %f PSI = %f\n", /* XX */

Diameter,Price,PricePerInch); }

Page 170: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [170]

void GetData (float * Price, float * Diameter){ printf ("\n---> GetData -> *Price = %f *Diameter = %f\n\n", /* XX */

*Price, *Diameter);*Price = 2; /* XX */*Diameter = 2; /* XX */}

void PerformComputations (float Price, float Diameter, float * PricePerInch){ printf ("\n---> PerformComputations -> Price= %f Diameter= %f\n", /* XX */ Price,Diameter); printf ( "---> *PicePerInch= %f\n\n",* PricePerInch); /* XX */*PricePerInch = 2; /* XX */} void PrintResults (float PricePerInch){ printf ("\n---> Print Results -> PicePerSquareInch= %f\n\n", /* XX */ PricePerInch);}

The output from the code fragment above is as follows:

1- D= 1.000000 P= 1.000000 PSI = 1.000000

---> GetData -> *Price = 1.000000 *Diameter = 1.000000

2- D= 2.000000 P= 2.000000 PSI = 1.000000

---> PerformComputations -> Price= 2.000000 Diameter= 2.000000---> *PicePerInch= 1.000000

3- D= 2.000000 P= 2.000000 PSI = 2.000000

---> Print Results -> PicePerInch= 2.000000

4- D= 2.000000 P= 2.000000 PSI = 2.000000

Function main is the driver function; it's purpose at the moment is to call all other subprograms (one at a time). Functions GetData, PerformComputations, and PrintResults are stubs. Some of the lines in the harness/stub implementation are throw-away lines; they will be deleted as the program is completed. These throw-away lines are generally not indented or well formatted; the lack of indention makes them easy to identify and remove. The throw-away lines in this program are marked with /* XX */.

Diameter, Price, and PricePerInch are initialized for testing purposes. The first printf (in main) verifies that each of these variables is initialized to 1.

It is the responsibility of the subprogram stub to (1) display the subprogram name, (2) display the values of all value parameters, (3) display the values pointed to by pointers, and (4) alters pointer and return values. Reason will have to prevail on these displays when arrays and structures are introduced later in this text.

Stub GetData is passed two pointers. The values pointed to are printed. The values pointed to are changed. The second printf (in main) verifies that the Price

Page 171: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [171]

and the Diameter each contain the value 2. The pointers were successfully dereferenced.

Stub PerformComputations is passed two value arguments and one pointer. The copy of the Price and Diameter are printed to verify that they were correctly passed. The value pointed to is printed. The value pointed to are changed. The third printf (in main) verifies that the PricePerInch contains the value 2. The pointer was successfully dereferenced.

Stub PrintResults is passed one value argument. The copy of the PricePerInch is printed to verify that it was correctly passed. The fourth printf (in main) verifies that PrintResults had no impact upon the variables in main.

Notice that the printfs and assignments have been placed on the left margin (not indented). Once you are sure a subprogram is running, you can remove the extra printfs (easy to spot because it was not indented) and assignment statements. Once the interface between the void-functions has been verified, the computer scientist begins to systematically replace the stub code with correct code; this is often most quickly accomplished by completing and testing one subprogram at a time.

Exercises 4.7 1. Skip ahead to the program EXPark.c. (next section). After examining the

structure chart (figure 4.2), construct a stub and driver shell that would test the interface for this problem.

a. This program should display all value parameters and alter all pointers (dereferencing) within the appropriate subprograms.

b. Initialize EntryTime, ExitTime, and AmountDue as they are declared. c. Be sure to print the EntryTime, ExitTime, and AmountDue each and every

time execution returns to the main function. ––––––––––––––––––––––FOCUS ONPROGRAMMING––––––––––––––––––––––

In order to encourage people to shop downtown, the Downtown Businesses Association partially subsidizes parking. They have established the E-Z Parking lot where customers are charged $0.75 for each full hour of parking. There is no charge for part of an hour. Thus, if someone has used the lot for less than an hour, there would be no charge.

The E-Z Parking lot is open from 9:00 A.M. until 11:00 P.M. When a vehicle enters, the driver is given a ticket with the entry time printed in military style. Thus, if a car entered the lot at 9:30 A. M., the ticket would read 0930. If a vehicle entered at 1:20 P.M., the ticket would read 1320. When the vehicle leaves, the driver presents the ticket to the attendant and the amount due is computed.

Let's now develop a solution and write a program to assist the attendant. Input consists of a starting and ending time. Output should be a statement to the customer indicating the input information, the total amount due, a heading, and a closing message. Sample output for the data 930 (9:30 A.M.) and 1320 (1:20 P.M.) is

Please enter the time in and press <RETURN> : 930Please enter the time out and press <RETURN> : 1320

E - Z Parking -------------

Time in : 930 Time out: 1320

Page 172: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [172]

Amount due $ 2.25

Thank you for using E - Z Parking

BUCKLE UP and DRIVE SAFELY

A first-level development for this problem is

1. Get the data2. Compute amount3. Print results

Page 173: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [173]

Page 174: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [174]

Page 175: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [175]

Note the explicit return of Amount is indicated with the symbol (

Page 176: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [176]

Page 177: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [177]

).Once the logic flow is mapped out on the hierarchy chart, the problem is

partitioned into well-defined subprograms. Figure 4.2(b) illustrates our subprogram grouping.

Page 178: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [178]

Page 179: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [179]

Subprogram specifications for the three main subprograms are

1. GetData Subprogram Data received: None

Information returned: Entry time Exit timeLogic: Have the user enter information from the keyboard.

2. ComputeAmount SubprogramData received: Entry time Exit timeInformation returned: Amount dueLogic: Subtract the entry time from the exit time and use integer / 100 to get the number of full hours.

3. PrintResults SubprogramData received: Entry time Exit time Amount dueInformation returned: NoneLogic: Print the heading, entry time, exit time, amount due, and closing message.

By examining the subprogram specifications, we see that pointers are needed for GetData. ComputeAmount needs two value parameters and one variable parameter, and PrintResults needs three parameters.

A second-level pseudocode development is

1. Get the data 1.1 scanf time entered 1.2 scanf time exited

2. Compute amount 2.1 compute number of hours 2.2 compute amount due

3. Print results 3.1 print a heading 3.2 print amount due 3.3 print a closing message

One programming solution is as follows:PROGRAMEZPark.c

/***************************************************************************************************************************************************************** Purpose: This program prints statements for customers of the E-Z **** Parking lot. Interactive input consists of entry **** time and exit time from the lot. Output consists of a **** customer statement. Emphasis is placed on using **** void-functions to develop the program. **** Modules Required: ClearScreen, GetData, ComputeAmount, PrintHeading **** PrintMessage, PrintResults **** Systems **** Analyst : William Donald Date : xx/xx/xx **

Page 180: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [180]

** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/

# include <stdio.h> # define HOURLY_RATE .75

/******************************************************************************** Prototypes ********************************************************************************/void GetData (int * EntryTimePtr, int * ExitTimePtr);float ComputeAmount (int EntryTime, int ExitTime);void PrintHeading(void);void PrintMessage(void);void PrintResults (int EntryTime, int ExitTime, float AmountDue);

void ClearScreen (void); /* Code listed in Appendix 7 */

/******************************************************************************** main ********************************************************************************/main () { intEntryTime, ExitTime;

floatAmountDue;

GetData (&EntryTime, &ExitTime);AmountDue = ComputeAmount(EntryTime, ExitTime);PrintResults (EntryTime, ExitTime, AmountDue);

}

/***************************************************************************************************************************************************************** GetData **** **** Purpose: Interactively Prompt the User to Fill EntryTime & ExitTime **** Modules Required : ClearScreen **** Globals Required : None **** Headers Required : stdio.h **** Defines Required : None **** Limitations : Interactive Integer Input is Not User-Friendly - No ** ** precautions are taken to make sure that the user **** enters valid integer data. **** Systems **** Analyst : William Donald Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/void GetData (int * EntryTimePtr, int * ExitTimePtr){ClearScreen();printf ("Please enter the time in and press <RETURN> : ");scanf ("%d",EntryTimePtr);

Page 181: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [181]

printf ("Please enter the time out and press <RETURN> : ");scanf ("%d",ExitTimePtr);

}

/***************************************************************************************************************************************************************** ComputeAmount **** **** Purpose: Explicitly return full hours (NoOfHours* HOURLY_RATE) **** Modules Required : None **** Globals Required : None **** Headers Required : None **** Defines Required : HOURLY_RATE **** Limitations : EntryTime before midnight and ExitTime after Midnight ** ** are not properly calculated (Lot closes at 11 pm) **** Systems **** Analyst : William Donald Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/float ComputeAmount (int EntryTime, int ExitTime){intNumberOfHours;

NumberOfHours = (ExitTime - EntryTime) / 100;return ((float) NumberOfHours * HOURLY_RATE);

}

/***************************************************************************************************************************************************************** PrintHeading **** **** Purpose: Print a suitable heading for the ticket **** Modules Required : None **** Globals Required : None **** Headers Required : stdio.h **** Defines Required : None **** Limitations : None ** ** Systems **** Analyst : William Donald Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/void PrintHeading(void){ printf ("\n\n%36s\n", "E - Z Parking"); printf ("%36s\n\n", "-------------");}

/***************************************************************************************************************************************************************** PrintMessage **** **** Purpose: Print a closing message for the ticket **** Modules Required : None **

Page 182: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [182]

** Globals Required : None **** Headers Required : stdio.h **** Defines Required : None **** Limitations : None ** ** Systems **** Analyst : William Donald Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/void PrintMessage(void){printf ("%45s\n\n\n", "Thank you for using E - Z Parking");printf ("%33s\n", " BUCKLE UP");printf ("%30s\n", " and");printf ("%34s\n", " DRIVE SAFELY");

} /***************************************************************************************************************************************************************** PrintResults **** **** Purpose: Print a closing message for the ticket **** Modules Required : PrintHeading, PrintMessage **** Globals Required : None **** Headers Required : stdio.h **** Defines Required : None **** Limitations : None ** ** Systems **** Analyst : William Donald Date : xx/xx/xx **** Compiler : LightSpeed C Computer : MacII *****************************************************************************************************************************************************************/void PrintResults (int EntryTime, int ExitTime, float AmountDue){PrintHeading();printf ("%30s %d\n", "Time in :", EntryTime);printf ("%30s %d\n\n", "Time out:", ExitTime);printf ("%29s $ %5.2f\n\n", "Amount due ", AmountDue);PrintMessage();

}

Output from program EZPark.c is as follows:

Please enter the time in and press <RETURN> : 930Please enter the time out and press <RETURN> : 1320

E - Z Parking -------------

Time in : 930 Time out: 1320

Amount due $ 2.25

Thank you for using E - Z Parking

Page 183: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [183]

BUCKLE UP and DRIVE SAFELY

In order to reduce printing costs, the PrintResults subprogram and any other subprograms throughout the remainder of this text will be documented as follows:

/********************************************************************************* ** Purpose : Print a customer receipt; calls both PrintHeading **** and PrintMessage **** Modules Required : PrintHeading, PrintMessage **** Headers Required : stdio.h **** Globals Required : stdio.h **** Defines Required : None ***********************************************************************************/

––––––––––––––––––––RUNNING AND DEBUGGING TIPS––––––––––––––––––––

1. Each subprogram can be tested separately to see if it is producing the desired result. This is accomplished by a main function, or driver function, that calls and tests only the subprogram in question.

2. You can use identical variable names in the parameter lists. For example,

void Compute (int Number1, int Number2 , float * Average );

could be called by

Compute (Number1, Number2, &Average);

3. You can use related but not identical variable names in the parameter lists. For example,

void Compute (int N1, int N2 , float * Average );

could be called by

Compute (Number1, Number2, &Average);

4. Be sure the type and order of parameters and arguments agree. You can do this by listing them one below the other. For example,

void GetData (char * Init1,char * Init2, int *Score); GetData (&Initial1, &Initial2, &Score);

5. Carefully distinguish between passing arguments by value and passing pointers to variables. If a variable in one function is to be changed, the address of that variable must be passed to a called function which matches it with pointer of corresponding data type.

SUMMARYKey Terms / Words

Page 184: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [184]

argument (actual parameter)blockbottom-up testingcall a functiondereference a pointerdriverevoke a functionexplicit-functionglobal variablein-scopelocal variablememory allocatedmemory de-allocated

memory mapmain functionmodulemodule documentationmodularityout-of-scopeparameter (formal parameter)parameter listpassed by referenceprogram documentationfunctional abstractionvoid-functionspreprocessingprototype

returnscope of an identifiersoftware maintenancesubprogramstructured programmingsystemsystems analyststub programminguser-defined functionvalue parametervoid-functionvoidwhite space

Key Concepts

Page 185: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [185]

Page 186: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [186]

The form for a user-defined void-function is

void FunctionName (ParameterList){[Local Variables Declared]. . [work of void-function here].}

Page 187: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [187]

Page 188: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [188]

The form for a user-defined explicit-function is

ReturnType FunctionName (ParameterList){[Local Variables Declared]. . [work of function here].return (xx); /* Parentheses around return value are optional */}

Page 189: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [189]

Page 190: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [190]

It is generally better to pass those parameters that are not to be ch

Sum is to be explicitly returned in the following function:

int CalculateSum (int Addend1, int Addend2)

Page 191: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [191]

Page 192: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [192]

Neither Addend1 nor Addend2 are changed in explicit-function CalculateSum (above); it is generally better not to pass these variables as pointers. Note the explicit return of Sum is indicated with the slanted arrow.

Now as a void-function:

void CalculateSum (int Addend1, int Addend2, int * Sum)

Page 193: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [193]

Page 194: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [194]

Neither Addend1 nor Addend2 are changed in void-function Sum; it is generally better not to pass these variables as pointers. Since Sum are to be changed within CalculateSum, Sum must be passed as a pointer.

Page 195: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [195]

Page 196: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [196]

The formal parameter list in the subprogram heading should match the number and types of actua

void Arithmetic (char OperatorSymbol, int No1, int No2 ) Arithmetic (Symbol, Num1, Num2);

Page 197: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [197]

Page 198: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [198]

One of the guidelines of

Page 199: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [199]

Page 200: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [200]

Global variable s c

Page 201: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [201]

Page 202: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [202]

Local variabl

Page 203: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [203]

Page 204: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [204]

One of the advantages of well written subprograms is that t

Page 205: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [205]

Page 206: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [206]

Blank lines help readability of the program code; they are ignored by the compiler. They neither increase the size of the bina

Page 207: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [207]

Page 208: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [208]

Comment lines are invaluable in program maintenance; they are ignored by the compiler. They neither increase the size of the binar

Page 209: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [209]

Page 210: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [210]

Let us once more emphasize the difference using scanf with a

main(){intNumberUnits;

floatUnitCost,TotalCost;

TotalCost = GetData (&UnitCost, &NumberUnits);}

float GetData (float *CostPerUnit, int *NoUnits){floatLocalTaxRate;

printf ("Enter Loocal Tax Rate (.xxx%) :");scanf ("%f",&LocalTaxRate);printf ("Enter NoUnits :");scanf ("%d",NoUnits);printf ("Enter Cost Per Unit :$");scanf ("%d",CostPerUnit);return ( (1+LocalTaxRate) * (*NoUnits) * (*CostPerUnit) );

}

Since NoUnits and CostPerUnit are already addresses (pointers), there is no ampersand (&) in the last two scanf function calls of the GetData void-function. NoUnits is a pointer (pointing to NumberUnits within main) and CostPerUnit is a pointer (pointing to UnitCost within main). In the first scanf function call, the ampersand is used to place the Local Tax Rate into the address associated with LocalTaxRate.

––––––––––––––––––––PROGRAMMING PROBLEMS––––––––––––––––––––

For each of the programs below(A) construct the hierarchy structure chart(B) write the pseudocode for all subprograms(C) create a working copy [Attractively include the computer scientist name(s)

on the output screen for each program](D) test the program(E) document the program and each subprogram in accordance with your

instructor's requirements.

The following programming problems will be run on a very limited set of data. In later chapters, as you build your programming skills, you will run these problems with larger data bases and subprograms for various parts. Since these problems will be referred to and used repeatedly, carefully choose the ones on which to work and then develop them completely.

1. Write a program to get the coefficients of a quadratic equation

ax+ bx + c = 0

from the keyboard and then print the value of the discriminant

Page 211: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [211]

b– 4ac

2. Write a program to compute the cost for carpeting a room. Input should consist of the room length, room width, and carpet price per square foot. Use constants for the pad charge and installation charge. Include a heading as part of the output.

3. Williamson's Paint and Papering store wants a computer program to help them determine how much paint is needed to paint a room. Assuming a room is to have four walls and the ceiling painted, input for the program should be the length, width, and height of the room. Use a constant for the wall height (usually eight feet). One gallon of paint should cover 250 square feet. Cost of paint for the walls and ceiling should be entered by the user. Output should be the amount and cost for each kind of paint, and the total cost.

4. The Fairfield College faculty recently signed a three-year contract that included salary increments of 7 percent, 6 percent, and 5 percent respectively for the next three years. Write a program that allows a user to enter the current salary and then prints out the compounded salary for each of the next three years.

5. Several instructors use various weights (percentage of the final grade) for test scores. Write a program that allows the user to enter three test scores and the weight for each score. Output should consist of the input data, the weighted score for each test, and the total score (sum of the weighted scores).

6. The Roll-Em Lanes bowling team would like to have a computer program to print the team results for one series of games. The team consists of four members whose names are Weber, Fazio, Martin, and Patterson. Each person on the team bowls three games during the series: thus, the input will contain three lines, each with four integer scores. Your output should include all input data, individual series totals, game average for each member, team series, and team average.Sample output is

NAME GAME 1 GAME 2 GAME 3 TOTAL AVERAGE

Weber 212 220 190Fazio 195 235 210Martin 178 190 206Patterson 195 215 210

Team Total:

Team Average:

7. The Natural Pine Furniture Company has recently hired you to help them convert their antiquated payroll system to a computer-based model. They know you are still learning, so all they want right now is a program that will print a one-week pay report for three employees. You should use the constant definition section for the following:

a. Federal withholding tax rate 18%b. State withholding tax rate 4.5%c. Hospitalization $25.65d. Union dues $7.85

Page 212: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [212]

Each line of input will contain the employee's initials, the number of hours worked, and the employee's hourly rate. Your output should include a report for each employee and a summary report for the company files.A sample employee form follows:

Employee: JIMHours Worked: 40.00Hourly Rate: 9.75

Total Wages:

Deductions: Federal Withholding State Withholding Hospitalization Union Dues Total Deductions

Net Pay

Output for a summary report could be

Natural Pine Furniture Company Weekly Summary

Gross Wages:

Deductions: Federal Withholding State Withholding Hospitalization Union Dues Total Deductions

Net Wages

8. The Child-Growth Encyclopedia Company wants a computer program that will print a monthly sales chart. Products produced by the company, prices, and sales commissions for each are

a. Basic encyclopedia $325.00 22%b. Child educational supplement $127.50 15%c. Annual update book $18.95 20%

Write a program that will get the monthly sales data for two sales regions and produce the desired company chart. Each line of data will contain a two-letter code for the region followed by three integers representing number of products a, b, and c sold, respectively. The prices may vary from month to month and should be defined in the constant definition section. The commissions are not subject to change.

Sample input is

MI 150 120 105TX 225 200 150

Page 213: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [213]

Typical output could be

REGION SALES (Encyclopedia) (Supplement) (Update)

MI 150 120 105TX 225 200 150

Total Sales:

Total Commission:

9. The Village Variety Store is having its annual Christmas sale. They would like you to write a program to produce a daily report for the store. Each item sold is identified by a code consisting of one letter followed by one digit. Your report should include data for three items. Each of the three lines of data will include item code, number of items sold, original item price, and reduction percentage. Your report should include a chart with the input data, sale price per item, and total amount of sales per item. You should also print a daily summary.Sample input is

A1 13 5.95 15A2 24 7.95 20A3 80 3.95 50

Typical output form could be

Item Code # Sold Original Price Reductions Sale Price Income--------- ------ -------------- ---------- ---------- ------ A1 13 $5.95 15% $5.06 $65.78

Daily Summary------------- Gross Income:

10. The Holiday-Out Motel Company, Inc., wants a program that will print a statement for each overnight customer. Each line of input will contain room number (integer), number of nights (integer), room rate (real), telephone charges (real), and restaurant charges (real). You should use the constant definition section for the date and current tax rate. Each customer statement should include all input data, the date, tax rate and amount, total due, appropriate heading, and appropriate closing message. Test your program by running it for two customers. The tax rate applies only to the room cost.Typical input is

135 3 39.95 3.75 57.50

A customer statement form is

Holiday-Out Motel Company, Inc.----------- ----- -------- ----

Date: XX-XX-XXRoom # 135Room Rate: $39.95Number of Nights: 3

Page 214: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [214]

Room Cost: $119.85Tax: XXX% 4.79 Subtotal: $124.64

Telephone: 3.75Meals: 57.50

TOTAL DUE $185.89

Thank you for staying at Holiday-Out Drive safely Please come again

11. As a part-time job this semester, you are working for the Family Budget Assistance Center. Your boss has asked you to write and execute a program that will analyze data for a family. Input for each family will consist of

Family ID number (int)Number in family (int)Income (float)Total debts (float)

Your program should output the following:

a. An appropriate header.b. The family's identification number, number in family, income, and total

debts.c. Predicted family living expenses ($3000 times the size of the family).d. The monthly payment necessary to pay off the debt in one year.e. The amount the family should save (the family size times 2 percent of the

income minus debt--Farm Size * 0.02 (income - debt)).f. Your service fee (.5 percent of the income).

Run your program for the following two families:-----------------------------------------------------------------Identification Number Size Income Debt----------------------------------------------------------------- 51 4 18000.00 2000.00 72 7 26000.00 4800.00-----------------------------------------------------------------

Output for the first family could be:

Family Budget Assistance Center March 1989 Telephone: (800)555-1234

Identification number 51Family size 4Annual income $ 18000.00Total debt $ 2000.00Expected living expenses $ 12000.00Monthly payment $ 166.67Savings $ 1280.00Service fee $ 90.00

Page 215: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [215]

12. The Caswell Catering and Convention Service has asked you to write a computer program to produce customers' bills. The program should scanf in the following data.

a. The number of adults to be served.b. The number of children to be served.c. The cost per adult meal.d. The cost per child's meal (60 percent of the cost of the adult's meal).e. The cost for dessert (same for adults and children).f. The room fee (no room fee if catered at the person's home).g. A percentage for tip and tax (not applied to the room fee).h. Any deposit should be deducted from the bill.

Write a program and test it using data sets 2, 3, and 4.

Data Child Adult Adult Dessert Room Tip/ Set Count Count Cost Cost Rate Tax Deposit

1 7 23 12.75 1.00 45.00 18% 50.002 3 54 13.50 1.25 65.00 19% 40.003 15 24 12.00 0.00 45.00 18% 75.004 2 71 11.15 1.50 0.00 6% 0.00

Note that data set 1 was used to produce the following sample output:

Caswell Catering and Convention Service Final Bill

Number of adults: 23 Number of children: 7Cost per adult without dessert: $ 12.75Cost per child without dessert: $ 7.65 Cost per dessert: $ 1.00 Room fee: $ 45.00 Tip and tax rate: 0.18

Total cost for adult meals: $ 293.25 Total cost for child meals: $ 53.55 Total cost for dessert: $ 30.00 Total food cost: $ 376.80 Plus tip and tax: $ 67.82 Plus room fee: $ 45.00 Less deposit: $ 50.00

Balance due: $ 439.62

13. The Maripot Carpet Store has asked you to write a computer program to calculate the amount a customer should be charged. The president of the company has given you the following information to help in writing the program.

a. The carpet charge is equal to the number of square yards purchased times the labor cost per square yard.

b. The labor cost is equal to the number of square yards purchased times the cost per square yard. A fixed fee for floor preparation is added to some customers' bills.

Page 216: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [216]

c. Large volume customers are given a percentage discount but the discount applies only to the carpet charge, not the labor costs.

d. All customers are charged 4 percent sales tax on the carpet: there is no sales tax on the labor cost.

Write the program and test it for customers 2, 3, and 4.

Sq. Cost per Labor per Prep.Customer yds. sq. Yd. sq. Yd. Cost Discount

1 17 18.50 3.50 38.50 0.022 40 24.95 2.95 0.00 0.143 23 16.80 3.25 57.95 0.004 26 21.25 0.00 80.00 0.00

Note that the data for customer 1 were used to produce the following sample output:

Square yards purchased: 17 Cost per square yard: $ 18.50 Labor per square yard: $ 3.50Floor preparation cost: $ 38.50 Cost for carpet: $ 314.50 Cost for labor: $ 98.00 Discount on carpet: $ 6.29 Tax on carpet: $ 12.33 Charge to customer: $ 418.54

14. The manager of the Croswell Carpet Store has asked you to write a program to print customers' bill. The manager has given you the following information.

a. The store expresses the length and width of a room in terms of feet and tenths of a foot. For example, the length might be reported as 16.7 feet.

b. The amount of carpet purchased is expressed as square yards. It is found by dividing the area of the room (in square feet) by nine.

c. The store does not sell a fraction of a square yard. Thus, square yards must always be rounded up.

d. The carpet charge is equal to the number of square yards purchased times the carpet cost per square yard. Sales tax equal to 4 percent of the carpet cost must be added to the bill.

e. All customers are sold a carpet pad at $2.25 per square yard. Sales tax equal to 4 percent of the pad cost must be added to the bill.

f. The labor cost is equal to the number of square yards purchased times $2.40, which is the labor cost per square yard. No tax is charged on labor.

g. Large volume customers may be given a discount. The discount may apply only to the carpet cost (before sales tax is added), only to the pad cost (before sales tax is added), only to the labor cost, or to any combination of the three charges.

h. Each customer is identified by a five-digit number and that number should appear on the bill. The sample output follows:

Croswell Carpet Store Invoice

Page 217: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [217]

Customer number: 26817

Carpet : 574.20 Pad : 81.00 Labor : 86.40

Subtotal : 741.60 Less discount : 65.52

Subtotal : 676.08 Plus tax : 23.59 Total : 699.67

Write the program and test it for the following three customers.i. Mr. Wilson (customer 81429) ordered carpet for his family room, which

measures 25 feet long and 18 feet wide. The carpet sells for $12.95 per square yard and the manager agreed to give him a discount of 8 percent on the carpet and 6 percent on the labor.

ii. Mr. And Mrs. Adams (customer 04246) ordered carpet for their bedroom, which measures 16.5 feet by 15.4 feet. The carpet sells for $18.90 per square yard and the manager granted a discount of 12 percent of everything.

iii. Ms. Logan (customer 39050) ordered carpet that cost $8.95 per square yard for her daughter's bedroom. The room measures 13.1 by 12.5 feet. No discounts were given.

15. Each week Abduhl's Flying Carpets pays its salespeople a base salary plus a bonus for each carpet they sell. In addition, they pay a commission of 10 percent of the total sales by each salesperson.

Write a program to compute a salesperson's salary for the month by inputting Base, Bonus, Quantity, and Sales, and making the necessary calculations. Use the following test data:-----------------------------------------------------------------Salesperson Base Bonus Quantity Commission Sales----------------------------------------------------------------- 1 250.00 15.00 20 10% 1543.69 2 280.00 19.50 36 10% 2375.90-----------------------------------------------------------------

The commission figure is 10 percent. Be sure you can change this easily if necessary. Sample output follows:

Salesperson : 1 Base : 250.00 Bonus : 15.00 Quantity : 20 Total Bonus : 300.00 Commission : 10% Sales : 1543.69Total Commission : 154.37 Pay : 704.37

Page 218: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written

West Publishing - Chapter 4 - Introduction to Computer Science With C - Hicks, Nance, & Naps [218]

16. "Think Metric'' is the preferred way of having members of a nonmetric society become familiar with the metric system. Unfortunately, during the transition, many people are forced to rely on converting from their present system to the metric system. Develop a solution and write a program to help people convert their height and weight from inches and pounds to centimeters and kilograms. The program should get input of a person's height (in feet and inches) and weight (rounded to the nearest pound) from a keyboard. Output should consist of the height and weight in metric units.

Page 219: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap04-User... · Web viewFrom 1950 to the early 1970s programs were designed and written on a linear basis. A program written