You are on page 1of 7

Birla Institute of Technology & Science, Pilani

Second Semester 2015-2016, Computer Programming [CS F111]


Week #8
Tutorial Sheet #1 Date:___/_____/________
Name: ______________ _____________ID: ______________________ Lec Sec/Lab
Sec:______/_____

Section 1 Passing arrays to a function


Important concepts to recall :
1) A pointer is a variable that stores the address of another variable.
2) The array name is in fact a pointer which contains the address of the element at
index 0.
3) A function can return at most one thing. Returning multiple entities can be
indirectly accomplished using pointers.
Example 1 : Write a function to compute the minimum value of an array of floating
point numbers.
Pay attention to what the inputs to the function must be.
#include<stdio.h>
float computeMinimum(float arr[],int size);
int main()
{
float a[] = {8.9,7.75,14,16,5.7,10.05,23.57};
int arraySize = 7;
//An array initialized within main and array size is known before hand.
//Here it is hard coded, in practice large arrays are usually read from one or
more files.
float minimumValue = computeMinimum(a,arraySize);
return 0;
}
//A function to compute the minimum value of an array
//Inputs : arr : The array
//
size : The number of elements in the array
//Output : Minimum value
float computeMinimum(float arr[],int size)
{
//Check whether array has at least one element
//If not we are returning a single value -1.
//Generally a value which cannot be a legitimate value is returned. Here to avoid
the code from becoming long and cumbersome, we are returning -1. Note that -1
could be a legitimate minimum value, the only way to distinguish in our case is via
the message Array size cannot be negative or 0.
if(size <= 0)
{
printf("Array size cannot be negative or 0. Returning.\n");
return -1;
}
float minimumValue = arr[0];
int minIndex = 0;
int i = 0;
for(i=0;i<size;i++)
{

if(arr[i] < minimumValue)


{
minimumValue = arr[i];
minIndex = i;
}
}
printf("Minimum value of array = %f, occurs at index
%d\n",minimumValue,minIndex);
return minimumValue;
}

Note : There are two variables called minimumValue, one in main and another
within the function
computeMinimum. Although they have the same name, they are different variables
within different scopes. One is local to main and another is local to the function
computeMinimum.
Recall : scope of variables covered in previous sessions.
Question : Why do we need to pass the size of the array to the function
computeMinimum, is it not enough to pass the array alone?
Answer : No explicit array bounds checking in C. Size is not encoded when the
array is passed. Recall that the array name is a pointer, i.e. when an array is
passed, only the start address is passed.
Question : Is it possible to return both the minimum value and index?
Answer : A function can return at most one thing. Returning multiple
entities can be indirectly accomplished using pointers. If it is necessary to return
both, one way is to create a new struct which contains both these entities and
return a pointer to that struct. structs will be covered in later classes.
Example 2 : Implement selection sort using functions
/*Sorting Elements of an array in ascending order using insertion sort algorithm and
a function*/
#define MAX_SIZE 100
#include<stdio.h>
void selectionSort(int data[],int numElements); //Function declaration
int main()
{
int data[MAX_SIZE],numElements,i;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&numElements);
printf("Enter elements: ");

for(i=0;i<numElements;i++)
{
scanf("%d",&data[i]);
}
selectionSort(data,numElements); //Function call
printf("In ascending order: ");
for(i=0; i<numElements; i++)
printf("%d\t",data[i]);
return 0;
}
//Function implementing selection sort.
void selectionSort(int arr[],int numElements)
{
int i,j,temp;
for(i=0;i<numElements;i++)
{
for(j=i+1;j<numElements;j++)
{
if(arr[i]>arr[j]) //swap values of arr[i] and arr[j]
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
Question : Will the function sort only a copy of the array (like in the swap
program), what needs to be done to ensure the original array created in main is
sorted?

Answer :
Arrays are in fact pointers. Thus when an array is passed to a function
(the array named data created in main), the pointer corresponding to the array
location (specifically the address of data[0]) is passed. Since the mechanism was
pass by pointers and not pass by value, the values corresponding memory
locations in the original array itself are changed.
Exercise :
Implement insertion sort and bubble sort. First
modularize the problem into separate functions by identifying
arguments and return types. Now implement any one sorting
technique.

Section 2 Passing arrays to and returning arrays from a function


Example 3 : Consider two arrays: x-coor[] and y-coor[]. The ith location of the two
arrays stores the x and y coordinates of a point. For example, x-coor[4] and ycoor[4] stores the x and y coordinates of fourth point.
a) Pass these two arrays to a function which prints the quadrant in which each
point lies.
Emphasis is on passing array to a function.
b) Pass these two arrays to a function. The function stores the quadrant in which
each point lies in another array (which is also passed to the function). The
quadrant is then printed in the main function.
Question : In addition to the arrays, is it necessary to pass the number of points
as argument to the
functions?
Hint : In C there is no explicit array bounds checking and size of array is not
encoded when passing array.
#include<stdio.h>
//Description : Prints quadrants within the function itself
void findAndPrintQuadrants(float x[],float y[],int N);
//Stores the result in another array (also passed to the function)
void getQuadrants(float x[],float y[],int quadrants[],int N);
int main()
{
int numPoints = 10;
int i =0;
//The x and y coordinates of the points are stored in two separate arrays x
and y respectively.
//Note : there is no explicit array size or bounds checking in C
float x[] = {4.896769,3.327884,2.279168,-2.297895,-4.782233,
-3.759458,9.117635,-4.036853 -6.422286,3.823252};
float
y[]
={-7.086525,6.997422,-3.515955,6.181462,-7.618957,
-9.985152,9.494849,7.326179,5.786673,6.878022};
//Generally better to allocate arrays using constants and fixed numbers,
//the following is possible also.
int quadrants[numPoints];
//printf("Size of array = %ld\n",sizeof(quadrants));
//Find and print quadrants by calling a function
printf("++++++++++++++++++++++\n");
printf("Computing and printing quadrant in a function\n");
printf("++++++++++++++++++++++\n");

findAndPrintQuadrants(x,y,numPoints);
printf("++++++++++++++++++++++\n");
printf("Computing via function and printing in main\n");
printf("++++++++++++++++++++++\n");
//Get quadrants of the points via a function
getQuadrants(x,y,quadrants,numPoints);
for(i=0;i < numPoints;i++)
{
printf("%d : (%f,%f) ",i,x[i],y[i]);
switch(quadrants[i])
{
case 1 :
printf("First quadrant\n");
break;
case 2 :
printf("Second quadrant\n");
break;
case 3 :
printf("Third quadrant\n");
break;
case 4 :
printf("Fourth quadrant\n");
break;
default :
printf("Unknown quadrant\n");
}
}
return 0;
}
//A function which takes as inputs two arrays which contain the x and y
coordinates and
//prints the quadrant to which the point belongs to.
void findAndPrintQuadrants(float x[],float y[],int N) //N = number of points
{
int i=0;
if(N <= 0)
{
printf("Number of points must be a positive integer\n");
return;
}
for(i = 0;i < N;i++)
{
if(x[i] >= 0 && y[i] >= 0)
printf("%d : (%f,%f) First Quadrant\n",i,x[i],y[i]);
else if(x[i] < 0 && y[i] >= 0)
printf("%d : (%f,%f) Second Quadrant\n",i,x[i],y[i]);
else if(x[i] < 0 && y[i] < 0)
printf("%d : (%f,%f) Third Quadrant\n",i,x[i],y[i]);
else //if(x[i] >= 0 && y[i] < 0)
printf("%d : (%f,%f) Fourth quadrant\n",i,x[i],y[i]);
}
}

//A function which takes as inputs two arrays which contain the x and y
coordinates and
//computes the quadrants to which the points belong to. The result is stored in
another array
//which is also passed as input to the function.
void getQuadrants(float x[],float y[],int quadrants[],int N)
{
int i=0;
if(N <= 0)
{
printf("Number of points must be a positive integer\n");
return;
}
for(i = 0;i < N;i++)
{
if(x[i] >= 0 && y[i] >= 0)
quadrants[i] = 1;
else if(x[i] < 0 && y[i] >= 0)
quadrants[i] = 2;
else if(x[i] < 0 && y[i] < 0)
quadrants[i] = 3;
else //if(x[i] >= 0 && y[i] < 0)
quadrants[i] = 4;
}
}

Exercise : Modularize the following program into multiple functions. Consider a list
of prices of books represented as one dimensional array. Traverse the list and
modify the prices according to the following conditions:
(i) if price > 250, offer discount of 10%. Update the price with respect to
discount.
(ii) if price > 500, offer discount of 25%. Update the price w.r.t discount.
Modularize it into following functions.
(i) readList(): Populate prices of the items.
(ii) printList(): Prints the price list.
(iii) modifyList(): Modify the prices in the list according to the conditions given
above.
Identify input arguments and return types for all the functions. Also write main
function where the functions are called.