Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Functions in C++: Definition, Syntax, and Calling Mechanisms, Study notes of Computer Programming

An in-depth explanation of functions in c++ programming, including their definition, syntax, and calling mechanisms. Topics covered include function types, argument lists, return values, and function declarations and definitions. Examples and code snippets are included to illustrate the concepts.

Typology: Study notes

2011/2012

Uploaded on 08/06/2012

anchal
anchal 🇮🇳

4.6

(9)

103 documents

1 / 11

Toggle sidebar

Related documents


Partial preview of the text

Download Understanding Functions in C++: Definition, Syntax, and Calling Mechanisms and more Study notes Computer Programming in PDF only on Docsity! Lecture No. 9 Reading Material Deitel & Deitel – C++ How to Program chapter 2 3.1, 3.2, 3.3, 3.4, 3.5, 3.6 ction efinition of a Function is almost complete. The basic constructs of programming are quence, decision making and loops. You have learnt all these techniques. Now we an write almost all kinds of programs. There are more techniques to further refine the rograms. One of the major programming constructs is Functions. C is a function- functions. sider the making of a Summary o Introdu o Functions ction o Structure of a Fun nd Do Declaration a o Sample Program 1 Sample Program 2 o o Sample Program 3 ry o Summa o Tips ntrodu tion I c ow our toolkit N se c p oriented language. Every program is written in different In our daily life, we divide our tasks into sub tasks. Con laboratory stool. It has a seat and three legs. Now we need to make a seat and three legs out of wood. The major task is to make a stool. Sub tasks are, make a seat and then fabricate three legs. The legs should be identical. We can fashion one leg and then re-using this prototype, we have to build two more identical legs. The last task is to assemble all these to make a stool. We have a slightly difficult task and have broken down it into simpler pieces. This is the concept of functional design or top-down designing. In to design, we look at the problem from top i.e. identification of the problem. What we p 77 docsity.com 78 ng as we get easily manageable sk. Let's consider an example like home construction. From the top level, we have to ome. Then we say that we need design of the home according to which e building will be constructed. We need to construct rooms. How can we construct a e we come down to the level where a task is easily manageable nd doable, we stop doing further refinement. When we break up a task into smaller s top at a reasonable level. Top-down designing mechanism is based on e principle of 'divide and conquer' i.e. we divide a big task into smaller tasks and em. k at a simple example to understand the process of dividing big task to simple ones. Suppose we want to know how many students are currently logged in the LMS (Learning Management System) of VU. This task will be handed over to dministrator to find out the number of students currently logged in LMS work administrator will check the network activity or get this e list of students currently logged in. The mber hat list and the result is given back to us. What s hap There was a simple request to find the number of udents currently logged in LMS. This request is delegated to the network ministrator. The network administrator performs this task and we get the result. In s we are not interested in the names or list udents. This technique is known as parallel rocessing. In terms of programming, network administrator has performed a function ocess, the network n from us. So the information he function. Some information is given to the network quest to calculate the number of students currently logged in is provided back to us (i.e. the number of students). subtasks. They receive some information, do some process and rough a calling program. Calling program is doing and how it is performing its task. g methodology. The calling program calls a function function. When we write a unding braces just like with tegories of functions: rn a value the square of an integer such that function uare of the integer. Similarly we may have a function which displays have to solve? Then refine it and divide it into smaller pieces. We refine it again and divide it into smaller pieces. We keep on doing it as lo ta construct a h th room? We need bricks, cement, doors, windows etc. Procurement of all of these things is tasks. Onc a ub tasks, we s th then accomplish th Let's have a loo in the network a of the university. The net ormation from the database and get thinf un of students is counted from t pened in this whole process?ha st da the mean time, we can do some other task a f students. We only want the number of sto p i.e. calculation of the number of students. During this pr dministrator also gets the list of students which is hiddea hiding is also a part of t .e. the readministrator (i the LMS) while some information unctions F e likeThe functions ar provide a result. Functions are invoked th unction does not need to know what the f callinThere is a specific function- by giving it some information and receives the result. e hav a maiW e n ( ) in every C program. ‘main ( )’ is also a , and surrofunction, it must start with a name, parentheses ain ( ) Functm . ions are very important in code reusing. here are two caT alue 1. Functions that return a v s that do not retu2. Function e a function that calculates Suppose, we hav will return the sq docsity.com 81 rite the declaration of functions before the main( ) tion is a one line statement in which we write the return tion and the data type of arguments. Name of the arguments is of the function contains the complete code of the nction. It starts with the declaration statement with the addition that in definition, e the names of the arguments. After this, we write an opening brace and the function square is defined in a separate file or after the calling function, then we eed to declare it: Declaration: declaration. Therefore we w nction. Function declarafu type, name of the func not necessary. The definition fu we do writ then all the statements, followed by a closing brace. Example: If n int square ( int ); Definition: int square ( int number) { return (number * number ) ; } Here is the complete code of the program: square of a given number eam.h> ns. ber, result; cout << “ Please enter the number to calculate the square ”; cout << “ The square of “ << number << “ is “ << result; } //This program calculates the #include <iostr // Function declaratio int square(int); main() { int num result = 0; number = 0; cin >> number; // Calling the function square(int number) result = square(number); docsity.com 82 // function to calculate the square of a number return (number * number ) ; } int square ( int number) { A function in a calling program can take place as a stand-alone statement, on right- his can be a part of an assignment expression. result = square (number + 10); cout << “ The square of “ << number << “ is “ << square (number); in the function using the eturn keyword) is assigned to the variable result. In this case, the square(5) will signed to variable result. There may be functions which do ot return any value. These functions can't be used in assignment statements. These roblem statement: some number (xn). e want to get the power of some number. There is no operator for power function in nction to calculate the power of x to n (i.e. xn). How can we alculate the power of some number? To get the power of some number x to n, we x up to n times. Now what will be the input (arguments) to the ber and power, as number can be a real number so we have to declare umber as a double date type and the power is an integer value so we will declare the eger. The power is an integer value so we will declare power as an sult will also be a real number so the return value type will be of double e should be descriptive, we can name this function as e declaration of the function is: w ( double x, int power ) ; hand side of a statement. T Considering the above example, here are some more ways of function calling mechanism. result = 10 + square (5); or or result = square (number) + square (number + 1) + square (3 * number); or In the above statements, we see that functions are used in assignment statements. In a statement result = square(5); The square(5) function is called and the value which is returned from that function (i.e. the value returned with r return 25, which will be as n functions are written as stand-alone statements. Sample Program 1 C is called function-oriented language. It is a very small language but there are lots of functions in it. Function can be on a single line, a page or as complex as we want. P Calculate the integer power of Solution: W C. We need to write a fu c need to multiply x with function? A num n power as an int integer. The re data type. The function nam raiseToPow. Th double raiseToPo docsity.com 83 power of x up to power times, we need a loop which will be executed ower t unction is: funct n to c ( double x , int power ) t i ; result = 1.0 ; i <= power ; i ++ ) { as result = result * x } sult ) ; To calculate the p imes. The definition of f // io alculate the power of some number double raiseToPow { double result ; in for ( i = 1 ; result *= x ; // same return ( re } Her the is e program which is calling the above function. This program is calling a function raiseToPow. eam.h> << “ Please enter the number “ ; // #include <iostr //Function declaration double raiseToPow ( double , int ); main ( ) { double x ; int i ; cout cin >> x ; cout << “ Please enter the integer power that you want this number raised to “ ; cin >> i ; cout << x << “ raise to power “ << i << “ is equal to “ << raiseToPow ( x , i ) ; } Now we have to consider what will happen to the values of arguments that are pa x i raiseToPow ssed the function? As in the above program, we are passing and to the ctually nothing is happening to the values of x and i. These values are . Such function calls are known as 'call by value'. to function. A unchanged. A copy of values x and i are passed to the function and the values in the calling program are unchanged docsity.com { int number; 86 { { } cout << " Please enter the number: " ; cin >> number ; if ( isEven ( number ) ) { cout << " The number entered is even " << endl; } else { cout << " The number entered is odd " << endl; } } int isEven ( int number ) { if ( 2 * ( number / 2 ) == number ) return 1; } else return 0; } Summary Functions are very good tools for code reuse. We have seen in the above example th the area of two circles has been calculated without rewriting the code. This mea at ns that we are going to use a function in our program and the definition of the function is fter the calling program. The calling program needs to know how to call the function, re and what it will return. So its declaration must occur before eclare a function before using, the compiler will give an error. If of claration is used as a the code has been reused. We can reuse the circleArea function to find the area of any circle. A function performs a specific task. Functions also provide encapsulation. The calling program does not know how the function is performing its task. So we can build up modular form from small building blocks and build up more and more complex programs. If a what the arguments a sage. If we do not du we define a function before the calling program, then we do not need a separate declaration. The function declaration is also known as function prototype or function signature. Whenever, we need to build something, first of all we build a prototype that thing and then later on we build it. Similarly the function de docsity.com 87 top- down methodology. We break the program into maller modules and just declare the functions and later on we can define these. power prototype. We are following the s Exercise: 1. Modify the raise to function so that it can handle negative power of x, ero an positi w of x. ring z d ve po er 2. Modify the area of function put in error checking mechanism. o smaller pieces, which is a top-down structured approach. be a small module, self-contained. It should solve a well be self- explanatory. he code. Tips  We used functions for breaking complex problems int  Each function should defined problem.  Variable names and function names should omment t Always c docsity.com
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved