• Function definition
• Calling function
• Global variables
• Function parameters
• Call by value
• Functions that return value
• Function prototype
• Assignment :- create a function that returns details of one cd.
/*
* double2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
return n1 * 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
printf("The doubled value is %d\n", double_it(num1));
fflush(stdin);
getchar();
}
/*
* double.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
n1 *= 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
double_it(num1);
printf("The doubled value is %d\n", num1);
fflush(stdin);
getchar();
}
/*
* average3.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average4.c
*
* Program to demonstrate the use of function prototypes
*
* by Rajesh Kulkarni
*/
#include
float average3(int n1, int n2, int n3);
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
printf("The average of 4, 3 and 5 is %f\n", average3(4, 3, 5));
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
float ave;
average3(int n1, int n2, int n3)
{
ave = (float)(n1 + n2 + n3) / 3;
}
main()
{
int num1, num2, num3;
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
average3(num1, num2, num3);
printf("The average is %f\n", ave);
fflush(stdin);
getchar();
}
/*
* average.c
*
* Program to demonstrate the use of global variables
*
* by Rajesh Kulkarni
*/
#include
int num1, num2, num3;
float ave;
input()
{
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
}
average()
{
ave = (float)(num1 + num2 + num3) / 3;
}
output()
{
printf("The average is %f\n", ave);
}
main()
{
input();
average();
output();
fflush(stdin);
getchar();
}
/*
* strlen.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int length;
strlength(char str[])
{
for (length = 0; str[length] != '\0'; length++)
; /* do nothing loop */
}
main()
{
char string[100];
printf("Please enter your first name: ");
scanf("%[^\n]", string);
strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
/*
* strlen2.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int strlength(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
; /* do nothing loop */
return i;
}
main()
{
char string[100];
int length;
printf("Please enter your first name: ");
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
printf("Please enter your last name: ");
fflush(stdin);
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
Functions
Class Test
on 7th February Thursday
5:30 to 6:30 pm
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.
Solution
#include
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 */
}
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?
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.
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.
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.
Common functions
int main (void)
{
. . .
}
More common functions
Every standard C compiler comes with a set of standard libraries.
#include
Tells the compiler you will use the standard IO library
#include
C’s standard math library functions:
sqrt, pow, sin, cos, exp, ...
isspace, ...
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.
High level programming structure
main ()
{
. . .
SetUpBoard ();
do {
redsTurn ();
blacksTurn ();
} while (gamenotover ());
}
Function definition
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
void
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
Calling a function
int main (void)
{
/* produce some output */
. . .
print_banner ();
/* produce more output */
. . .
print_banner ();
/* produce final output */
. . .
print_banner ();
}
Terminology
main () is the caller
print_banner() is the callee.
main() invokes / calls print_banner() 3 times.
print_banner() is called from main()
Function Control Flow
/* print banner line */
void print_banner (void)
{
printf(“**************\n”);
}
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
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.
Calling a function
A value-returning function is called by including it in an expression.
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.
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);
}
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.
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.
Functions
Lecture 10
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.
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.
Control and data flow
When a function is called:
(1) control transfers to the function body
(2) argument values are copied
(3) the function executes
(4) control and return value return to the point of call.
Control and data flow
int main (void)
{
double x, y, z;
y=6.0;
x = area(y/2.0);
. . .
z = area(7.88);
. . .
return (0);
}
Style notes
Put comments above a function body to specify completely what the function does, including the significance of all the parameters.
Multiple parameters
a function may have more than one parameter
arguments must match parameters in number, order and type.
Rules for using functions
Arguments must match parameters:
in number
in order
in type
A function can only return one value.
but it might contain more than one return statement.
In a function with return type T, the return expression must be of type T.
A function with return type T can be used anywhere an expression of type T can be used.
Local variables
A function can define its own local variables.
The locals have meaning only within the function.
Each execution of the function uses a new set of locals
Local variables cease to exist when the function returns
Parameters are also local.
Local variables
Defining function prototypes
Functions should be declared before they are used (invoked).
Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used.
It is a good programming style to use function prototypes.
Function prototypes
int operate (double x, double y, char op) ;
int operate (double, double, char);
void print_average (double, int);
int get_intput (void);
void print_banner (void);
Local Variables
Formal parameters and variables declared in a function are local to it.
cannot be accessed or used by other functions directly
Allocated (created) on function entry.
De-allocated (destroyed) on function return.
Formal parameters initialized by copying value of actual parameter. (“Call by value”)
Call by value
void printDouble (int x) {
printf (“Double of %d “, x);
x *= 2;
printf (“is %d\n”, x) ;
}
void main () {
int num=15;
printDouble (num);
printf (“ num = %d\n”, num);
}Functions
Functions
a group of declarations and statements that is assigned a name
effectively, a named statement block
usually has a value
a sub-program
when we write our program we always define a function named main
inside main we can call other functions
which can themselves use other functions, and so on…
Example - Square
#include
double square(double a)
{
return a*a;
}
int main(void)
{
double num;
printf("enter a number\n");
scanf("%lf",&num);
printf("square of %g is %g\n",num,square(num));
return 0;
}
Why use functions?
they can break your problem down into smaller sub-tasks
easier to solve complex problems
generalize a repeated set of instructions
we don’t have to keep writing the same thing over and over
printf and scanf are good examples…
they make a program much easier to read and maintain
Characteristics of Functions
return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …)
{
function body;
return value;
}
Return Statement
Return causes the execution of the function to terminate and returns a value to the calling function
The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)
In a function there may be any no of return statements but only one can be executed.
Return type is optional
Default return type is int
Exercise
Write a program that gets a positive integer from the user and prints all the prime numbers from 2 up to that integer.
(Use a function that returns 1 if its parameter is prime, 0 otherwise)
Solution
is_prime_func.c
The Great Void
Sometimes there’s no reason for a function to return a value
In these cases, the function return type should be ‘void’
If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified
The Great Void
Calling ‘return’ in a function returning void is not obligatory
If the function receives no parameters, the parameter list should be replaced by ‘void’ (or just nothing)
Example
void ShowHelp(void)
{
printf("This function explains what this program does…\n");
printf("Yadayadayada");
/* ... */
}
int main(void)
{
char choice;
printf("Please enter your selection: ");
scanf("%c", &choice);
if (choice==‘h’)
ShowHelp();
else if /* Program continues … */
}
Calling function: a function which is referring another function is called calling function
Called function: a function which is referenced by another function is called called function.
Function call:
Actual parameters:
Formal parameters;
Pass-by-value
Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables
A change to the value of an argument in a function body will not change the value of variables in the calling function
Example – add_one.c
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Riddle me this
#include
int factorial(int n)
{
int fact = 1;
while (n>1)
{
fact *= n;
n--;
}
return fact;
}
Scope of variables
A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name
A function cannot access variables that are declared in other functions
Example – scope.c
Call –by- Reference
Wrong way to do it
int add_one(int b)
{
a=b+1;
}
int main(void)
{
int a=34,b=1;
add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Function Declaration
Most software projects in C are composed of more than one file
We want to be able to define the function in one file, and to use it in all files
Function Declaration
For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time
the declaration contains:
Function Declaration
#include
int factorial(int a); /* Function Declaration! */
int main(void){
int num;
printf("enter a number\n");
scanf("%d", &num);
printf("%d != %d\n", num, factorial(num));
return 0;
}
int factorial(int a){
int i, b = 1;
for(i = 1; I <= a; i++)
b = b*i;
return b;
}
Function Declaration
stdio.h actually contains a large set of function declarations
The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called
The math library
A collection of mathematical functions
Need to include the header file math.h (#include
Use functions of the library, e.g.
double s,p;
s = sqrt(p);
Declared in math.h :
double sqrt (double x);
The math library
sin(x), cos(x), tan(x)
x is given in radians
asin(x), acos(x), atan(x)
log(x)
sqrt(x)
pow(x,y) – raise x to the yth power.
ceil(x), floor(x) …and more
Exercise
Write a function that uses the formula
in order to approximate . The function should accept
an argument n which determines the number of terms in
the formula. It should return the approximation of .
Write a program that gets an integer n from the user,
and approximate using n terms of the above formula.
Solution
pi.c
Exercise
Modify the previous function that approximates
. The function should accept an argument
specifying the desired accuracy, and keep
adding terms until the contribution of the next
term drops below this level.
Write a program that gets a (small) double
epsilon from the user, and approximates
within this function.
Solution
pi_eps.c
The debugger
Some programs may compile correctly, yet not produce the desirable results.
These programs are valid and correct C programs, yet not the programs we meant to write!
The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program.
The debugger’s common features
Setting breakpoints (a point where the execution stops): bring the cursor to desired line and press the palm icon or F9. A dark red dot appears near the line.
Executing a debugged run: Build->start debug->go or F5. The program will run and stop at the first breakpoint.
The debugger’s common features (cont.)
Stopping at a specific line: Bringing the cursor to the line and press ctrl+F10, or Build->start debug->go to cursor. The program will stop at that point.
Stepping to the next line – F10.
Entering a function – F11.
Seeing variable values – quickwatch and/or debug window at the bottom.
The yellow arrow indicates our whereabouts at any given moment.
No comments:
Post a Comment