0% found this document useful (0 votes)
25 views101 pages

Chapter 5.0

The document discusses functions and arrays in C language. It covers defining and calling functions, passing arguments to functions by value and reference, and different types of functions. It also covers defining and initializing arrays, one-dimensional and multi-dimensional arrays. The document provides examples of code to demonstrate functions and arrays. It discusses using functions and arrays together to perform input/output operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views101 pages

Chapter 5.0

The document discusses functions and arrays in C language. It covers defining and calling functions, passing arguments to functions by value and reference, and different types of functions. It also covers defining and initializing arrays, one-dimensional and multi-dimensional arrays. The document provides examples of code to demonstrate functions and arrays. It discusses using functions and arrays together to perform input/output operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 101

CHAPTER 5 :

Function and Array

Lecturer :
Pn. Wan Fazlini Idayu binti Wan Fakari
Function and Array
5.1 Remember FUNCTION statements
5.1.1 Define FUNCTION statement
5.1.2 Identify the need for FUNCTION statements
5.1.3 Describe the structure of FUNCTION statements

5.2 Remember ARRAYS


5.2.1 Define ARRAY statement
5.2.2 Identify the need for ARRAY in programming
5.2.3 Describe the structure of ARRAY

5.3 Understand FUNCTION statements


5.3.1 Differentiate the call by value and call by reference in C language
5.3.2 Explain the passing value between FUNCTION
5.3.3 Explain the initialize FUNCTION in C Language
Function and Array
5.4 Understand ARRAY
5.4.1 Differentiate the two and three Dimensional ARRAY in C language
5.4.2 Explain the Passing ARRAY Elements in C Language
5.4.3 Explain the Initialize ARRAY in C Language

5.5 Apply FUNCTION statements


5.5.1 Construct program(s) that use FUNCTION statements
5.5.2 Construct program(s) that use Call by Value statements
5.5.3 Construct program(s) that use Call by Reference statements

5.6 Apply ARRAYS


5.6.1 Construct program(s) that use ARRAY in C Language
5.6.2 Construct program(s) that use Two Dimensional ARRAY in C Language
5.6.3 Construct program(s) that use Three ARRAY in C Language

5.7 Use ARRAY and FUNCTION statement to demonstrate the I/O operation
FUNCTION statements
Functions
• A function is a group of statements that together perform a
task.
• Every C program has at least one function, which is main(),
and most programs can define additional functions.
• You can divide up your code into separate functions, where
each function performs a specific task.
• A function declaration tells the compiler about a function's
name, return type, and parameters.
• A function definition provides the actual body of the
function.

5
Types of function
• There are two type of function:-
a. Predefined function
b. User-defined function
Types of function - Predefined function
• Predefined functions are functions that have been written and we can
use them in our C statements.

• These functions are also called as 'library functions'. These functions


are provided by system. These functions are stored in library files.
Example:-
– scanf()
– printf()
– strcpy
– strlwr
– strcmp
– strlen
– strcat
Types of function - User-defined function
• The functions which are created by user for program
are known as 'User defined functions'.
• Advantages :
– It is easy to use.
– Debugging is more suitable for programs.
– It reduces the size of a program.
– It is easy to understand the actual logic of a program.
– Highly suited in case of large programs.
– By using functions in a program, it is possible to construct
modular and structured programs.
Types of function - User-defined function
• Syntax: void main() { // Function prototype
<return_type><function_name>([<argu_list>]); // Function Call
<function_name>([<arguments>]); } // Function definition
<return_type><function_name>([<argu_list>]); { <function_body>; }
Types of function - User-defined function
Three steps in using functions
1. Declare the function:
• Known as function declaration or function prototyping.
• Write a function prototype that specifies:
– the name of the function
– the type of its return value
– its list of arguments and their types

2. Define the function:


• Known as function definition or function implementation.
• Write the block of statements (body) of the function to define processes
should be done by the function.

3. Call the function:


• Known as function call or function invocation.
• Call the name of the function in order to execute it. 11
Figure : Declaring, calling and defining functions

12
FUNCTIONS
• there are five types of functions and they are:
1. Functions with no arguments and no return
values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return values.

13
1. Functions with no arguments and no return value.

Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
15
1. Functions with no arguments and no return value.
#include<stdio.h>
#include<conio.h>

void printline()
{
int i;
printf("\n");
for(i=0;i<30;i++)
{
printf("-");
}
printf("\n");
}

void main()
{
clrscr();
printf("Welcome to function in C");
printline();
printf("Function easy to learn.");
printline();
getch();
} 16
Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
2. Functions with arguments and no return value.

Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
17
2. Functions with arguments and no return value.
#include<stdio.h>
#include<conio.h>

void add(int x, int y)


{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}

void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}

18
Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
3. Functions with arguments and return value.

Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
19
3. Functions with arguments and return value.
#include<stdio.h>
#include<conio.h>

int add(int x, int y)


{
int result;
result = x+y;
return(result);
}

void main()
{
int z;
clrscr();
z = add(952,321);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}
20
Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
4. Functions with no arguments but returns value.

Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
21
4. Functions with no arguments but returns value.
#include<stdio.h>
#include<conio.h>

int send()
{
int no1;
printf("Enter a no : ");
scanf("%d",&no1);
return(no1);
}

void main()
{
int z;
clrscr();
z = send();
printf("\nYou entered : %d.", z);
getch();
}
22
Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
5. Functions that return multiple values.
#include<stdio.h>
#include<conio.h>

void calc(int x, int y, int *add, int *sub)


{
*add = x+y;
*sub = x-y;
}

void main()
{
int a=20, b=11, p,q;
clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();
}

23
Reference: http://rajkishor09.hubpages.com/hub/Types-of-Function-in-C-Programming-Languages
Declaring a function
return_type function_name ( formal_parameter_list );

• The syntax of a function declaration (formally called prototype)


contains:
– The type of the return value of the function
• if the function does not return anything, the type is void
• if return_type is not written the Compiler will assume it as int

– The name of the function


• same rules as for variable naming

– A list of formal parameter made up of its names and its types.


They are enclosed in parentheses

– The prototype must be terminated by a semicolon

• Function prototypes are usually written between the preprocessor


directives and main(). 24
Examples of function prototypes
• float avrg(int num1, int num2, int num3);
– Function avrg takes three integers as parameters and returns a floatingpoint
value.

• void mix( double num1, int num2);


– This function receives a double and an integer value as parameters. But, it does
not return any value.

• void greeting( void );


– This function does not receive any parameter and also does not return any value.

• calculate();
– The return type and the formal parameters are not written.
– This function does not receive any parameter. It returns an integer value.
25
Defining a function
• The syntax of a function definition is:
function header

return_type function_name (formal_parameter_list)

{ The header is similar to


statements; prototype but no semicolon
return an_expression; function body
}

If the return_type is not void, the function must


have a return statement.
But, if the return_type is void, the return statement is
optional or just put return; (without an_expression)
26
Calling a function
• The name of a function is called in order to execute the
function.

• A called function receives control from a calling


function.

• When the called function completes its task, it returns


to the calling function.

• The called function may or may not returns a valueto


the calling function 27
Functions that return a value can be used in an expression or as a
statement.

Example:
if given function defintion as below:
float avrg(int a, int b, int c)
{
return (a+b+c)/3.0;
}

All function calls below are valid


result = avrg(1,2,3) + avrg(4,5,6); // function calls are
// used in an expression

avrg(1,2,3); // function call is used as a statement

printf(“The average is %.2f”, avrg(1,2,3) );


28
void function cannot be used in an expression because it does not
return any value. It can only be used as a statement.

Example:
if given function defintion as below:
void greeting(void)
{
printf("Hello");
return;
}

Function call below would be an error


result = greeting(); // Error! greeting() is a void function

29
• Formal parameters are variables that are declared in the header of
the function definition

• Actual parameters are the expressions in the calling statement

• When making a function call, the formal and actual parameters


must match exactly in type, order and number.

• The parentheses is compulsory, even when no parameters present.


This is the way, how the compiler knows an identifier either it is a
function or a variable.

– Example:
greeting; // Error. greeting is a function.
//So, it must have the ()
// eventhough no parameter present
30
Figure : void function with parameters

31
Figure : Function that returns a value

32
Function that calls itself is known as recursive function
Example:

int factorial(int n)
{
if (n>1) return n * factorial(n-1);
return 1;
}

This function calculates the factorial of n,


n! = n x (n-1) x (n-2) x … 2 x 1

At the first statement of the function definition, the function


calls itself.

33
return statement
• A function returns a computed value back to
the calling function via a return statement.

• A function with a non-void return type must


always have a return statement.

• Code after a return statement is never


executed.
34
The following function always returns 10.

int square (int n)


{
This line causes the control
return 10; back to the calling function and
ignores the rest of lines.
n = n * n;
return n; These two lines
are ignored and
} never executed

35
Local & global variables
• Local variable is a variable declared inside a
function.
– This variable can only be used in the function.

• Global variable is a variable declared outside


of any functions.
– This variable can be used anywhere in the program

36
Example: Local vs. Global

#include<stdio.h>
void print_number(void);
p is declared outside of all
int p; functions. So, it is a global
variable.
void main (void)
{
q is declared inside the
int q = 5;
function main. So, it is a local
printf(“q=%d”, q); variable to the function.
p=10;
print_number();
}
p can be used anywhere
void print_number(void)
{
Error! q can only be used in
printf(“%d”,p); the function main, because it
q = q + 5; is a local variable
37
}
Example: Local vs. Global
#include<stdio.h>
double compute_average (int num1, int num2);
void main (void) Same variable names?!?
{ --it’s OK; they’re local to
their functions. Compiler treat
double average; them as different variables.
int age1 = 18, age2 = 23;
average = compute_average(age1, age2);
return 0;
}
double average (int num1, int num2)
{
double average;
average = (num1 + num2) / 2.0;
return average;
} 38
Scope
• Scope determines the area of the program in
which an identifier is visible (ie. the identifier can
only be used in that area)

• Remember, identifier can be a variable, constant,


function, etc.

• Examples:
– Scope of a local variable : only in the function body
where t was declared.
– Scope of a global variable : everywhere in the program.39
Scope
• Scope that enclosed in { } is called a block.

• Inner block can use identifiers that were declared outside of


it.
– eg. Any function can use any global variables.

• But outer block cannot use identifiers that were declared in


inner block.

• Any block cannot use any identifier that was declared in


other block.
– eg. You cannot use any local variable from a function in another
function. 40
Example: Scope of inner and outer block and function
Parameter Passing
• To call a function, we write its name and give it
some information which are called parameters.

• Giving information to a function call is called


parameter passing.

• You have learnt these:


– formal parameters – parameters that are used in
function definition
– actual parameters – parameters that are used in
function call 43
Parameter Passing
• In order to pass parameters, the actual and
formal parameters must match exactly in type,
order and number.
– Eg. If you have defined a function with its formal
parameter as an “output parameter”, you must use
the ampersand (&) for its actual parameter when you
call the function. Otherwise you will get a syntax
error “Type mismatch”.

• Two types of passing:


– Pass by value
– Pass by reference 44
Pass by Value
• When a data is passed by value, a copy of the
data is created and placed in a local variable in
the called function.

• Pass by value does not cause side effect.


– After the function call completed, the original data
remain unchanged.

45
Figure : Pass by value
Pass by Value
• You have been introduced with the term
“input parameter”. This type of parameter is
passed using “Pass by Value”.

• When passing an expression, the expression is


evaluated first, then the result is passed to the
called function.

47
Passing expression by value
Pass by Value - examples
Pass by Value - examples
#include <stdio.h>
#include <conio.h>
void printno(int a) ;

void printno(int a)
{
printf("\n Number is : %d", a);
}

void main()
{
int no;
void printno(int);
clrscr(); printf("\n Enter Number : ");
scanf("%d", &no); printno(no); getch();
}
Pass by Reference
• Passing by reference is a passing technique that
passes the address of a variable instead of its
value.
– That’s why it is also called Pass by Address

• Pass by reference causes side effect to the actual


parameters.
– When the called function changes a value, it actually
changes the original variable in the calling function.

• Only variables can be passed using this technique.


51
Pass by Reference
• The formal parameter must be a pointer.
Example:
void fun(int *x) // x is a pointer variable
{
// function body
}

• The actual parameter must be an address of a


variable.
Example:
int n;
fun(&n); // &n means “address of variable n” 52
Pass by Reference- examples
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;

}
Pass by Reference- examples
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );

return 0;
}

void swap(int *x, int *y) {


int temp;

temp = *x; /* save the value of x */


*x = *y; /* put y into x */ *
y = temp; /* put temp into y */

return;

}
Figure : Pass by reference
ARRAYS
Concept of an array
• An ordinary variable can only contain a single value.
• An array is a variable that contains a collection of values of
the same type. These values are stored in a sequential
location.

57
Concept of an array

• A single value in an array is called an element.


• An index (or a subscript) is a reference of an element
– It is an integer number
58
– Index 0 refers to the first element
Using arrays
• Two things to do when using arrays:
– Declaration and definition of arrays
– Accessing elements in arrays
• for putting values
• for getting values

59
Declaring and defining Arrays
• Since an array is a variable, it must be declared and
defined before it can be used.
• Declaration and definition tell the compiler:
– the name of the array
– the data type of each element
– the number of elements in the array
Syntax:
data_type variable_name[n]; // n = number of elements

60
Declaring and defining Arrays

61
Declaring and defining Arrays
Like ordinary variables, arrays may also be initialized:

62
Accessing elements in arrays
• We use an index to access an element from an array.

• The index must be in a valid range


– The following example would be an error – array A has only 2
elements, but we try to access the third element which is not exist.

int A[2];

A[2] = 100; // this line would an error

• We access an element for two purposes:


– assigning new value into it
– getting its current value
63
Assigning values into elements
Examples:
1. Assigning a new value into the 2nd element of array A.

int A[] = {1,3,5,7};


A[1] = 100;

2. Incrementing the value of 3rd element of array B.

int B[] = {11,23,35,47};


B[2]++;

64
Assigning values into elements
Examples:
3. Assigning each element of array C with a value
that is twice its index

int C[9];
int i;
for (i=0; i<9; i++)
C[i] = i*2;

65
Assigning values into elements
Examples:
4. Assigning each element of array D with a value
that is read from the keyboard

int D[5];
int i;

for (i=0; i<5; i++)


scanf(“%d”,&D[i]);

66
Assigning values into elements
Examples:
5. The following example would be an error – elements of an
array must be assigned individually.

int E[4];
E = {10,20,30,40}; // this would be an error

// solutions: - assign them individually.


E[0]=10;
E[1]=20;
E[2]=30;
E[3]=40;

67
Getting values from elements
Examples:
1. Assigning variable n with the value of first
element of array A.
int A[] = {1,3,5,7};
int n;
n = A[0];

2. Printing the second element of array B


int B[] = {10,30,50,70};
printf(“%d”, B[1]);

68
Getting values from elements
Examples:
3. Assigning the first element of array C with the value of the
second element,
int C[] = {11,23,35,47};
C[0] = C[1];

4. Printing all elements of array D


int D[]={1,4,3,6,7,8,9,0,2};
int i;

for (i=0; i<9; i++)


printf(“%d\n”, D[i] );

69
Arrays and Functions
• Passing an element of an array to a function
can be in two forms:
- Pass by value - pass its content:
eg. printf(“%d”, A[2] );
- Pass by reference - pass its address.
eg. scanf(“%d”, &A[2] );

70
Arrays and Functions
Passing the whole array to a function can only be done by using pass by
reference.
- It is actually passes the address of the first element.

Example:

void increase(int x[3])


{ x[0] += 1;
x[1] += 2;
x[2] += 3;
}

void main(void)
{
int A[3]={10,20,30};
increase(A); // or, increase(&A[0]);
} 71
Extra note/ summaries
Array declaration (pengisytiharaan tatasunan):
[ ] means array
20 means 20 element/ 20 box
int B [20]; B

array
char GRED [10];

Array of char only

72
Reference
[ 0 ] 1st element

[ N-1] last element


73
assess the initial array
int B[5];
B[5]={26,3,6,107,20};

int B[5]={26,3,6,107,20};

26 3 6 107 20

[0][1][2][3][4]
74
• C allows a character array to be represented by a character
string rather than a list of characters, with the null terminating
character automatically added to the end. For example, to store
the string "Merkkijono", we would write:

char string[] = "Merkkijono";


OR
char string[] = {'M', 'e', 'r', 'k', 'k', 'i', 'j',
'o', 'n', 'o', '\0'};

String "Merkkijono" stored in memory

75
To read/print array using looping:
• Read:
for (i=0; i<5; i++)
{
scanf("%d ", &A[i]);
}

• Print:
for (i=0; i<5; i++)
{
printf("%d ", A[i]);
}

76
P L E
E X A M

77
#include <stdio.h>

void increase(int x[3])


{
x[0] += 1;
Another Function:
x[1] += 2; void increase(int x[3])
x[2] += 3;
} output:
void main(void)
{
int A[3]={10,20,30};
int i;

for (i=0; i<3; i++)


{
printf("%d ", A[i]);
}

printf("\n");
Array is use looping. If not:
increase(A); // or, increase(&A[0]); printf("%d ", A[0]);
printf("%d ", A[1]);
for (i=0; i<3; i++) printf("%d ", A[2]);
{
printf("%d ", A[i]);
}
} 78
#include <stdio.h>

void main()
{
char word[20]; output:

word[0] = 'H';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
word[5] = 0;
printf("The contents of word[] is -->%s\n", word );
}

79
#include <stdio.h>

void main()
{
output:
char day1[7] = "Sunday";
char day2[7] = "Monday";
char day3[8] = "Tuesday";
char day4[10] = "Wednesday";
char day5[] = "Thursday";
char day6[] = "Friday";
char day7[] = "Saturday";

printf("Day 1 is-->%s\n", day1 );


printf("Day 2 is-->%s\n", day2 );
printf("Day 3 is-->%s\n", day3 );
printf("Day 4 is-->%s\n", day4 );
printf("Day 5 is-->%s\n", day5 );
printf("Day 6 is-->%s\n", day6 );
printf("Day 7 is-->%s\n", day7 );
}
80
Multi-Dimensional Arrays
• 1-D array can also be extended to Multi-dimensional Array
• Multi-Dimensional array allows us to handle all these using a
single identifier
• Multi-Dimensional Arrays:-
– Two Dimensional ARRAY
– Three Dimensional ARRAY
1-D array 2-D array 3D-array
Two-Dimensional Arrays
• Two-dimensional (2D) arrays are indexed by two
subscripts, one for the row and one for the column.
• Example:
2D-array
2D-array
INITIALIZATION (2D array)
• Initialized directly in the declaration statement
• int b[2][3] = {51, 52, 53, 54, 55, 56};
b[0][0] = 51 b[1][0] = 54
b[0][1] = 52 b[1][1] = 55
b[0][2] = 53 b[1][2] = 55

• Use braces to separate rows in 2-D arrays.


– int c[4][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
– int c[ ][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
• Data may be input into two-dimensional
arrays using nested for loops interactively or
with data files.
• A nested for loop is used to input elements in
a two dimensional array.
• In this way by increasing the index value of the
array the elements can be entered in a 2d
array.
PROGRAM: Two-dimensional Array
FIGURE: Memory Layout
PROGRAM: Convert Table to One-dimensional Array
PROGRAM: Convert Table to One-dimensional Array
FIGURE: Passing a Row
FIGURE: Calculate Average of Integers in Array
FIGURE: Example of Filled Matrix
PROGRAM: Fill Matrix
PROGRAM: Fill Matrix
Three Dimensional (3D) ARRAY in C
Language
• A 3D array is essentially an array of arrays of
arrays: it's an array or collection of 2D arrays,
and a 2D array is an array of 1D array.
FIGURE: A Three-dimensional Array (3 x 5 x 4)
FIGURE: C View of Three-dimensional Array
example
Declaration and Initialization 3D
Array
Array using a Loop

You might also like