Functions and Arrays (PDF)
Document Details
Uploaded by ImpartialOtter2669
Babcock University
Tags
Summary
This document discusses user-defined functions and one-dimensional arrays in programming, offering examples and explanations for their practical application.
Full Transcript
User-Defined Functions A function or subroutine or program module is a chunk of code/ fragment/ segment (or lines of set of lines of code) logically packed and designed to perform a single well-defined task or some units of tasks. For example, if you have factorial of a number an...
User-Defined Functions A function or subroutine or program module is a chunk of code/ fragment/ segment (or lines of set of lines of code) logically packed and designed to perform a single well-defined task or some units of tasks. For example, if you have factorial of a number and square of a number to find, the best practice is to make them into separate functions/program modules that you can call them separately anytime you need them. No matter how simple these operations appear, they are two different tasks (refereed to as separate responsibilities in Object Oriented Programming). The best practice is that a function should do one task and do it well (i.e. it should support single responsibility). Cramming these together in one module or just main() function is a poor programming practice which leads to a lot of difficulties e.g. debugging, maintenance, reuse problems. A good software engineering practice such as modularising your code lends itself to the rich benefits in these two attributes (maintainable and reusable programs) and even more. Basic Things To Know: (1)Function Definition -How to write a function within a program (2)Function Declaration –How to make the function known to the program (3)Function call - How to call a function from any part of the program (4)Ways of passing Parameter(s) - How to send information/data to a function (5)Returning result from function and functions that return nothing (6)Scope of variables The Concept of Procedure Oriented Programming(POP) (Modular Programming) Words like module, subroutine, function are synonymously used to imply the same concept originating from the idea called structured programming concept where programs are written following some sets of procedures well organised to make programming experience easy. Benefits include program readability, write-ability, reusability, maintainability and so on. A complete program may contain a number of different tasks/responsibilities that is logical enough to make into different functions such that these functions are only called when they are needed. Take for example a calculator program to perform four basic operation for a pupil should include addition, subtraction, multiplication and division. As simple as these operations are, each is unique in its own respect. Therefore, we can create four subroutines or module or functions called at needed times to accomplish this. Structure of Modular Concept main( ) f1() f2() f3() There are 4 functions here, the main() function, f1(), f2() and f3(). main() calls f1 and f2(), while f2() can also call f3() as the case may require. We do not want to cram all these tasks into main() alone anymore as we used to do in the elementary coding class. A scenario of how f2() may need f3() is this: If function main() calls f2() to action where f2() needs f3() before it can carry out its entire duty. It simply means that part of f2() duty is delegated to f3(). And this sub-task is delegated to f3() so that f2() is not also crammed up with many things. For instance, if f2() is to fetch students with CGPA of 4.0 and above but should Declaring and Defining a function : One solid advantage of creating a function is that you can always re-use it by just calling it instead of writing the entire code again when it is needed somewhere else within or outside the immediate program. Once you know the specific task a function should carry out, the first is to name it. Just the way we name variables but with a bracket after the name. A function can be given any name like adekolaDan() but it makes sense and makes a good programming practice to give a name that reflects what in particular the function or module is to do. Therefore, I will prefer displayInfo() as a name for the following function. Note, generally, a function has return type and form(format to follow). We shall explain these better with time. Declaring and Defining a function : 1. void displayInfo() 2. { 3. printf(”\n Welcome to the Input Segment”); 4. printf(”\n Please Enter Your Input Value”); 5. printf(”\n Note That Input is within 0-10”); 6. } The first line which declared the function is called function header; comprising 2 words, function return type (void) and function name (displayInfo()). displayInfo() is a function having 3 lines of executable codes that are just displaying some messages on the screen for the user. The advantage here is that if you need to display the same message anywhere or as many times as you want in the program, you do not need to rewrite line 3 to 5 instructions but only make a call to the function displayInfo(), the all the 3 messages are done in one go. Declaring and Defining a function : Void: When a function terminates and does not send back or return some information/ value but only display a message on the screen or does only the task assigned, it means such does not return any information/value. So we say the return type of that function is void. But if has a value to send back to the caller (e.g. main()) , we say the function has a return type. Therefore, in such a situation we don’t put void but rather the keyword for the type of the value it is returning. Example is float or double for a floating point value or int for integer and so on; instead of void. displayInfo(): This is the name you chose to give the function, followed by a pair of empty brackets. If there is a need to send information or pass value into a function, then the pair of brackets will not be empty but will contain the information. This is the input avenue or medium to Declaring a function in C C language demands that functions may be declared before use especially if you intend to write the function anywhere in the program. It may not be necessary if the functions are defined and seen ahead by the program before use. The culture of declaring a function is simple to follow. Just the same way you declare a variable before use, you also declare a function before use. The simple way to declare a function is to copy the function definition header only and add a semicolon as follows: void displayInfo(); // function now declared The general format is as follows: return-type functionName(optional parameter list); Note: As a variable is declared in the function where it is used, function declaration is placed or done in the function where it would be used or called. E.g. if you placed a declaration inside the main() function, it means the function would be used or called by only the main() function. But if you want the function to be called or used by another function other than main(), then you need to place its Declaring a function in C A) Declaring a function as local to main() #include int main() { void displayInfo(); // function now declared inside main, seen by main alone int I, j, count; // other variables local to main() function ---- ---- return 0; } B) Declaring a function as global (External function) #include void displayInfo(); int main() { int I, j, count; // other variables local to main() function ---- ---- Calling a function: Getting a written function to perform its task is a process described as calling the function. When a function is called, we are actually doing the instruction(s) inside it. We were used to only one function called main() in our earlier programs; where you write everything inside main(). The new functions we are making/creating/defining by ourselves can be called by the main() and can even call each other. Calling a function: After declaration and definition, you get a function to perform its task by calling the function. To call, use its name followed by empty brackets when there is no information/parameter to pass into it. e.g. displayInfo(): This function is defined separately outside (not inside) the main function. It stands alone. It means a function is a self-contained unit written to perform a specific but well-defined task. The following example will demonstrate what we are saying better. Also note that the order of arrangement of these functions within the program has no effect / does not matter. But very importantly only know that execution starts with the main(). Program Example: void main() { … displayInfo(); scanf(“%d”, &hour); … }// end of function main() //function is declared and defined below void main() { printf(”\n Welcome to the Input Segment”); printf(”\n Please Enter Your Input Value”); printf(”\n Note That Input is within 0-10”); }// end of function displayInfo() Program Example: Evidently there are two functions in the code example above, the first main() and the second displayInfo(). The second is called inside the main(). The “ … “in the main function preceding the calling indicates that the main function has been executing some series of instruction before getting to the line where the function displayInfo() is called. As this function is called in the function(main() ), program control flow jumps out of main() from that very point to where the called function is defined (void displayInfo(){…} ), carries out the instructions in the called function and comes back to the point where the calling took place to proceed execution. A stack activation record is internally required for the program to be able to know where to return. One function Example: void main() { float price, tax, result; Scanf(“%f”; &price); Scanf(“%f”; &tax); result = price * ( 1 + tax /100); pintln(“Cost After Tax = %f “, result); } The program illustrate a program comprising only a main() function calculating a cost after tax. The same program can be re-written to use two functions where tasks are delegated to different functions. functions: We can create a function to perform the same calculation to enable us to call the function at various points in the program where the calculation could be done using different values passed to the function per each call. This gives the advantage of code reusability. See below: float addTax(float price, float tax) { float answer; answer = price * ( 1 + tax /100); return answer; } The above function is named addTax and it is of type float (return type) The variables(price and tax) declared as float within the bracket are called formal parameters. Formal Parameters: are variables created exclusively to hold values sent in from the calling function(caller). They hold the values of data sent in the order with which there are arranged in the function parameter declaration. i.e. price first, then tax second. parameter names at the function declaration does not PARAMETERS AND PARAMETER PASSING: depend on the name you give the function parameters where it is called. It means being “formal”, they can receive any value passed as far as the order and type are not compromised. For now, parameter are said to be passed by value. In the code above, variable answer is declared float inside the function addTax. This is called a local variable as far as its scope is concerned. When a variable is local to a function, it means it is known or valid within that function. For example, answer is not known to main function in the example below. Similarly, variable result is local to the main function and is not equally known to function addTax. The keyword return ends the function. The function terminates as soon as the program reaches this point. The keyword return is used to send the result of computation back to the caller. The control jumps back to the calling function sending back a value i.e. the result of the computation. Any code written after it becomes unreachable and that gives a compilation error. MAKING YOUR OWN FUNCTIONS(USER-DEFINED FUNCTIONS) 1) #include 2) int main() 3) { 4) float price, tax, result; //variable declarations 5) float addTax(float price, float tax); // function declared 6) printf("\n Enter the value of Price:"); 7) Scanf(“%f”; &price); Line 10 represents a call to addTax() function. Here, 8) printf("\n Enter the value of Tax:"); 9) Scanf(“%f”; &tax); parameters are passed by values, the value of price and 10)result = addTax(price, tax); // call; tax are sent to the function. At 11)pintln(“Cost After Tax = %f “, result); 12)return 0; line 10, these are called actual 13)} argument because a copy of what is read into price and tax are passed (to be used by the 14)float addTax(float price, float tax) 15) { function outside main()). 16) float answer; 17) answer = price * ( 1 + tax /100); 18) return answer; 19) } // SOLVING FOR FACTORIAL USING ONLY MAIN FUNCTION 1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5 2) #include 3) int main() 4) { 5) int i, n, mult = 1; //variable declarations; set mult to 1 for multiplication 6) printf("\nEnter the value of n for the factorial:"); 7) scanf("%d", &n); 8) // logic using iteration to do 1*2*3*4*5 9) for(i=1;i