Tuesday, January 3, 2012

Moving on with programming..

A natural way to solve large problems is to break them down into a series of sub-problems, which can be solved more-or-less independently and then combined to arrive at a complete solution. In programming, this methodology reflects itself in the use of sub-programs, and in C++ all sub-programs are called functions.
Here's a trivial example of a program which includes a user defined function, in this case called "area(...)". The program computes the area of a rectangle of given length and width.
         #include<iostream>
     using namespace std;
       
     int function(int parameter1, int  parameter2 ); /* function declaration */
       
     // MAIN PROGRAM: 
     int main()
     {
        --
        --
     }
     // END OF MAIN PROGRAM 
       
     // FUNCTION  
     int  function (int  parameter1 , int  parameter1 ) /* start of function definition */
     {
         --   
     }                            /* end of function definition */
     // END OF FUNCTION 
  • The structure of a function definition is like the structure of "main()", with its own list of variable declarations and program statements.
  • A function can have a list of zero or more parameters inside its brackets, each of which has a separate type.
  • A function has to be declared in a function declaration at the top of the program, just after any global constant declarations, and before it can be called by "main()" or in other function definitions.
  • Function declarations are a bit like variable declarations - they specify which type the function will return.
A function may have more than one return statement, in which case the function definition will end execution as soon as the first return is reached. 

C++ allows polymorphism,--> it allows more than one function to have the same name, provided all functions are either distinguishable by the typing or the number of their parameters. Using a function name more than once is sometimes referred to as overloading the function name. 

One of the main purposes of using functions is to aid in the top down design of programs. During the design stage, as a problem is subdivided into tasks, the programmer should have to consider only what a function is to do and not be concerned about the details of the function. The function name and comments at the beginning of the function should be sufficient to inform the user as to what the function does.

No comments:

Post a Comment