28.1.2001sudeshna sarkar, iit kharagpur 1 functions lecture 9 28.1.2001
TRANSCRIPT
28.1.2001 Sudeshna Sarkar, IIT Kharagpur1
Functions
Lecture 928.1.2001
28.1.2001 Sudeshna Sarkar, IIT Kharagpur2
Class Test
on 7th February Thursday
5:30 to 6:30 pm
28.1.2001 Sudeshna Sarkar, IIT Kharagpur3
A Problem
Suppose we are writing a program that displays messages on the screen.
We want to display rows of =============================== to separate sections of output.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur4
Solution#include <stdio.h>
int main (void)
{
/* produce some output */
/* print banner line */
printf(“==============\n”) ;
/* produce more output */
printf(“==============\n”);
/* produce even more output */
printf(“==============\n”);
/* produce final output */
}
28.1.2001 Sudeshna Sarkar, IIT Kharagpur5
Critique
Redundant code What if we want to change the display
e.g. to print a blank line before and after each line with =’s ?
What if we want to print banner lines in some other program?
28.1.2001 Sudeshna Sarkar, IIT Kharagpur6
The Solution: Functions
Definition: A function is a named code sequence
A function can be executed by using its name as a statement or expression.
The function may have parameters - information that can be different each time the function is executed.
The function may compute and return a value.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur7
Why use functions ?
Functions provide an abstraction when writing a program - allow low-level details to be packaged.
Able to package a computation we need to perform at multiple spots within a program. Write once, use many times.
If changes are needed, they only have to be done once, in one place.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur8
Why use functions ?
Allows the programmer to create a program from smaller, simpler sub-components.
Many programs are far too large to understand all at once.
Functions give us a way to break a large program into smaller pieces
A function should perform a well-defined task.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur9
Common functions
int main (void)
{
. . .
}
Function definitionfor main()
printf (“%d + %d is %d\n”,x,y,z);
scanf (“%d%d”, &x, &y) ;
limit = sqrt ((double) num);
Function calls
28.1.2001 Sudeshna Sarkar, IIT Kharagpur10
More common functions
Every standard C compiler comes with a set of standard libraries.
#include <stdio.h> Tells the compiler you will use the standard IO library
#include <math.h> C’s standard math library functions:
sqrt, pow, sin, cos, exp, ...
isspace, ...
28.1.2001 Sudeshna Sarkar, IIT Kharagpur11
Defining your own functions
You may define your own functions in your programs
You define a function by giving its name and writing the code that is executed when the function is called.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur12
High level programming structuremain ()
{
. . .
SetUpBoard ();
do {
redsTurn ();
blacksTurn ();
} while (gamenotover ());
}
28.1.2001 Sudeshna Sarkar, IIT Kharagpur13
Function definition
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
heading comment
function name
function body(statements to be executed)A function can haveANY number of ANYkind of statements
28.1.2001 Sudeshna Sarkar, IIT Kharagpur14
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
voidvoid has two different roles in this function definition.
indicates that the functiondoes not return (have) anoutput value.
indicates that the functionhas no parameters.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur15
Calling a functionint main (void){ /* produce some output */ . . . print_banner ();
/* produce more output */ . . . print_banner (); /* produce final output */ . . . print_banner ();}
To execute the function,it is called or invokedfrom within a program or another function.
Note: A function that does not return a value can be called wherever a statement is allowed.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur16
Terminology
main () is the caller print_banner() is the callee. main() invokes / calls print_banner() 3
times. print_banner() is called from main()
28.1.2001 Sudeshna Sarkar, IIT Kharagpur17
Function Control Flow/* print banner line */void print_banner (void){
printf(“**************\n”);}
int main (void){ . . . print_banner (); . . . print_banner (); return (0);}
main (void){
print_banner ();
print_banner ();
}
print_banner {
}
print_banner {
}
28.1.2001 Sudeshna Sarkar, IIT Kharagpur18
Control Flow
All C programs Start at main () /*no matter where main()is */
Continue in top-to-bottom order, statement by statement, unless the order is changed by: function call function return if loops
28.1.2001 Sudeshna Sarkar, IIT Kharagpur19
Function Type and Value A function can return a value. Like all values in C, a function return value has a type. The function has the type of its returned value.
/* Get number from user */int get_input (void){ int num; printf (“Enter a number:”); scanf (“%d”, &num); return (num);}
function type
return statement
returned value
28.1.2001 Sudeshna Sarkar, IIT Kharagpur20
Calling a function
A value-returning function is called by including it in an expression.
int main (void){ int x, y; x = get_input() ; y = get_input() ; printf (“ %d + %d = %d\n”, x, y, x+y); return (0);}
Note : A value returning function can be used anywhere an expression of the same type can be used.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur21
return
In a value-returning function (result type is not void) return does two distinct things : 1. specify the value returned by the execution of
the function 2. terminate that execution of the function.
In a void function: return is optional at the end of the function body. return may also be used to terminate execution of
the function explicitly. No return value should appear following return.
28.1.2001 Sudeshna Sarkar, IIT Kharagpur22
void compute_and_print_itax (){
double income;scanf (“%f”, &income);if (income < 50000) {
printf (“Income tax = Nil\n”); return;}if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000);return;
}if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);return ;
}printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
Terminate function execution before reaching the end
28.1.2001 Sudeshna Sarkar, IIT Kharagpur23
Function parameters
It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
The function specifies its inputs as parameters in the function declaration.
/* Find area of a circle with radius r */double area (double r){
return (3.14159*r*r) ;}
parameter
28.1.2001 Sudeshna Sarkar, IIT Kharagpur24
Arguments
The function call must include a matching argument for each parameter.
When the function is executed, the value of the argument is substituted for the parameter.
int main (void){ . . .
double circum;. . .area1 = area(circum/2.0);. . .
}
double area (double r){
return (3.14*r*r);}
parameter passing