0% found this document useful (0 votes)
10 views7 pages

5 Functions

The document discusses structured programming and function-based programming. Structured programming uses top-down design and breaking problems into smaller pieces called modules. Functions are the main building blocks and allow breaking programs into smaller and more manageable parts. Library functions provide common operations and functions can call other functions to perform tasks.

Uploaded by

Hussein El Beqai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

5 Functions

The document discusses structured programming and function-based programming. Structured programming uses top-down design and breaking problems into smaller pieces called modules. Functions are the main building blocks and allow breaking programs into smaller and more manageable parts. Library functions provide common operations and functions can call other functions to perform tasks.

Uploaded by

Hussein El Beqai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Introduction

Structured Programming is a problem-solving strategy and a


programming methodology that includes the following two
guidelines:
Functions and Structured
Programming • The flow of control in a program should be as simple as
possible.
• The construction of a program should embody top-down
design.

SPRING 2003 COP3223 1 SPRING 2003 COP3223 2

Top-down Design Program Modules in C


• Functions
Top-down design, also referred to as stepwise refinement, – Modules in C
or divide and conquer, consists of repeatedly decomposing – Programs combine user-defined functions with library functions
a problem into smaller problems. In other words: • C standard library has a wide variety of functions
• Function calls
– Construct a program from smaller pieces or components
– Invoking functions
• These smaller pieces are called modules
• Provide function name and arguments (data)
• Function performs operations or manipulations
– Each piece more manageable than the original program • Function returns results
– Function call analogy:
• Boss asks worker to complete task
– Worker gets information, does task, returns result
– Information hiding: boss does not know details

SPRING 2003 COP3223 3 SPRING 2003 COP3223 4

1
Math Library Functions Available Mathematical functions
Function Header Description
• Math library functions
– perform common mathematical calculations int abs(int num) Returns the absolute value of an integer
element.
– #include <math.h>
double fabs (double num) Returns the absolute value of a double
• Format for calling functions precision element.
double pow(double x,double y) Returns x raised to the power of y.
– FunctionName ( argument );
• If multiple arguments, use comma-separated list int rand(void ) returns a random number
– y = sqrt( 900.0 );
double sin(double angle) Returns the sine of an angle the angle
• Calls function sqrt, which returns the square root of its should be in Radius.
argument
• All math functions return data type double double cos(double angle) Returns the cosine of an angle the angle
should be in Radius.
– Arguments may be constants, variables, or expressions
double sqrt(double num) Returns the sign the square root.

SPRING 2003 COP3223 5 SPRING 2003 COP3223 6

Using Library Functions Functions


• Calculate the square root of (x1 - x2)2 + (y1 - y2)2 Ø We have already written our own functions and used
a = x1 – x2; library functions:
b = y1 – y2; – main is a function that must exist in every C program.
c = pow(a,2) + pow(b , 2);
– printf, scanf are library functions which we have
d = sqrt(d );
already used in our programs.
OR just:
d=sqrt( pow( (x1-x2), 2) + pow( (y1-y2), 2)); Ø We need to do two things with functions:
– Create Functions
• What is the value of: – Call Functions (Function invocation)
sqrt(floor(fabs(-16.8)))

SPRING 2003 COP3223 7 SPRING 2003 COP3223 8

2
Function Definition function
Example
prototype
A function definition has the following form: • Let’s define a function to compute the cube of a number:
int cube ( int num ) {
return_type function name (formal parameter list) int result;
{
declarations result = num * num * num;
statements return result;
} }
return_type - the type of value returned by the function
• This function can be called as:
• void – indicates that the function returns nothing.
function name – any valid identifier
formal parameter list – comma separated list, describes the number n = cube(5);
and types of the arguments that get passed into the function
when its invoked.
SPRING 2003 COP3223 9 SPRING 2003 COP3223 10

Function Invocation #include <stdio.h>

void prn_message (void); /* function prototype */

• A program is made up of one or more Main int main (void)


functions, one of them being main( ). {
Func 1
prn_message ( ); /* function invocation */
• When a program encounters a function, return 0;
the function is called or invoked. }
• After the function does its work, Func 2
program control is passed back to the void prn_message(void) /* function definition */
{
calling environment, where program
printf(“A message for you: ”);
execution continues. printf(“Have a nice day!\n”);
}

SPRING 2003 COP3223 11 SPRING 2003 COP3223 12

3
/* An example demonstrating local variables */
#include <stdio.h> #include < stdio.h>
void print_message (int k); /*function prototype */
int main (void) void func1 (void) ; 5
{
int n;
5
int main (void)
printf(“There is a message for you.\n”); { 6
printf(“How many times do you want to see it? ”); int i = 5 ; 5
scanf(“%d”, &n); printf(“%d \n”, i);
print_message(n); func1( );
return 0; printf(“%d \n”,i);
}
return 0;
void print_message (int k) /* function definition */ }
{
int i; void func1 (void)
{
printf(“\nHere is the message.\n”); int i = 5;
for (i=0; i < k; ++i)
printf(“Have a nice day!\n”); printf(“%d \n ”, i);
} i++;
printf(“%d \n ”, i);
}
SPRING 2003 COP3223 13 SPRING 2003 COP3223 14

The return statement Examples


• When a return statement is executed, program control is
immediately passed back to the calling environment. return ;
• If an expression follows the keyword return, the value of
the expression is returned to the calling environment as return 77;
well.
• A return statement has one of the following two forms: return ++a;
return ;
return expression; return (a+b+c);

SPRING 2003 COP3223 15 SPRING 2003 COP3223 16

4
#include < stdio.h>
int min (int a, int b); Parameters
int main (void)
• A function can have zero or more parameters.
{ • In declaration header:
int j, k, m;
int f (int x, double y, char c);
printf(“Input two integers: ”);
scanf(“%d %d”, &j, &k);
the formal parameter list
m = min(j,k);
(parameter variables and their
printf(“ \nThe minimum is %d.\ n”, m);
types are declared here)
return 0 ;
}
int min(int a, int b) Input two integers: 5 6
The minimum is 5. • In function calling:
{
if (a < b) value = f(age, score, initial);
Input two integers: 11 3
return a; The mininum is 3.
else
return b; actual parameter list (cannot
} tell what their type are from
here)
SPRING 2003 COP3223 17 SPRING 2003 COP3223 18

Rules for Parameter Lists


Invocation and Call-by-Value
• The number of parameters in the actual and formal
parameter lists must be consistent • Each argument is evaluated, and its value is used locally in
• Parameter association is positional: the first actual place of the corresponding formal parameter.
parameter matches the first formal parameter, the second • If a variable is passed to a function, the stored value of that
matches the second, and so on variable in the calling environment will not be changed.
• Actual parameters and formal parameters must be of • In C, all calls are call-by-value.
compatible data types
• Actual parameters may be a variable, constant, any
expression matching the type of the corresponding formal
parameter

SPRING 2003 COP3223 19 SPRING 2003 COP3223 20

5
1 /* Finding the maximum of three integers */
2
#include <stdio.h> 3 #include <stdio.h>
int compute_sum (int n) 4
int compute_sum (int n); 5 int maximum( int, int, int ); /* function prototype */
{ 6
int sum; 7 int main()
int main (void) 8 {
{ 9 int a, b, c;
sum = 0; 10
int n, sum; 11 printf( "Enter three integers: " );
12 scanf( "%d%d%d", &a, &b, &c );
for ( ; n > 0; --n) 13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
n = 3; 14
sum += n; 15 return 0;
printf(“%d\n”, n); 16 }
printf(“%d\n”, n); 17
return sum;
sum=compute_sum(n); 18 /* Function maximum definition */
} 19 int maximum( int x, int y, int z )
printf(“%d\n”,n); 20 {
printf(“%d\n”, sum); 21 int max = x;
22
return 0; 23 if ( y > max )
} 24 max = y;
3 25
26 if ( z > max )
0 27 max = z;
3 28
29 return max;
6 30 }
Enter three integers: 22 85 17
SPRING 2003 COP3223 21 SPRING
Maximum is: 85 2003 COP3223 22

Alternative styles for function definition order


Function Prototypes #include <stdio.h > #include <stdio.h >
int max ( int a, int b )
• Function prototype int max(int ,int ); {
– Function name int min(int ,int ); ...
}
– Parameters – what the function takes in int main( void )
– Return type – data type function returns (default int) { int min ( int a, int b )
min(x,y); {
• Used to validate functions max(u,v); ...
– Prototype only needed if function definition comes after use ... }
}
in program
int max ( int a, int b ) int main( void )
• The function with the prototype { {
int maximum( int, int, int ); ... ...
} min(x,y );
• Takes in 3 ints int min ( int a, int b ) max(u,v);
• Returns an int { ...
... }
}
SPRING 2003 COP3223 23 SPRING 2003 COP3223 24

6
Correct the errors in the following Correct the errors in the following
program segments program segments
1. int g (void) { 3. void f (float a); {
printf (“Inside function g \n”);
float a;
printf (“%f”, a);
int h(void) {
}
printf(“Inside function h \n”);
}
} 4. void product (void) {
int a, b, c, result;
2. int sum(int x, int y) { printf(“Enter 3 integers: ”);
int result; scanf(“%d %d %d”, &a, &b, &c);
result = x + y; result = a * b * c;
} printf(“Result is %d\n”, result);
return result;
}

SPRING 2003 COP3223 25 SPRING 2003 COP3223 26

You might also like