The function decollation denotes the type of value it would returned to the calling portion of the program. Any of the basic data types such as int, float, char etc, may appear in the function declaration. In case, when a function is not supposed to return any value, it may be declared as type void.
For example:
int func_name(int a);
void func_nam(float b);
10.2.2 Function Name
The function name can be any name conforming to the syntax rules of the variables. However, you should normally use a function name relevant to the function operation.
For Example:
void show (void)
void square (int a, int b)
Example 10.2 illustrates the definition of a user defined line() function. Notice that the function definition is at the beginning of the function itself, and the semicolon is not used after the name of the function.
Example 10.2:
// A program to print a line
#include<iostream.h>
#include<stdio.h>
void line(void)
{
int j;
for (j = 1; j < 20; j++)
cout << "-";
cout << "\n";
}
main()
{
line ( );
}
10.2.3 Formal Arguments
Any variable declared in the body of a function is said to be local to that function. Other variables that are not declared within the body of the function are assumed to be global to the function and must be defined externally.
Consider the following code:
int counter (float x1, int x2, char c)
{
return (int value);
}
In this code segment, x1, x2, and c are formal arguments applicable to the function only. The function returns an int value to the calling program.
The program listed in Figure 4. 10 uses a line ( ) function to draw a line containing 20 asterisks (*). We can draw any number of such lines by calling the line ( ) function. Thus there is no need to write a program every time. You need to define the function once and call the user defined function any number of times to perform the desired function.
The variable j used in line( ) function in example 10.2 is only known to line ( ). It is invisible to the main ( ) function. If we used this variable in function main ( ) without declaring it there, then compiler gives an error message because main ( ) do not know any thing about this variable.
This is very important to know while writing functions in C++. Variables used in a function are unknown outside the function. Thus a local variable will be known to the function it is defined in, but not to others. A local variable used in this way in a function is known in C++ as an “automatic” variable, because it is automatically created when a function is called and destroyed when the function returns.
Example 10.3 demonstrates the function declaration, function calling and function definition
Example 10.3:
//A Program demonstrating function calling, declaration and definition # #include<iostream.h>
void show (void); //prototype
void main (void)
{
void show (void); //function declaration
show ( ); //function calling
}
void show (void) //function definition
{
cout << “demonstration program \n”,
cout << “for calling a function \n”;
} // end of function
When the programme is compiled, the output of the program will be:
demonstration program
for calling a function
The program given in example 10.4 uses a special character ‘\a’ which is called BELL alert in the standard ASCII code. By using the cout statement, you can create a beeping sound by using the code given in example 10.3. The program calls a function called twobeep(). The function makes two beeps separated by a short silent interval. Then the program asks you to type a letter. When you do, it makes two beeps again.
How the delay is created?
A for loop is set up to cycle 1000 times. This constitutes a “null” statement: a statement with nothing in it. Its only role is to terminate the for loop after cycling 1000 times. This may be thought as a for loop for introducing delay in the loop.
Example 10.4:
A program that make two beeps
#include<iostream.h>
#include<stdio.h>
/*twobeep */
/* beeps the speaker twice */
void twobeep(void)
{
int k;
cout << "\a";
for (k = 1; k < 1000; k++);
cout << "\a";
}
main()
{
char x;
twobeep();
cout << "\nType any character ";
cin >> x ;
twobeep();
}
10.2.4 Function Prototype
The function prototype tells the C++ compiler in advance about some characteristics of a function used in a program. i.e. it notifies the C++ compiler of the type and number of arguments that a function will use.
Prototyping helps the compiler to detect errors if the function is improperly used.
A function prototype takes the form:
Type function_name(type argument_1, type argument-2,. . .);
It has three main components. These are:
i. Function type
ii. Function name
iii. Arguments
Function type
The function “type” is the type of the returned value. If the function does not return a value, the type is defined as void.
Function name
The function name is any legal identifier followed by the parentheses without spaces in between.
Arguments
The arguments (or parameters) are given inside the parentheses, preceded by their types and separated by commas. If the function does not use any parameters, the word void is used inside the parentheses. Here are some examples for prototypes of built-in functions
int getchar(void);
double pow(double x, double y);
void exit(int x);
The first function, int getchar(void); returns an integer value and does not take any arguments. The second function double pow(double x, double y); takes two double arguments (x and y) and returns a value of the type double. The third function void exit(int x); returns no value but it accepts an argument x of the type integer.
The header files such as iostream.h and stdio.h contain the prototypes of the built-in C++ functions. You may sometimes forget to include the proper header file in your program, but you still have the program running and may get correct results. This is because if you do not include the header file, the compiler will use the default type which is of the type in for any function.
10.2.5 Use of void() Function
If the function is of the type void, no return statement is used. Actually, the main() block of the C++ program is a function, and because no type is specified, it is therefore considered of the type int, Turbo C++ compiler gives a warning if you do not use the return statement at the end of the main() block. You can avoid this warning by writing your main function as given below:
main()
{
statement(s);
return(0);
}
This means that no returned value is expected from the main function. Another way to avoid the warning message is to use the void type like this.
void main()
{
………………
}
You may also run across programs with the main function declared as:
void main (void);
10.1 Accessing a Function
A user defined function is invoked or called from the main program simply by using its name, including the parentheses containing the parameters to be passed, if any. The parentheses are mandatory so that the compiler knows you are referring to a function and not a variable that you forgot to declare.
10.3.1 Invoking a Function without Passing Argument(s)
It is the simplest way of writing a user defined function because there is no formal argument transfer between the calling statement of the program and a called program function. Program shown in example 10.5 (a) calls the function sample() without passing any argument. The function sample()after execution transfers the control back to the function main (). The presence of void in the function void sample(void) shows that no value is passed to the function.
Example 10 .5
/* Program for calling function without passing values from main() */
#include<ostream.h>
void sample (void); /* prototype declaration of function sample */
main()
{
cout << "\n I am calling function sample \n" << endl;
sample();
}
void sample(void) /* function definition */
{
cout << "Thank you for calling me." << "I am sample "<< endl;
} /* end of function */
When the program is run, the output will be:
I am calling function sample
Thank you for calling me. I am sample
10.3.2 Passing Arguments to Function
Arguments are used to pass the values of variable to a function. The structure of a function passing one argument is shown in example 10 6.
In the definition of function bar1 () shown in Figure 4.13 (a), int score within the parenthesis is the formal argument. This shows that the main () will transfer the argument for score which has a integer value. The key word void before bar1 indicates that the function bar1 () does not return any value to the main () block.
Example 10.6
/* A Program using argument to pass data to a function */
#include<iostream.h>
#include<stdio.h>
void bar1(int score)
{
int j;
for (j = 1; j <= score; j++)
cout << "\xCD”; /* draw double-line character*/
cout << "\n";
}
main()
{
cout << "Harun \t";
bar1(25);
cout << "Chacha \t";
bar1(35);
cout << "Ashim \t";
bar1(5);
cout << "Hemed \t";
bar1(10);
cout << ("Jackson \t";
bar1(20);
}
The declarations for the argument variables serve to remind the compiler and the programmer that these are special variables whose values are supplied by the calling program.
When the program is run the output will be as follows:





The purpose of the function bar1() is to draw a horizontal line, made up of the double-line graphics character “\xCD” on the screen. The program shown in example 10 5 generates function bar1() that draws a barograph for names. The bar length is represented by the argument value given to the function bar1(). For each person, the main program prints the name and then calls the function bar1(), using as an argument the score value entered for the function bar1()
Storage of Values when passed as Arguments to a Function
The program given in example 10.7 transfers the value of x and y to the function swap1() and the function swap1() receives them and stores them as separate variables xx and yy in a separate location in the main memory. It then prints the values of xx and yy when asked to do so.
This value is printed by taking the values from the main memory assigned for the variables xx and yy in the called function. This process known as passing arguments by value results in a waste of memory space.
Example 10.7:
/* This program that demonstrates passing arguments to a function */
#include<iostream.h>
#include<stdio.h>
void swap1(int xx, int yy)
{
cout << "First is " << xx << endl;
cout << "Second is " << yy << endl;
}
main()
{
int x = 1;
int y = 7;
swap1(x, y);
}
A program shown in example 10.8 passes the formal arguments to a function cube() but the function cube() does not return any value to the caller. It is one way communication between a calling program and the function block.
Example 10.8
/* Program for calling function by passing formal arguments from main ( ) */
#include<iostream.h>
void cube(int, int); /* prototype declaration function cube*/
main()
{
int x, y;
cout << "\n Enter integer values for x and y: \n" << endl;
cin >> x >> y;
cube(x, y); /* function call */
}
void cube(int x, int y) /* function definition */
{
x = x*x*x;
y = y*y*y;
cout << "x cube = " << x << endl;
cout << "y cube = " << y << endl;
} /* end of function */
When the program is run, the output will be as follows:
Enter integer values for x and y:
4 5
x cube = 64
y cube = 125
Example 10.9
/*A program that finds a cube of a number, using a function declaration with the return statement. */
#include<iostream.h>
float cube(float); /* prototype declaration of function cube */
main()
{
float i, max, value;
max = 2.0;
i = -2.0;
while(i <= max)
{
value = cube(i);
cout << "i = " << "\t" << "\t" << "1 cube = " << "\t" << value << endl;
i = i + 0.5;
}
}
float cube(float n) /* function definition */
{
float value;
value = n*n*n;
return (value);
} /* end of function */
When the program is run the output will be as follows:
I = -2 I cube = -8
I = -1.5 I cube = -3.375
I = -1 I cube = -1
I = -0.5 I cube = -0.125
I = 0 I cube = 0
I = 0.5 I cube = 0.125
I = 1 I cube = 1
I = 1.5 I cube = 3.375
I = 2 I cube = 8
In example 10.9, the function cube() gets the value of the parameter n. It calculates the cube of n and assigns it to value.
The statement return (value) transfers the calculated cube value of n to the main(). Thus, every time the function cube(i) is called in the main() block, the calculated value of cube of the argument is returned to themain(). The main() block uses a while loop to assign different values to the variable i. This argument, i is transferred to the function float cube (float n)
10.3.3 Passing Multiple Arguments to a Function
You can pass as many arguments to a function as you wish. The program in example 10.10 passes to a function called rectang1(). The purpose of this function is to draw a rectangle whose sides are given as multiple arguments namely (int length, int width) in the declaration:
Example 10.10
/* Program that passes multiple arguments to a function*/
#include<iostream.h>
#include<stdio.h>
void rectang1(int length, int width)
{
int j, k;
length /= 2; /* scaling length to half */
width /= 4; /* scaling width to one fourth */
for (j = 1; j <= width; j++)
{
cout << "\t\t";
for (k = 1; k <= length; k++) /* line of rectangles */
cout << "\xDB"; /* print one rectangle */
cout << "\n"; /* next line */
}
}
main()
{
cout << "Drawing room " << endl;
rectang1(22,12); /* draws shape of drawing room */
cout << "Kitchen" << endl;
rectang1(10,7); /* draw shape of kitchen */
cout << "Bedroom" << endl;
rectang1(12,12); /* draws shape of bathroom */
cout << "Bathroom" << endl;
rectang1(6,8); /*draw shape of bathroom */
}
The typical run of the program is shown in below:
|
Drawing room
|
Kitchen
|
Bedroom
|
Bathroom
Exercise 4
1. When do you use the keyword return while defining a function? When do you not use the keyword return when defining a function?
2. Write a program in C that prints out the larger of two numbers entered from the keyboard. Use a function to do the actual comparison of the two numbers. Pass the two numbers to the function as arguments, and have the function return the answer.
3. Write a program in C that asks the user to input the length of two sides of the right-angled triangle. Make use of the built-in functions pow() and sqrt() to compute the length of hypotenuse using Pythagoras Theorem.
4. Write a C program that asks for a distance in meters and convert it to feet.
5. Write a C program that calls a function which returns a cube of a given number.
6. Write a programme to accept a decimal number and convert it to binary number.
Exercise 5
1. Write a program in C++ that asks the user to input the length of two sides of a right angled triangle. Make use of built in functions pow() and sqrt() functions to compute the length of the Hypotenuse using Pythagoras theorem.
2. Using switch-case statements write a program in C++ that Add, Subtract, Multiply and Divide two numbers. Let the program display the menu of options, prompt the user to enter numbers and, perform computations and print the result in each case.
3. Using switch–case statements write a program that compute the area of a circle, the area of a rectangle and the area of a triangle. Let the program prompt the user to enter dimensions, perform calculations and print the result in each case. For simplicity, assume C++ is not case sensitive.
4. Using if ... else conditional statement and only one function main(), write a program to convert temperature from degrees Centigrade to degrees Fahrenheit. Provide the menu from which a user can make a choice.
(Hint: Use the mathematical model C = (5/9)(F – 32)).
5. Write a C program that uses a function called cylinder_vol() to compute the volume of a cylinder. Let the main() program prompt the user to enter radius and height of a cylinder, pass these values to cylinder_vol() which perform the computation and return the result to main for display.
(Hint: Use the mathematical model v =
r2h)

6. Using the “switch” statement write a program that recognizes the numbers 2, 4, 6, 8 and 10. Let the program display the word TWO when the number two is entered, FOUR, when the number 4 is entered and so on. Let also the program display the statement UNRECOGNIZED INPUT!, when the number entered is not among the numbers mentioned above.
Exercise 6
1. Write a C++ program that prompt the user for an integer value. Next using a for loop make it count from this value to zero displaying each number on its own line. When it reaches zero have it sound a bell.
Hint: For a bell to sound use the character combination (“\a”).
2. Using switch–case statements write a program that compute the area of a circle, the area of a rectangle and the area of a triangle. Let the program prompt the user to enter dimensions, perform calculations and print the result in each case. For simplicity, assume C++ is not case sensitive. Note that C++ is case sensitive.
3. Write a C++ program to read two “float” values representing the radius and height of a cylinder. Let your program define two functions cylinder_area() and cylinder_vol(), which receive radius and height dimensions from main(), calculate the area and volume of a cylinder and then return the results to main()for display.
Hint: Use the following mathematical models: A = 2πr2 + 2πrh, V = πr2h.
4. Write a C program to read a “float” number representing temperatures. Let your program define two functions convert_Fahr()and convert_Cels(), whereby convert_Fahr()converts degree Fahrenheit to degree Celsius and convert_Cels() convert degree Celsius to Fahrenheit. Your main program should print the float equivalent temperature results such us:
“100.0 DEGREES CELSIUS EQUALS 212.0 DEGREE FAHRENHEIT”.
After the user has entered a number, let him have a choice of what conversion he want to perform.
5. Using if or if ... else conditional statement, write a program to convert temperature from degrees Centigrade to degrees Fahrenheit or vise versa. Declare a function other than main()that receives temperature value perform the conversion and return the converted value to main() for display. Provide the menu from which a user can make a choice of what a conversion to perform. (Hint: Use the mathematical model C = (5/9)(F – 32)).
6. Write a program that reads two “floating” point numbers representing the radius and height of a cylinder. Declare two functions that calculate the area and volume of a cylinder and let the program print out the area and volume for the given dimensions. Your output should take the form.
The area of a cylinder of radius …cm and height …cm is … square cm.
The volume of a cylinder of radius …cm and height …cm is … cubic cm.
Also let your program print the error message:
“ERROR!! Negative values not permitted!!”
In case the user enters negative values for radius or height.
No comments:
Post a Comment