Summary

These lecture notes provide an introduction to functions in C++. They cover the basics of function declarations, calls, definitions, and parameters, along with examples. The material is suitable for an undergraduate computer science course.

Full Transcript

Functions 1 Functions A group of statements that perform a specified operation is called a function. In a function we group several program statements into a unit and give that unit a name that is called func...

Functions 1 Functions A group of statements that perform a specified operation is called a function. In a function we group several program statements into a unit and give that unit a name that is called function name. Function can be invoked any where in the program. Program statements that appear in the program more than once are suitable for creating a function. Function code is stored in only one place in the memory. Another reason for creating functions is that a complex or bigger program code is divided into different functions due to which it becomes easy to manage the program. 2 Functions There are 3 things important related to a function. i) Function Declaration ii) Function Calling iii) Function Definition 3 Functions A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. To use a function, you will have to call or invoke that function. A function is knows as with various names like a method or a sub-routine or a procedure etc. 4 Functions How user-defined function works in C++ Programming? 5 Function The general form of a C++ function declaration and definition are as follows: return_type function_name( parameter list ); // declaration return_type function_name( parameter list ) // definition { //body of the function } Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. 6 Function Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does. 7 Repetition of Code - Example int main() { for(int a=1; a

Use Quizgecko on...
Browser
Browser