Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 12

Passing Arrays to Functions

Elimination of separate variables


We dont want to have a function that accepts each element
of the array as an argument E.g.
void SomeFunction(int element1, int element2,
int element3, );

Wed rather pass the entire array into the function.


For added flexibility, also pass the size of the array into the
function

Example:
/* File: frequency1.c
* Mofified by: Aniket Apte
* Modified on: 9/30/02
* SSN: xxx-xx-1234
* Section: 0203
* Email: aniket1@cs.umbc.edu
* Modified for: Discussion 5
*/

#include <stdio.h>
#include <stdlib.h>

/* the range in which we wish to obtain numbers */


#define HIGH 4
#define LOW 1

/* the number of runs we want to do */


#define LOWER 0
#define RUNS 20

void PrintResults(int freq1, int freq2, int freq3, int


freq4);

int main()
{
int num, i;
int freq1 = 0;
int freq2 = 0;
int freq3 = 0;
int freq4 = 0;

/* for loop for the number of runs */


for (i = LOWER ; i < RUNS ; i ++ ){
/* call to rand and force in range */
num = rand() % (HIGH - LOW + 1) + LOW ;

/* add to the appropriate variable */


switch (num) {
case 1:
freq1++;
break;
case 2:
freq2++;
break;
case 3:
freq3++;
break;
case 4:
freq4++;
break;
default:
printf("Oops, we messed up\n");
break;
}
}

PrintResults(freq1, freq2, freq3, freq4);


/* return no error */
return 0;
}

/*
* Function: PrintResults
* Input: The frequencies to be printed out
* Output: None
* Accepts the frequencies to be printed as a list of
* integer arguments, and prints them out
*/
void PrintResults(int freq1, int freq2, int freq3, int
freq4)
{
/* print out the results */
printf( " Frequency of 1 is %d \n", freq1);
printf( " Frequency of 2 is %d \n", freq2);
printf( " Frequency of 3 is %d \n", freq3);
printf( " Frequency of 4 is %d \n", freq4);
}
[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] gcc -Wall -ansi
frequency1.c
[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out
Frequency of 1 is 4
Frequency of 2 is 4
Frequency of 3 is 6
Frequency of 4 is 6

Problems with this technique:


Confusing to pass so many arguments to a function
What if we need to change the size of the array?
o We need to pass even more arguments into the function

1-D Arrays as Parameters


Prototype:
void PrintResults(int freq[], int size);

Remarks:
Can optionally declare the size of the array
void PrintResults(int freq[4], int size);

Name of the array is optional. So we can also declare the


function as
void PrintResults(int [], int size);
What gets passed to the function?
The address of the base of the array gets copied into the function.

There is a big difference between passing values, which we have


been doing up until now, and passing addresses.

When we pass values, a copy is made and placed into a local


variable of the function. Changes that are made to that variable
in that function do not affect the original value back in the
calling function. This is known as call by value.
When we pass an array to a function, we are really passing an
address. We are not making a copy of the array. Changes that
are made to the array by the called function change the original
array, because we are accessing its elements by using its
address. Passing an address is known as call by reference.

Example:
/* File: frequency2.c
* Mofified by: Aniket Apte
* Modified on: 9/30/02
* SSN: xxx-xx-1234
* Section: 0203
* Email: aniket1@cs.umbc.edu
*/
#include <stdio.h>
#include <stdlib.h>

/* the range in which we wish to obtain numbers */


#define HIGH 4
#define LOW 1

/* the number of runs we want to do */


#define LOWER 0
#define RUNS 20

#define NUMBERS 4

void PrintResults(int freq[], int size);


void ModifyValues(int freq[], int size);

int main()
{
int num, i;
int freq[NUMBERS] = {0, 0, 0, 0};

/* for loop for the number of runs */


for (i = LOWER ; i < RUNS ; i ++ ){
/* call to rand and force in range */
num = rand() % (HIGH - LOW + 1) + LOW ;

/* add to the appropriate variable */


freq[num 1]++;
}

PrintResults(freq, NUMBERS);
ModifyValues(freq, NUMBERS);
printf(After modifying array:\n);
PrintResults(freq, NUMBERS);

/* return no error */
return 0;
}

/*
* Function: PrintResults
* Input: The frequencies to be printed out, and size of
* array
* Output: None
* Accepts the frequencies to be printed as an array, and
* prints them out
*/
void PrintResults(int freq[], int size)
{
int i;

for(i = 0; i < size; i++) {


printf(Frequency of %d is %d\n, i + 1, freq[i]);
}
}

/*
* Function: ModifyValues
* Input: The frequencies to be modified, and size of array
* Output: None
* Accepts the frequencies to be modified as an array, and
* increments each of them by one
*/
void ModifyValues(int freq[], int size)
{
int i;

for(i = 0; i < size; i++) {


freq[i] += 1;
}
}

[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] gcc -Wall -ansi


frequency2.c
[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out
Frequency of 1 is 4
Frequency of 2 is 4
Frequency of 3 is 6
Frequency of 4 is 6
After modifying values:
Frequency of 1 is 5
Frequency of 2 is 5
Frequency of 3 is 7
Frequency of 4 is 7

Multidimensional Arrays as Parameters


2-D array
void Print2DArray(int a[][5], int rows,
int cols);

3-D array
void Print3DArray(int a[][5][5], int x,
int y, int z);

We have to declare the size of all but the leftmost dimension.

Example:
/*
* File: matrixadd.c
* Author: Aniket Apte
* Date: 9/30/02
* Section: 0203
* SSN: 123-45-6789
* Email: aniket1@cs.umbc.edu
*/
#include <stdio.h>

#define X 3
#define Y 3

void CalcSum(int total[][Y], int term1[][Y],


int term2[][Y], int x, int y);

void PrintMatrix(int term[][Y], int x, int y);

int main()
{
int term1[X][Y] = { {0, 1, 4},
{-4, 3, 10},
{0, 0, 4} };

int term2[X][Y] = { {5, 3, -4},


{14, 0, 8},
{0, -10, 8} };
int total[X][Y];

/* calculate sum */
CalcSum(total, term1, term2, X, Y);

/* Print them out */


printf(Matrix term1:\n);
PrintMatrix(term1, X, Y);
printf(Matrix term2:\n);
PrintMatrix(term2, X, Y);
printf(Matrix total:\n);
PrintMatrix(total, X, Y);
return 1;
}

/*
* Function: CalcSum
* Input: 3 2-D matrices, and their sizes
* Output: None
* Adds the matrices term1 and term2 and puts results in
* total
*/
void CalcSum(int total[][Y], int term1[][Y],
int term2[][Y], int x, int y)
{
int i, j;

for(i = 0; i < x; i++) {


for(j = 0; j < y; j++) {
total[i][j] = term1[i][j] + term2[i][j];
}
}
}

/*
* Function: PrintMatrix
* Input: 2-D matrix and its size
* Output: None
* Prints a 2D matrix.
*/
void PrintMatrix(int term[][Y], int x, int y)
{
int i, j;

for(i = 0; i < x; I++) {


for(j = 0; j < y; j++) {
printf(%2d , term[i][j]);
}
printf(\n);
}
printf(\n);
}

[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] gcc -Wall -ansi


matrixadd.c
[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out
Matrix term1:
0 1 4
-4 3 10
0 0 4

Matrix term2:
5 3 -4
14 0 8
0 -10 8

Matrix total:
5 4 0
10 3 18
0 -10 12
Sorting and Searching
Importance of sorting
Fundamental part of many tasks
Required for the efficient performance of other tasks (e.g.
searching a phonebook)

Algorithms
Many algorithms out there with varying degrees of complexity,
speed etc.

Selection Sort
Insertion Sort
Bubble Sort

Analysis of Algorithms
How fast is it?
How much memory does it need?

Selection Sort
Finds the smallest value in the unsorted portion of array
Moves this value to the current position

Insertion Sort
Sorting while playing cards.
Extract a card, shift the remaining cards, and then insert the
extracted card in the correct place.
Repeated until all the cards are in the correct sequence.

Linear Search
Simply go through the array element by element

Binary Search
Works on a sorted array
Compare the middle element of array with the search key
If it matches, the subscript is returned
Otherwise, the problem is reduced to searching one half of
the array
If the key is greater than the middle element, restrict search
to second half array
Otherwise restrict search to first half

UNIX Redirection
Output Redirection
Output of a UNIX command goes to standard output i.e. the
terminal screen E.g.
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] date
Tue Oct 1 01:39:50 EDT 2002

We can redirect (i.e. save) the output into a file by using the >
operator after the command. E.g.
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] date > date.txt
will save the output of the date command into the file
date.txt. If we open the file in an editor, we can see the
output.
The > redirection operator will overwrite into the file
specified.
If we want to append to a file, we use the >> operator. E.g.
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] date > date.txt
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] cat date.txt
Tue Oct 1 01:46:19 EDT 2002
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] date >>
date.txt
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] cat date.txt
Tue Oct 1 01:46:19 EDT 2002
Tue Oct 1 01:46:29 EDT 2002

Input Redirection
Input to a UNIX command comes from standard input i.e.
the terminal screen.
We can use the < operator and specify a file that becomes the
standard input to the command.

Example:
/*
* File: stdinput.c
* Author: Aniket Apte
* Date: 9/30/02
* Section: 203
* SSN: 123-45-6789
* Email: aniket1@cs.umbc.edu
*
* Demonstrates redirection of standard input.
*/

#include <stdio.h>
int main()
{
int n1, n2;
printf(Enter n1: );
scanf(%d, &n1);
printf(Enter n2: );
scanf(%d, &n2);

printf(%d + %d = %d\n, n1, n2, n1 + n2);


return 1;
}

[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] gcc -Wall -ansi


redir.c
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out
Enter n1: 34 Input taken from user
Enter n2: 56 i.e. standard input
34 + 56 = 90

Now redirect input from file in.txt


[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] cat in.txt
45 233
[linux3:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out <
in.txt
Enter n1: Enter n2: 45 + 233 = 278

Input from the redirected file does not appear on the screen

We can combine both input and output redirection. E.g. take


input from in.txt and redirect output to out.txt
[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] ./a.out <
in.txt > out.txt

[linux1:/afs/umbc.edu/users/a/n/aniket1/home/201] cat out.txt


Enter n1: Enter n2: 45 + 233 = 278

You might also like