0% found this document useful (0 votes)
24 views

5. Functions and Arrays

The document provides an overview of functions in C programming, detailing built-in and user-defined functions, their declarations, definitions, and calling mechanisms. It also covers arrays, including single and multi-dimensional arrays, their declaration, initialization, and access methods. Additionally, it discusses string manipulation functions and provides examples for better understanding.

Uploaded by

Bethwel Kipruto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

5. Functions and Arrays

The document provides an overview of functions in C programming, detailing built-in and user-defined functions, their declarations, definitions, and calling mechanisms. It also covers arrays, including single and multi-dimensional arrays, their declaration, initialization, and access methods. Additionally, it discusses string manipulation functions and provides examples for better understanding.

Uploaded by

Bethwel Kipruto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

FUNCTIONS

A function is a subprogram that does a particular task. Generally, it is used to encapsulate a set of operations
and return information (value) to the main function or calling routine/function. 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). 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.

ii) User-Defined Functions


These are functions written by a programmer to break down a large program into a number of modules known
as functions. Functions allow the programmer to modularise a program.
Generally a function has four parts, namely:
i) A name
ii) A body
iii) A return type
iv) A parameter list

Programming Notes ~ Wainaina Page 1 of 11


The name refers to the name of the function which has to unique
The body refers to the actual C code which defines how the function works. The body is enclosed by {}.
The return type is the type of the single variable/value, which the function is able to return to whatever other
function that called it.
The parameter list contains values that the function needs to use from outside itself and it is enclosed in brackets

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

The return statement:


This is the statement that is used in functions to return a value to the calling function. It is optional for any
function
Format:
return (expression); or return variable;

Function Declarations and Function Definitions:-


Every function in program must have a function declaration and a function definition
 Function Declaration refers to the functions name, return data type and parameters.
 Function Definition refers to the implementation of a particular function
Notice that Function Declaration and Function Definition appear together to form a function

Function Prototype:
A function prototype is a function declaration statement that 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);
If a function returns a value, then it should be called so that the return value is used. E.g. if a function add
returns an integer value then it might do something with that return value such as putting it into a variable.
x=add ();

Programming Notes ~ Wainaina Page 2 of 11


Arguments (Actual parameters)
It refers to the information that the called function needs, in order to perform its designated task i.e. the values,
which are passed to a function. Actual parameters are found in the calling functions.

Parameters (Formal Parameters)


It refers to special variables that are meant to receive the arguments. I.e. it provides a means for communicating
information between functions. Formal Parameters are found in the called functions

Example
Write a program which incorporates a function using parameter passing and performs addition of the two
numbers. The function returns a value to the calling function

#include<stdio.h>
/* function prototypes*/
int add(int, int);

/* main function definition*/


int main()
{
int number1, number2, sum;
printf("Enter two integer numbers\n");
scanf("%d%d%d ",&number1, &number2);
sum= add (number1,number2);
printf("The sum of two numbers is %d\n",sum);
return 0;
}

/* add function definition*/


int add(int num1, int num2)
{
int summation;
summation=num1+num2;
return summation;
}

Arguments Passing Mechanisms:


There are two ways of passing values in a function in many programming languages, which are: -
i) Pass by value
ii) Pass by reference

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.

Programming Notes ~ Wainaina Page 3 of 11


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*/


int factorial (int a)
{
if (a ==0)
return (1);
else
return (a * factorial (a-1));
}

/*The main function*/


int main ()
{
int number;
printf("Enter the number to find factorial:\n ");
scanf("%d",&number);
printf("The factorial of %d is %d\n",
number,factorial (number));
return 0;
}

Advantages of Using Functions


i) The sub programs are easier to write, understand and debug. The main program can consists of function
calls rather than countless lines of codes.
ii) A Function can be shared by other programs by compiling it separately and loading them together (re-
usability).
iii) Different programs working on one large project can divide the workload by writing different functions
hence reducing the complexity of the entire task.

Programming Notes ~ Wainaina Page 4 of 11


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.
This means that, for example, we can store five (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

Example
int number[5];
Means that five memory locations are created and are referenced by number[0], number[1], number[2],
number[3], number[4]

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:
int number[5] = {16, 2, 77, 40, 12071};

This declaration would create following array:

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.

Access the Values of an Array.


The values of an array are accessed individually by using the following format:

name[index]

For example, to store the value 75 in the third element of number a suitable statement statement would be as
follows:

Programming Notes ~ Wainaina Page 5 of 11


number[2] = 75;

and, to pass the value of the third element of number to the variable a, the following statement is used:

int a =number[2];

Therefore, for all the effects, the expression number[2] is like any variable of type int with the same properties.

Example 1
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;
}

Example 2
Write a program that prompts and inputs any ten integer numbers, store them in an array and then calls a
function display to output the array elements on the screen

#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]);
}
}

Programming Notes ~ Wainaina Page 6 of 11


Two Dimensional Arrays
It refers to bidimensional table consisting of rows and columns as shown below.

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:
Write a program that will initialize the elements of a 10 by 10 multiplication table to a two dimensional array
and display the same on the screen

/* two dimensional array*/


#include <stdio.h>
#define ROWS 10
#define COLUMNS 10
int main ()
{
int table [ROWS][ COLUMNS];
int i, j;
for (i=0; i< ROWS; i++)
for (j=0; j< COLUMNS; j++)
{
table [i][j] = (i+1)*(j+1);
}
for (i=0; i< ROWS; i++)
{
for (j=0; j< COLUMNS; j++)
{
printf ("%d\t", table [i][j]);
}
printf ("\n");
}
return 0;
}

Programming Notes ~ Wainaina Page 7 of 11


Strings
Characters arrays are called strings. Group of characters, digits, symbols enclosed within quotation marks are
strings.

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

#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[8]={'P','R','O','G','R','A','M','\0'};
int i, j;
for(i=0;name[i]!='\0';i++)
{
for(j=0;j<=i;j++)
{
printf("%c\t",name[j]);
}
printf("\n");
}
return 0;
}

Functions to manipulate strings


The string library defines many functions to perform some manipulation operations. The following are some of
these functions:
 strcat: char* strcat (char* dest, const char* src); Appends src string at the end of dest
string. Returns dest.
 strcmp: int strcmp (const char* string1, const char* string2); Compares strings
string1 and string2. Returns 0 is both strings are equal.

Programming Notes ~ Wainaina Page 8 of 11


 strcpy: char* strcpy (char* dest, const char* src); Copies the content of src to dest.
Returns dest.
 strlen: size_t strlen (const char* string); Returns the length of string.
 strlwr: converts uppercase characters of a string to lower case
 strlupr: converts lowercase characters of a string to lower case
 strdup: Duplicates a string
 strrev: Reverses all characters of a string
 strset: Sets all characters of a string

Exercise
Write a C program that inputs two strings and then finds out whether it is a palindrome or not

Additional Examples
1) 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.

******* Furniture Menu *******


Option Size Rate (KSh)
1 4’ * 6’ 500
2 6’* 10’ 850
3 8’ *12’ 1275
4 Exit

#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)

Programming Notes ~ Wainaina Page 9 of 11


table_rate=1275;
return table_rate;
}

2) Write a program that asks the user to enter two numbers and compute the sum or difference according to
the following rules. The product is computed when the first number is not equal the second number. The
quotient is computed when the first number is the same as the second. Define two functions multiply ()
and divide () to perform the two operations. Output the result by calling the relevant functions.

#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;
}

3) 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.

bool f1( int a, int b, int c)


{
if (pow( (float) a, (float) b)==c)
return true;
else
return false;
}

Programming Notes ~ Wainaina Page 10 of 11


4) Write a C function that computes that total sum of a specific column Cin a 2 dimensional array of size 2
by 3.

int SumOfCol (int a[][3], int rows, int col_id)


{
int sum=0,r;
for (r=0; r<rows; r++)
sum+=a[r][col_id];
return sum;
}

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.

7). Consider the Fibonacci series:


1, 1, 2, 3, 5, 8, 13, 21, 34...
Each number, after the second, is the sum of the two numbers before it. Write down a recursive function
fab that computes Fibonacci of the nth number. Note, fab(1) is 1 and fab(2) is 1.

Programming Notes ~ Wainaina Page 11 of 11

You might also like