Vous êtes sur la page 1sur 8

Programming in C : UAA 105 : L .

Notes 6 : M S Prasad ( AISST)


Functions & Arrays
Functions
1. It is always recommended to break a large program into smaller modules
which can be understood well and produces legible output. In C language
this is carried out by defining functions ( similar to sub routines in old prog
language).
type function name ( arg1 , arg 2 )
type arg 1 ; type arg 2;
{ variables
------ expressions & statements
return ( return value )
}
Type defines the function type that is int , char etc. argument( arg) 1 & 2
are variables which are required to execute this function or define it . The
return return value should be as of the type definition of the function .
A function in C language is a block of code that performs a specific task. It has a
name and it is reusable i.e. it can be executed from as many different parts in a C
Program as required. It also optionally returns a value to the calling program. The
function which does not return a value is known as void function such as main (0
Properties of Function
.Every function has a unique name. This name is used to call function from
main() function.
A function can be called from within another function.
A function is independent and it can perform its task without intervention from or
interfering with
other parts of the program.
A function performs a specific task. A task is a distinct job that your program
must perform as a part of its overall operation, such as adding two or more integer,
sorting an array into numerical order, or calculating a cube root etc.
A function returns a value to the calling program. This is optional and depends
upon the task
function is going to accomplish. Suppose you want to just show few lines through
function then it is not necessary to return a value. But if you are calculating area of

rectangle and wanted to use result somewhere in program then you have to send
back (return) value to the calling function.
C language is collection of various inbuilt functions. If you have written a program in
C then it is evident that you have used Cs inbuilt functions. printf, scanf, clrscr etc.
all are Cs inbuilt functions.
Example of function.
int sum (int x, int y)
{
int result;
result = x + y;
return (result);
}
Advantages of using functions:
It makes possible top down modular programming. In this style of programming, the
high level logic of the overall problem is solved first while the details of each lower
level functions is addressed later.
The length of the source program can be reduced by using functions at appropriate
places.
It becomes uncomplicated to locate and separate a faulty function for further study.
A function may be used later by many other programs this means that a c
programmer can use function written by others, instead of starting over from
scratch.
A function can be used to keep away from rewriting the same block of codes which
we are going use two or more locations in a program. This is especially useful if the
code involved is long or complicated.
Types of functions:
A function may belong to any one of the following categories:
Functions with no arguments and no return values.
In such functions we can not pass data (values like int, char etc) to the called
function. Similarly, function with no return type does not pass back data to the
calling function. It is one of the simplest types of function in C. This type of function
which does not return any value cannot be used in an expression it can be used only
as independent statement.
Functions with arguments and no return values
This type of function can accept data from calling function. In other words, you send
data to the called function from calling function but you cannot send result data
back to the calling function. Rather, it displays the result on the terminal. But we
can control the output of function by providing various values as arguments
.
Functions with arguments and return values.

This type of function can send arguments (data) from the calling function to the
called function and wait for the result to be returned back from the called function
back to the calling function. And this type of function is mostly used in programming
world because it can do two way communications; it can accept data as arguments
as well as can send back data as return value. The data returned by the function
can be used later in our program for further calculations.
Functions that return multiple values.
So far, we have learned and seen that in a function, return statement was able to
return only single value. That is because; a return statement can return only one
value. But if we want to send back more than one value then how we could do this?
We have used arguments to send values to the called function, in the same way we
can also use arguments to send back information to the calling function. The
arguments that are used to send back data are called Output Parameters.
Example :
Functions with no arguments and return values.
We may need a function which does not take any argument but only returns values
to the calling function then this type of function is useful. The best example of this
type of function is getchar() library function which is declared in the header file
stdio.h.
Example simple function to add two integers.
?
1
#include<stdio.h>
2
#include<conio.h>
3
void add(int x,int y)
4
{
5
int result;
6
result = x+y;
7
printf("Sum of %d and %d is %d.\n\n",x,y,result);
8
}
9
void main()
10
{
11
clrscr();
12
add(10,15);
13
add(55,64);
14
add(168,325);
15
getch();
16
}
Example 2 .Returns 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();
}
Pointer to a function
Like C variables, function too has address and we can use this address to invoke
function. But before we can call a function using pointers we need to find out its
address.
The below program segment finds the memory address of a function show.
#include<conio.h>
#include<stdio.h>
int show();
void main()
{
clrscr();
printf("Address of show() : %u", show); /* to know the address of a function show()
it is sufficient to write only function name in printf statement. */
show();
getch();
}
int show()
{
printf("\n\nFunction called!");
return 0;
}
Using function pointers
#include<stdio.h>
#include<conio.h>
int show(); / * check it has been declared integer . Since pointers stores only
address of a data type ( int , float char etc) hence it has been made int */
void main()
{
int (*fnPtr)(); /8 function pointer defined . note always put function name in
brackets as ( *fnptr).
clrscr();

fnPtr=show;
printf("Address of function :%u",show);
(*fnPtr)();
getch();
}
int show()
{
printf("\nFunction called using pointer!");
return 0;
}
Function pointers are generally used for writing memory residents
programs such as Viruses and malware.

Arrays

Arrays are a data structure which hold multiple variables of the same data type.
Consider the case where a programmer needs to keep track of a number of people
within an organisation. So far, our initial attempt will be to create a specific variable
for each user. An array is a multi-element box, like a filing cabinet, and uses an
indexing system to find each variable stored within it.
Arrays could be single dimension or multi dimension. Arrays are defined as
under :type array name [ number of elements ]
In C, indexing of array starts at zero and all elements are stored
contiguously in the memory
e.g int a [100] the index of each element is a[0] , a[1] , .a[99]. Arrays, like
other variables in C, must be declared before they can be used, and can contain
any data types.
One important point about array declarations is that they don't permit the use of
varying subscripts. The number which defines elements could be unary operators ,
binary expression or return value from a function , and must be constant
expressions which can be evaluated at compile time, not run time.:
Multi-dimensioned arrays have two or more index values which specify the element
in the array. Muti dimensional arrays can be declared like this:
int three_dee[5][4][2];
int d[2][3]
If you refer to the precedence , [ ] associates left to right and that, as a result, the
first declaration gives us a five-element array called three_dee. The members of
that array are each a four element array whose members are an array of two ints.
The arrays are stored in Rows major order . e.g
Let us say we have following statements :-

#define max students 10


# define maxtest

int scores [ max students ] [ max test]


/ * is actually a 2 dimensional array containing 30 elements or 10 rows of 3
columns each and index would start from scores [0] [0] ..scores [ 9] [ 2]This
would be organized in memory as under */

Mem address

col 1

1000

col2

[0][0]

[0][1]

col3
[0][9]

1020

[1][0]

[1][1]

[1][9]

1040

[2][9]

[2][1]

[2][9]

Note; Memory address is incremented by 10 elements x 2 bytes . ( 16 bit


computer).In general to compute the memory address of any element we can use
following expression ;
Address of scores [7][2] = & of scores[0][0] +iI x size of( int )x max test + j x size
of (int)
Scores [7][2] =
2 bytes.}

1000 + 7 * 2 * 3 + 2 * 2 = 1046 { size of int in 16 bit system is

2.Character strings are treated as array of strings by the compiler. E.g I am


going is taken as array of character including end of line .
Example : indexing method of to access array elements also known as
Relative addressing
main ()
{ int value [12] ; /* defined a single dimension array of 12 elements)
for ( index =0 ; index < 12 ; index ++ )
values [ index] = 2 * [ index + 4] ; / * this is to put the values of the
elements in the array */
for ( index = 0 ; index < 12 ; index ++ )
printf ( value at index = % 2d is % 3d \ n , index , value { index] ) ;
}

Passing an array to a function


#include <stdio.h>
#include <string.h>
void myfunct (int , char [ ]);
int main ( )
{

char name[20] = " a. b. cdefghij


myfunct (20, name);

}
void myfunct (int len , char text[ ])
{

int k ;
printf ("%d\n", strlen(text)) ;
for (k = 0 ; k < len ; k++) printf ("%c", text[k]) ;

}
Result would be 14 , ( includes blanks also)
a. b. cdefghij
Finding the size of array
int array [ 10]
size of ( array [ 3]) ; / * returns the element size in bytes . since it is declared int
hence for 32 bit computer it is 4 bytes.
size of ( array) / * returns to total size of array i.e. 10 x4 bytes = 40 */
When we pass an array to a function actually its size is lost.
For multi dimensional arrays , the size of all , but the first dimension must be
specified. E.g
Char name [ ] [ 30]
Array Processing using Pointers
In general , every array notation expression has an equivalent pointer notation
e.g

tree [ 20 ]

is equivalent to * ( tree + 20).

Note : if we use array name in any expression , actually the value of that
expression is the array address
--------------------------------------------------------------------------------------------------------------------------

Vous aimerez peut-être aussi