1
Announcements
Lecture 12
• Assignment 3 out today
– Designs due on Friday at the
beginning
of your
recitation session
• Functional block diagram, algorithm, IPO diagram
–
IPO diagram
describes the inputs, outputs and general operations to be
performed
–
Functional block diagram
shows who calls who (functions), and data
passed back and forth (without library functions)
–
Algorithm
is a procedure (i.e. a sequence of
steps/instructions) for
solving a given problem.
Flowchart or pseudocode OK.
»
Tip
:
level of abstraction should be at least 1:10
• Exam 1 - Friday in class
– Study tip: work the sample exam, specific exercises in the
book (on Wed.), solutions for most are on BB
• Topics for today
– More on functions (passing arrays back and forth)
– Modular sorting program example
– Recursive functions
Functions – reminder
#include <stdio.h>
float max(float, float);
/* fcn prototype */
int main(void)
{
int x, y;
printf("Enter two numbers: ");
scanf("%d%d", &x, &y);
printf("The larger number is %g\n",
max(x, y)
); /* call*/
return 0;
}
float max(float a, float b)
/* definition of function */
{
if (a > b) return a;
else return b;
}
main
max
2 #s
(x,y)
the
larger
of the
2 #s
Order of events
1.
max() is called with x and y as arguments
2.
x, y are [converted] & copied into a & b
3.
The body of max is executed
4.
The return statement returns the value of
either a or b back to the call
5.
The value returned is used to output
/* average is a function that computes and returns the
average of
the values in a given (passed) integer array of given length */
double average (
int data [ ]
, int length)
{
if (length = = 0) return 0;
double sum = 0;
int i;
for (i = 0; i <
length; i++)
sum = sum + data[i];
return sum / length;
}
Passing an Array as an Argument
data
exam1scores
Array names are passed as a pointer
•
Called from your main function, e.g.
double
avg;
int exam1scores [CLASS_SIZE];
/* assume the full array gets its values somehow */
avg
= average (
exam1scores
, CLASS_SIZE);
• /* This function fills in an integer array with
random scores, each in the range from 0 to n */
void randomData (
int data [ ]
, int length, int n)
{int i;
for (i = 0; i < length; i++)
data[i] =
rand ( )
% (n + 1);
return;
}
• Called in the main for example as
randomData (
exam1scores
, CLASS_SIZE, 100);
Returning a Filled-in Array
rand( )
returns a random positive int; see pg 686[old 570]
Passing Multi-dimensional Arrays
• Only the length of the first dimension can be omitted
/* sum up the values in a n x 10 matrix of ints */
#define LEN 10
. . .
int sum_array(int a[ ] [LEN], int n)