Functions and Arrays
Functions and Arrays
A function is a subprogram that does a particular task. Basically, a function is used to encapsulate a set of
operations and return information to the main function or calling routine. Encapsulation is detail, information
or data hiding.
Once the function is written, we are only concerned with what it does i.e. what data it requires and what output
it produces. The details (how) the function works need not to be known.
There are two types of functions in C: -
i) Built-in functions
ii) User-defined functions
i) Built-in functions:
These are functions programmed and stored in C standard library, so that there can be called through any
program. There are used to perform operations frequently used by many programmers in their programs.
For instance, the math library functions are sqrt(x), exp(x), log(x), sin(x) and cos(x).
Example:
Write a program to find the square root of any integer number
#include <stdio.h>
#include<math.h>
#include <stdlib.h>
int main (void)
{
int number;
float square_root;
printf("Enter an integer number\n");
scanf("%d", &number);
square_root=sqrt(number);
printf("The square root of % d is %f\n", number, square_root);
return 0;
} /* end of main function*/
Header Files
Each standard library function has a corresponding header file containing the function prototypes for all
functions in that library. The following are some of the of the header files in C:
1). stdio.h :- This is a header file that contains function prototypes for the standard input and output
functions e.g. printf(), scanf(), getch() etc.
2). math.h :- This is a header file that contains function prototypes for mathematical functions e.g. pow(),
sqrt(), sin(), log() etc
3). string.h :- This is a header file that contains function prototypes for string processing functions e.g.
strcpy(), etc.
4). ctype :- This is a header file that contains function prototypes for functions which can test characters
for certain properties and can be used to convert lower case letters to uppercase and vice versa
5). conio.h :- This is a header file that contains function prototypes that enables for formatting of the
output
6). stdlib.h :- This is a header file that contains function prototypes for functions that convert numbers to
text, text to numbers and other utility functions.
Basic Format:
return_data_type function_name(data_type parameter1, data_type parameter2,….)
{
Statement 1;
Statement 2;
…………..
………….
}
The parameter list may be void in which case there are no parameters to the function. The brackets may be left
empty in this case.
Any function that does not have a return type void must contain a return statement as the last statement in the
function
Function Prototype:
A function prototype informs the compiler of the type of data returned by the function, the number of
parameters the function expects to receive, the type of parameters and the order in which the parameters are
expected.
Format:
return_type function_name (list of parameters);
The function prototypes are used when a call to the function is made before the compiler has seen the
declarator. This can occur when using a large program consisting of more than one separately compiled source
file
Calling Functions:
Functions are called (made to execute) by their names, followed by appropriate arguments.
For example: A function called add, which takes no arguments and returns no values, would be called as
follows: -
add ();
A function, which takes an integer argument, might be called as follows (either a literal number or a variable)
add (20); or add (n);
i) Passing by Value: When an argument is passed by value, a copy of the argument’s value is made and
passed to the called function. Changes to the copy do not affect the original variables values in the
caller. This prevents accidental side affects that greatly hinder the development of correct and reliable
software systems.
ii) Passing by Reference: In pass by reference the actual variable rather than a copy is passed to the called
function. The advantage is that it can allow more than one value to be derived from the function, unlike
pass by value that returns only one value from the called function. Passing arguments by reference is
only possible with use of pointers.
Scope of Variables:
Scope refers to the visibility of variables i.e. the section of the program where a variable may be accessed or
used. The following are various variable scopes:
i). Local Variables: These are variables that exist only inside the specific function that creates them. They are
unknown to other functions in the program and they cease to exist once the function is completed. They are
recreated each time the function is executed.
ii). Global Variables: These are variables that are used throughout the whole program. They are available to all
functions in the program, and are not recreated if the function is recalled. However they take up more
memory.
Recursive Functions
It refers to the functions that call themselves.
Example
Write a program that uses a recursive function to find the factorial of a number
#include <stdio.h>
/*ANSI prototype*/
int factorial (int);
/*The factorial function*/
ARRAYS
This is a sequence of a number of variables of the same data type, addressed by a single name. The selection of
a single specific variable from the sequence is done by an index. e.g. if number is the name of the array,
number[0] would address the first element, number[1] the second element etc.
That means that, for example, we can store 5 values of type int without having to declare 5 different variables
each one with a different identifier. Instead of that, using an array we can store 5 different values of the same
type, with a unique identifier.
For example, an array to contain 5 integer values of type int called number could be represented this way:
number
Where each blank panel represents an element of the array, that in this case are integer values of type int. These
are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length
Array Declaration:
Arrays are declared just like any variable with a subscripted number given within the square brackets. By
declaring an array the specified number of locations are fixed in the memory.
Syntax
dataType ArrayName[n];
Where n is a positive literal number
Initializing Arrays
When an array has been declared, it is possible to assign initial values to each one of its elements using curly
brackets { }.
For example:
number
The number of elements in the array that has been initialized within the curly brackets { } and must match the
length of elements that was declared in the array.
name[index]
For example, to store the value 75 in the third element of number a suitable statement statement would be as
follows:
number[2] = 75;
and, to pass the value of the third element of number to the variable a, the following statement is used:
a =number[2];
Therefore, for all the effects, the expression number[2] is like any variable of type int with the same properties.
Example
Write a program that initializes an array to the values 48,78,54,14,4 and displays the same
#include<stdio.h>
int main()
{
int i,number[5]={48,78,54,14,4 };
for(i=0;i<5;i++)
{
printf("%d\n", number[i]);
}
return 0;
}
#include<stdio.h>
void display(int [], int);
int main()
{
int i,number[10];
for(i=0;i<10;i++)
{
printf("Enter the element of the array\n");
scanf("%d",&number[i]);
}
display(number,10);
return 0;
}
void display(int arry[], int n)
{
int i;
printf("The elements of the array are:\n");
for(i=0;i<n;i++)
{
printf("%d\n", arry[i]);
}
}
table
Table represents a bidimensional array of 3 per 5 values of type int. The way to declare this array would be:
int table [3][5];
To reference the element in the second row and fourth column in an expression would be as follows:
table [1][3]
table [1][3]
Multidimensional arrays are not limited to two indices (two dimensions). They can contain so many indices as
needed, although it is rare to have to represent more than 3 dimensions
Example 1
Write a C program that inputs one of your name and the displays the same on the screen
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[20];
printf("Enter your name\n");
scanf("%s",name);
printf("Your name is: %s\n", name);
return 0;
}
Example 2
Write a C program that initializes the word PROGRAM and then displays it using the following format:
P
PR
PRO
PROG
PROGR
PROGRA
PROGRAM
Exercise
Write a C program that inputs two strings and then finds out whether it is a palindrome or not
Additional Examples
1) Write a program which incorporates a function using parameter passing and performs addition of the three
numbers. The function returns a value to the calling function
#include<stdio.h>
/* ANSI function prototypes*/
int add(int, int, int);
/* add function definition*/
int add(int num1, int num2, int num3)
{
int summation;
summation=num1+num2+num3;
return summation;
}
2) A furniture company sells tables various sizes. Write a C++ program that displays the menu shown below,
accepts the user’s option and passes the option as a parameter to the function (Compute), which should
return the cost of the table using the given rates. Your program should then output the cost.
#include<stdio.h>
/* ANSI function prototypes*/
int Compute(int);
/* main function definition*/
int main()
{
int option,rate;
printf("***Furnihture Menu***\n");
printf("Option\t\tSize\t\tRate(KSh)\n");
printf("1\t\t4'*6'\t\t500\n");
printf("2\t\t6'*10'\t\t850\n");
printf("3\t\t8'*12'\t\t1275\n");
printf("4\t\tExit\n");
printf("Enter your option\n");
scanf("%d",&option);
if(option==4)
exit(-1);
rate=Compute(option);
printf("The cost of the table is %d\n",rate);
return 0;
}
/* compute function definition*/
int Compute(int user_op)
{
int table_rate;
if(user_op==1)
table_rate=500;
else if(user_op==2)
table_rate=850;
else if(user_op==3)
table_rate=1275;
return table_rate;
}
#include<stdio.h>
int multiply (int, int);
float divide (int, int);
int main()
{
int number1,number2,product;
float quotient;
printf("Enter two numbers\n");
scanf("%d%d",&number1,&number2);
if(number1!=number2)
{
product = multiply (number1,number2);
printf("The product is %d\n", product);
}
else if (number1==number2)
{
quotient= divide (number1,number2);
printf("The quotient is %f\n", quotient);
}
return 0;
}
int multiply(int num1, int num2)
{
int product;
product =num1*num2;
return product;
}
float divide(int num1, int num2)
{
float quotient;
quotient =(float)num1/num2;
return quotient;
}
4) Write a C function that has three inputs which are integers. The function returns true if the first number
raised to the power of the second number equals the third number.
5) Write a C function that computes that total sum of a specific column Cin a 2 dimensional array of size 2
by 3.
Exercises
1). Write a program that accepts temperature in Fahrenheit and converts it to Celsius, through a user-defined
function named convert() and which returns the converted value. The program should print the Celsius
value, and if this is greater than 20, the program should print the message “ITS HOT HERE” otherwise, it
prints, “IT’S COLD HERE”. Use the following formula for conversion:
celsius = 5/9*( fahrenheit -32)
2). Write a program that computes the value of ex by using the formula ex=1+x/1!+x2/2!+x3/3!+-------------
-------------------------
3). Write a C program that uses four functions namely input, getGrade, output and main to read in the
average marks scored by a student and output the grade attained. The input function is used to read the
average mark (out of 100) for a student. This function should only accept values that fall within the range
0-100. The mark is then passed as a parameter to the getGrade function which uses it to assign a grade
based on the following classification:
Mark Grade
75 and above A
60 and below 75 B
50 and below 60 C
40 and below 50 D
Below 40 E
The mark and computed grade are the passed as parameters to the output function, which outputs the
appropriately. All functions input, getGrade and output are called from main
4). Write a C program that allows the user to enter and store the day’s temperature of the week. The program
then determines, computes and displays the lowest temperature, the highest temperature, sum and average
temperatures of the week using a suitable format.
5). Write a C Program that declares three arrays of size 2 by 3 and type integer. Your program should read
the values of the first two arrays, add the two arrays values and store the results in a third array. Declare
function to read the array values, use the function twice. Declare another function to add two arrays and
store the result in a third one.
6). Write a C function that searches for value key in a 2D array of size 6 by 5. The function should return
true if found false otherwise.