C-Functions: Dr. D.H. Kisanga
C-Functions: Dr. D.H. Kisanga
May 2020
Function
is a group of statements that together perform a task.
Every C program has at least one function, which is main()
A function in C plays the same role that functions, subroutines,
and procedures play in other languages, although the details might
differ.
The only function that does not need a prototype is main() since it
is predefined by the C language.
Function call (Calling a Function)
To use a function, you will have to call that function to perform
the defined task.
When a function is called, program control is transferred to the
called function. A called function performs a defined task and
there after returns the program control back to the calling
function (or main program).
While calling a function, there are two ways that arguments can
be passed to a function:
#include<stdio.h>
#include<conio.h>
float convert (void);
float dollar; /* This is a global variable */
main ()
{
float TSH;
TSH = convert();
printf ("US$ %f = Tshs %f", dollar, TSH);
getch();
}
Eg 7. C-mathematics functions. All the math functions require that
the header file math.h be included in a program.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float num;
printf("\n\n Enter a number \n");
scanf("%f", &num);
/* The fabs() function returns the absolute value of a number*/
printf("\n Absolute value of %f is %1.1f", num, fabs(num));
/* The pow() function returns base raised to the exponent power. Where base>0 and exp>=o */
printf("\n The power of %f raised to 5 is %1.1f", num, pow(num,5));
getch();
}
Homework
Q1. Modify the program in Eg6 using a for loop that will request a
user to enter amount in USD from the keyboard and display the
conversion to the monitor screen. Use 5 iterations.
Questions