Вы находитесь на странице: 1из 31

Functions

10

Introduction to Programming
Top-Down Design

• Also called “Divide and Conquer”

• A problem solving method in which you


first break a problem up into its major
sub-problems to derive a solution to the
original problem.

Introduction to Programming
Functions in C

• Execution starts and ends with the


main function

• This function can call other functions to


do special tasks
• Ex. Calling printf and scanf functions

Introduction to Programming
Functions in C

• Purpose: to receive 0 or more pieces of


data, operate on them, and return at
most one piece of data.

input function output

Introduction to Programming
Why use function subprograms?
• Top-Down Design
– easier and simpler
– Subprograms make it easier to divide
programming tasks

• Reuse of Code
– Functions can be executed more than
once
– Easier to alter code

Introduction to Programming
Why use function subprograms?
• Procedural abstraction
– Procedures – functions in C
– A programming technique in which
we use function sub-programs to
allow us to remove from the main
function the code that provides
detailed solution to a sub-problem

Introduction to Programming
Why use function subprograms?
• Protection of Data
– Centers around the concept of
local data – data available only to the
function wherein it is declared and only
when the function is executing
Note:
When the function is done, data is gone

Introduction to Programming
Function Declaration

• Done with a function prototype


statement
• Placed after the preprocessor directives
and before the main function
• Syntax:
return_type function_name (formal parameter list);

Introduction to Programming
Function Definition

• Contains the code for the detailed


solution to complete a function’s task
• Syntax

return_type function_name (formal parameter list)


{
/* local declarations */
/* executable statements */
}

Introduction to Programming
Function Header

• Formal parameter list – a list that


declares the variables that will contain
the data received by the function
• Void – used if there are no parameters
• You may omit the void and write it as ()

Introduction to Programming
Function Body

• Contains the local variable declarations


and executable statements for the
function
• It may or not have a return statement
(omitted in void functions)

Introduction to Programming
Function Call

• Using the function


• Syntax
function_name (actual parameter list)
Formal parameters – variables that are
declared in the function header.
Actual parameters – expressions in the
function call

Introduction to Programming
Function Call

• Void functions
– functions that don’t return a value
– Cannot be part of an expression
– Can only be used as a stand-alone
statement
• All other functions return a value
– Can be used either a part of an
expression or a stand-alone statement

Introduction to Programming
#include <stdio.h>

void prn_message(void);

int main()
{
prn_message();
return 0;
}

void prn_message(void)
{
printf("\nMessage for you: ");
printf("Have a nice day! \n");
}

Introduction to Programming
#include <stdio.h>

void prn_message(int k)
{
int i;

printf("Message for you:\n");


for(i=0; i<k; ++i)
printf(" Have a nice day!\n);
}

int main()
{
int n;
printf("Input a small positive integer: ");
scanf("%d",&n);
prn_message(n);

return 0;
}

Introduction to Programming
The Rules

• A function may accept as many


parameters as it needs, or no
parameters
• A function may return either one or no
values
• Variable declared inside a function are
only available to that function, unless
explicitly passed to another function

Introduction to Programming
Writing a Function - Example
int print_table(double start, double end,
double step)
{
double d;
int lines = 1;
printf(“Celcius\tFarenheit\n”);
for(d =start; d <=end; d+=step, lines++)
printf(“%.1lf\t%.1lf\n”,d, d*1.8+32);
return lines;
}

Introduction to Programming
Writing a Function - Example
#include <stdio.h>
int print_table(double, double, double);
int main()
{
int how_many;
double end = 100.0;

how_many = print_table(1.0, end, 3);


print_table(end, 200, 15);
return 0;
}
Introduction to Programming
Passing of Parameters

• Call by value
– Transfers only the value
– Any changes made will not be
reflected after the function terminates
• Call by reference
– Pointer to the actual parameter
– Any changes made will remain after
the function terminates

Introduction to Programming
Scope

• Refers to the region of a program where


a particular meaning of a name
(identifier) is visible or can be
referenced.
• It pertains to any identifier or object
that can be defined, such as a variable
or a function prototype statement.

Introduction to Programming
Scope

2 Concepts to consider
• Block- one or more statements
enclosed in a set of curly brackets
• Global area – consists of statements
that are outside the functions
Note: an object’s scope extends from where it is
declared until the end of its block or functions.

Introduction to Programming
Scope
• The following code will NOT compile:
#include <stdio.h>

int main()
{
{
int seventy_eight = 78;
printf("seventy_eight = %d", seventy_eight);
}

printf("\nseventy_eight = %d\n", seventy_eight);


}

• Not because there are braces but because


seventy_eight's declaration is not visible
outside the inner block
Introduction to Programming
Scope

• Global scope – any object defined in


the global area of a program is visible
from its definition/declaration until the
end of the program
• Local scope – any object defined within
a block and is visible from the point of
declaration until the end of the block.
Outside the block they are not visible.

Introduction to Programming
Scope Rules
• 1. An identifier may only be used within the
function in which it is declared.
– The same identifier may be reused on a
different block or scope.
– Declaring two variables with the same identifier
within the same block is prohibited
• 2. In case that when an identifier is declared more
than once within the same program, an identifier
reference always refers to the definition in the
inner most block defining the identifier.

Introduction to Programming
Variables

• Global variables – variables that may


be used all throughout the program

• Local variables – variables defined


within the function, available only
during function execution.

Introduction to Programming
Scope Rules
#include <stdio.h>

int num1 = 5; /*Global variable*/

int main()
{
/* Local variables*/
int num1 = 3, num2 = 4;
Output:
if (num1 < num2){
int num2 = 1; /*num2 redeclared*/ Labas!
Outside num2 = 4;
if(num1 < num2) {
printf("Pasok!\n");
}

else printf("Labas!\n");
}

printf("Outside num2 = %d\n",num2);


Introduction to Programming
}
Scope Rules
• The following code will NOT compile:
#include <stdio.h>

int main()
{
int num1 = 3, num2 = 4;
int num2 = 1; /*num2 redeclared*/

if (num1 < num2){


if(num1 < num2) {
printf("Pasok!\n");
}

else printf("Labas!\n");
}

printf("Outside num2 = %d\n",num2);


}
Introduction to Programming
Standard Mathematical
Functions
• As an example of calculation, consider
the calculation of the roots of a
quadratic equation: ax2 + bx + c = 0
• We can use the square root function of
C sqrt() defined in math.h
• To use this function, the include
statement must appear at the head of
the program:
#include<math.h>

Introduction to Programming
Standard Mathematical
Functions
...
float a, b, c;
float d, r1, r2;
printf(“Enter 3 numbers: “);
scanf(“%f %f %f”, &a, &b, &c);

d = (b*b) – (4.0 * a * c);


r1 = (-b + sqrt(d))/(2.0 * a);
r2 = (-b - sqrt(d))/(2.0 * a);
... Introduction to Programming
Example: Roots of a Quadratic

• We first check if both roots are non-imaginary


by finding the discriminant

...
d = (b*b) – (4.0 * a * c);
if(d< 0)
printf(“Imaginary roots”);
else{
r1 = (-b + sqrt(d))/(2.0 * a);
r2 = (-b - sqrt(d))/(2.0 * a);
printf(“%f %f”,r1,r2);
}
... Introduction to Programming
Standard Mathematical
Functions
cos(x) Cosine of the angle x, expressed in
radians
sin(x) Sine of the angle x, expressed in
radians
tan(x) tangent of the angle x, expressed in
radians
abs(x) The absolute value of x, sometimes
written as |x|
log(x) Natural logarithm of x ( to the base e)

pow(x,y) x raised to the power of y

Introduction to Programming

Вам также может понравиться