04-1 modularity & functions

advertisement

1 of 13

04-1 MODULARITY & FUNCTIONS

Page 9 can be used as a handout

WHAT IS A FUNCTION

It is a block of code that has a name and has a property or an ability to be reusable from anywhere in the C program

Up to this point you have been using FUNCTIONS. main() printf() scanf() getchar()

FUNCTIONS TO MODULARIZE A PROGRAM

We will use functions in order to modularize the program into logical groups.

Instead of a very long program that is all inside of main, the main() function or module will call other modules or functions.

EXAMPLES:

START of main initial function -- this will handle any initial processing needed begin loop -- the loop to do the repetitive procrssing processing or getting input function calculation function format output function prepare for summary function ask for more looping function ?? end of loop summary function

END OF MAIN

DEFINITION:

A function is a module that performs its task by accepting a set of input values, doing the necessary calculations and processing and returning no value (zero value) or a single value

KEY:

Functions in ALL languages return only a single value. That value may or may not be used.

EXAMPLE:

In EXCEL or other spreadsheets there are functions like SUM. The format is

@sum(beginning address of cells, ending address of cells). The result is a single value.

EX: @sum(b1:b23) will sum cells b1, b2, b3 … to b23 and place 1 answer in the cell

726944548 by rt 15 April 2020 1 of 13

2 of 13

WHY USE FUNCTIONS

1 To hide details

The actual code contained in printf is not usually important to see. All we want to see is the name of the function so that we know what is being executed and the part that will be displayed on the screen.

How the printf function does the job that it does, is not important to us. This means that functions hide the details. If you want to see the detail then in the case of printf you need to look it up in a manual.

For your own defined functions you would look for it later in the code.

2 Modularity

By breaking a large program into modules it organizes it better, it makes the main function smaller and eaier to understand, and it again hides the detail in the functions rather than in main. The main function is used to provide overall control to the program.

By using modules a large program can be broken into parts to be done by different programmers.

3 Reusability

If a piece of code is used in many programs then it should be put into a library where all programs that need it can use it. This reduces the need to continuously re-invent the code each time. An obvious example would be the already existing functions like printf and scanf.

However, it is “sometimes” the case that the time to search through libraries for pre written functions can take longer than it does to write the function itself. That means that reusability becomes less effective and does not save time and therefore money.

Reusability may be more important in the C++ class.

VISUAL: main

Get_inputs

Calc_tax

Calculate_pay

Calc_net

Prepare bank transfer

_pay

726944548 by rt 15 April 2020 2 of 13

FUNCTIONS – 2 TYPES

1 LIBRARY FUNCTIONS

3 of 13

2 USER DEFINED

1 LIBRARY FUNCTIONS

Examples of Library functions used so far printf() scanf() pow() getchar()

Examples in a program

#include <stdio.h>

The getchar () function grabs 1 character from the input buffer and returns it to main. If it is main()

{ int char1; not assigned to a variable (char1 in this example) the value grabbed is lost.

In this case the value was stored in the variable char1 for later use in the printf. printf("\nEnter a character: "); char1 = getchar(); printf"\n\nThe character entered was %c. ", char1);

}

/* end of the program */

NOTE: printf

- It is NOT a C language statement

- It IS a function that is a pre-written piece of C code designed to output to the screen what you pass to that function

Someone wrote it years ago and it is stored in a C library of functions called stdio.h. Since there is a common need to display things on the screen, this module is re-usable.

726944548 by rt 15 April 2020 3 of 13

4 of 13

USER DEFINED FUNCTIONS

HOW TO DECLARE

Just like declaring variables

GENERAL FORMAT : return-type function name( argument type, argument type,

. etc.);

WHERE TO DECLARE A FUNCTION

Before main() – see program examples later

SPECIFIC EXAMPLES of how to declare a function :

1 void print_blankline(void);

NOTE: This is how to

2 void fah_to_celsius(int);

DECLARE a function before main starts

3 int fah_to_celsius(int);

You also need to write the code

(Shown later)

TO DECLARE A FUNCTION :

1 Provide a descriptive name

2 Ask -- does the function being called require anything from the calling function?

3 Ask -- does the calling function need anything back from the called function?

AND

After it is declared you will need to code what action the function performs.

726944548 by rt 15 April 2020 4 of 13

3 EXAMPLES OF FUNCTIONS

EXAMPLE 1

Write a function to

clear the screen.

5 of 13

TO BUILD A FUNCTION :

1 Provide a descriptive name

2 Ask -- does the function being called require anything from the calling function?

3 Ask -- does the calling function need anything back from the called function?

1 function name clearscreen

2 the called function (clearscreen) needs nothing from the calling function to do its job

- enter VOID as an argument clearscreen(void)

3 the calling function needs no information returned from the called function

- enter VOID in the return-type area void clearscreen(void)

This is an example of a function that does not have any values passed to it and does not need to return any values.

It can do the job required without an exchange of values

726944548 by rt 15 April 2020 5 of 13

EXAMPLE 2

6 of 13

The function clears part of the screen. The calling function tells it how many lines.

TO BUILD A FUNCTION:

1 Provide a descriptive name

2 Ask -- does the function being called require anything from the calling function?

3 Ask -- does the calling function need anything back from the called function?

1 function name clear_x_lines

2 the called function needs the number of lines from the calling function

- enter INT as an argument clear_x_lines(int)

3 the calling function needs no information returned from called function

- enter VOID in the return-type area void clear_x_lines(int)

This is a function that requires values sent to it in order to work, but does not return anything back to the calling function

726944548 by rt 15 April 2020 6 of 13

EXAMPLE 3

The function divides 2 integers and returns an answer

7 of 13

TO BUILD A FUNCTION:

1 Provide a descriptive name

2 Ask -- does the function being called require anything from the calling function

3 Ask -- does the calling function need anything back from the called function

A function

1 function name

2 divide2ints the called function needs 2 integer values from the calling function

- enter the type of arguments divide2ints(int, int);

3 the calling function needs an answer returned that could be a decimal

- enter double in the return-type area double divide2ints(int, int);

This is the third variation of a function. It requires values from the calling program (function) and returns a single value to the calling program (function)

726944548 by rt 15 April 2020 7 of 13

OTHER INFORMATION

8 of 13

ARGUMENTS -- PARAMETERS

The arguments used in the main() function, when it invokes the called function are also called arguments. answer = divide2ints( int1, int2); int1 and int2 are arguments or parameters

The right side of the expression causes control of the program to pass to the function divide2ints.

The values are passed to the called function, so that if int1 has a value of 7 and int2 has a value of

48, then just the values 7 and 48 are passed to the called function.

This type of parameter passing is called passing by values.

Any changes, within the called function have no effect on the calling function.

Some programming languages allow passing by reference . In this case the values are NOT passed but the address of the variables are passed. This means the called function can change the values in the calling function since the address of the variables is known. C language does not allow this type of programming; the same effect can be achieved by way of pointers (not covered yet).

RETURNING A VALUE

If the calling function requires a value from the called function then inside the called function a return statement is required.

General syntax: return variable_that_holds_the_value_needed_by_main; example return answer;

The return statement passes the value back to the function call in the calling function, which is then assigned to a variable. int function_called(one, two); example declared as used as answer_here = function_called (one, two);

726944548 by rt 15 April 2020 8 of 13

THE WHOLE PROGRAM USING EXAMPLE 3

9 of 13

/* w04-1.c */

#include double

<stdio.h> divide2ints(int, int); main()

{ int first = 10, second = 3; double answer; printf("Enter the first integer: "); scanf("%d", &first);

/* contains headers for functions you may use */

/* declare any functions used that are not in stdio.h */ printf("Enter the second integer: "); scanf("%d", &second);

Note: the semi-colon at the end of the function declaration.

Note: No variable names mention in argument list, just the data types answer = divide2ints(first, second); printf("\nThe answer is: %lf", answer);

}

/* END OF THE PROGRAM */

/* START OF CALLED FUNCTION */

/* Name the functions called followed by the code. The function name starts the pieces of code the same way that main started the function

main */ double divide2ints(int one, int two)

{ double result;

// The 2 arguments can have the same or different names

Note: In the actual function there is NO semicolon on the end of the line just as there was result = one / two; none with main return result:

}

/* END OF CALLED FUNCTION */

726944548 by rt -- 4/15/2020 9 of 13

10 of 13

GLOBAL vs. LOCAL VARIABLES

A variable declared inside a function has a LOCAL scope.

It is known only inside the function (see the variable result on the previous page). No action outside the function can change the value of the variable with local scope.

A variable declared outside of a function has GLOBAL scope. The variable is known to all functions defined after the variable is declared. (C actually uses the term EXTERNAL)

EXAMPLE

#include

// global variables – They are defined before or EXTERNAL to any function int global1, global2;

// functions declared void clearscreen(void); double divide2ints(int, int); main()

{ int local1; // this variable is known ONLY in main global1 = 10; global2 = global1 + 5; // <<<defined outside of main local1= global1 / global 2

Etc.  .

EXTRA NOTES ON FUNCTIONS

Read the notes in the books about the advantages and disadvantages of the use of functions or the stuff in the next box.

726944548 by rt -- 4/15/2020 10 of 13

11 of 13

NOTE

This would “seem” to most students that all variables should be declared as global and then there is no need to have arguments since all variables are known to main and any called function.

It is NOT a good idea. (Explanation from the internet)

The use of global variables makes software harder to read and understand.

Since any code anywhere in the program can change the value of the variable at any time, understanding the use of the variable may entail understanding a large portion of the program. Not so difficult in a small program, but more difficult in a very large program.

The use of global variables make separating code into reusable libraries more difficult because many systems (such as DLLs) don't directly support viewing global variables in other modules.

They can lead to problems of naming because a global variable makes a name dangerous to use for any other local or object scope variable. A local variable of the same name can shield the global variable from access, again leading to harder to understand code. The setting of a global variable can create side effects that are hard to understand and predict.

The use of globals make it more difficult to isolate units of code for purposes of unit testing, thus they can directly contribute to lowering the quality of the code.

726944548 by rt -- 4/15/2020 11 of 13

GLOBAL VARIABLES

– EXTERNAL VARIABLES

DEFINE

What they do

SYNTAX

Where placed

Return values

Argument list

Etc

2 WAYS TO DO THEM

12 of 13

The following are 2 oversimplified examples of the same program that uses functions in 2 different ways.

METHOD 1 - This is NOT the preferred method as it depends upon the use of global variables and their disadvantages. It will appear to be a superior method due mainly to the very small size of the examples. The following is a program with functions, but without arguments.

#include <stdio.h> int original, /* global variables -- defined before word main */ doubled; void double_it_function(void); /* prototype */

Example with

EXTERNAL variables main() {

printf("\n\n\n\n");

printf("Enter an integer number to be doubled : ");

scanf("%d", &original); double_it_function();

} /* END OF MAIN */

/* calling the function */

printf("\n\nThe doubled amount is %d", doubled); void double_it_function(void) { /* actual function code */ doubled = original * 2; return

}

/* END OF PROGRAM */

726944548 by rt -- 4/15/2020 12 of 13

13 of 13

METHOD 2 - this requires the passing of values to and from the function as the variables are all local to the function .

#include <stdio.h> int double_it_function(int); main() { int original, /* local variables -- defined inside a function */ doubled; printf("\n\n\n\n"); printf("Enter an integer number to be doubled : "); scanf("%d", &original); double = double_it_function( original ); printf("\n\nThe doubled amount is %d", doubled);

} /* END OF MAIN */ int double_it_function(int original) { int doubled; /* 2 variables defined locally -- could be different names */ doubled = original * 2; return doubled;

}

/* END OF PROGRAM */

BONUS:

Write a program that does the following:

Displays your name on the screen

Calls a function

- to ask for 2 numbers and

- a character input to say whether they want to add or multiply the 2 numbers

- a Switch to determine which function to execute

- do the add

Or

- do the multiply

Back in main a printf that will show the values of both numbers, the action taken (+ or *) and the result.

Call your code B1 and mail the script to me before midnight friday of week 5

726944548 by rt -- 4/15/2020 13 of 13

Download