Chap 6 Functions
Chap 6 Functions
Objectives
At the end of this chapter, the reader should be able to:
Such programs are easier to write and debug and their logical
structure is more clear than programs which lack this type of
structure. This is especially true of lengthy, complicated programs.
}
function_name represents any meaningful
descriptive tag you will assign to the function for
example rect_area above.
return (expression);
Notice the long int specification that is included in the first line of
the function definition. The local variable prod is declared to be a
long integer within the function.
It is assigned an initial value of 1 though its value is recalculated
within a for loop. The final value of prod which is returned by the
function represents the desired value of n factorial (n!).
If the data type specified in the first line is inconsistent with the
expression appearing in the return statement, the compiler will
attempt to convert the quantity represented by the expression to the
data type specified in the first line.
This could result in a compilation error or it may involve a partial
loss in data (due to truncation). Inconsistency of this type should be
avoided at all costs.
1. main()
2. {
3. int a , b , c ,d;
4. /*read the integer quantities*/
5. printf(“\n a = ”);
6. scanf(“%d”, &a);
7. printf(“\n b = ” );
8. scanf(“%d”, &b);
9. printf(“\n c = ”);
10. scanf(“%d”, &c);
11. /* Calculate and display the maximum value */
12. d = maximum (a, b);
13. printf (“\n \n maximum = % d ”, maximum (c ,d));
14. return 0;
15. }
The names of the argument(s) can be omitted (though it is not a good idea
to do so). However the arguments data types are essential.
Hence, the prototype for the function square may also be written as void
square(int);
Or generally,
This is to say that in the factorial example, the calculation of n is expressed in form of a
previous result (condition (i) is satisfied).
/* Function definition */
1. long int factorial (int n)
2. {
3. if (n <=1) /*terminating condition*/
4. return (1);
5. else
6. return (n * factorial (n-1));
7. }
1. #include<stdio.h>
2.
1. #include <stdio.h>
2. void recurse(int i);
3. void main()
4. {
5. recurse(0);
6. }
7.
#include<stdio.h>
int func(int count);
main()
{
int a,count;
for (count=1; count< = 10; count + +)
{
a = func(count);
printf(“%d”,a);
}
return 0;
}
int func(int x)
{
int y;
y = x * x;
return(y);
}
fv = p * 1
(1 + r)n
Required:
Write a program that reads the investment amount, rate and number of
years, calculates and prints the future value.