You are on page 1of 35

LESSON ONE

Function

OBJECTIVES

Know the advantages of using Function; and

Differentiate

Differentiate the call by value and call by reference.

the storage classes

STORAGE CLASSES
There are two different ways to characterize variables
By data type refers to the type of information represented by a
variable
By storage class refers to the permanence of a variable andits
scope within the program, that is, the portion of the program
over which the variable is recognized.
There are four storage-class specifications in C
1. Automatic variables or Auto
2. External variables or Extern
3. Static variables
4. Registers

AUTOMATIC VARIABLES
Automatic variables are always declared within a function
and are local to the function in which they are declared; that is
their scope is confined to that function. Automatic variables
defined in different functions will therefore be independent of
another, even though they may have the same name.
Any variable declared within a function is interpreted as an
automatic variable unless a different storage class specification
is included within the declaration.
Since the location of the variable declarations within the
program determine the automatic storage class, the keyword AUTO
is NOT required at the beginning of each variable declaration.
There is no harm in including an auto specification within a

declaration if the programmer wishes, though this is normally not


done.
An automatic variable, does not retain its value once the
control is transferred out of its defining function. Therefore,
any value assigned to an automatic variable within a function
will be lost once the function is exited. If the program

logic

requires that an automatic variable be assigned a particular


value each time the function is executed, that the value will
have to be reset whenever the function is re-entered.
EXTERNAL VARIABLES
External variables, in contrast to automatic variables, are
not confined to single functions. Their scope extends from the
point of definition through the remainder of the program. Hence,
they usually span two or more functions, and often an entire
program.
Since external variables are recognized globally, they can
be accessed from any function that falls within their scope. They
retain their assigned values within this scope. Therefore, an
external variable can be assigned a value within one function and
this value can be used within another function.
A declaration for an external variable can look identical to
a declaration for a variable that occurs inside a function or
block. Such a variable is considered to be global to all
functions declared after it, and upon exit from the block or
function, the external variable remain in existence.
The use of extern will cause some traditional c compilers to
complain. Although this is allowable in ANSI C, it is not

required. Variables defined outside of a function have external


storage class, even if the keyword extern is not used. Such
variables cannot have automatic or register storage class.
STATIC VARIABLES
Static variables have two important and distinct uses:
a. To allow local variable to retain its previous value when
the block is re entered.
b. Use in connection with external declarations.
Static variables can be utilized within the function in the same
manner as other variables. They cannot however be accessed
outside of their defining function.
REGISTER VARIABLES
The storage class register tells the compiler that the
associated variables should be stored in high-speed memory
registers, provided it is physically and semantically possible.
Since resource limitations and semantic constraints sometimes
make this possible, this storage class defaults to automatic
whenever the compiler cannot allocate an appropriate physical
register. Typically, the compiler has only a few such register
available; many are required for system use and cannot be
allocated otherwise.
Basically, the use of storage class register is an attempt
to improve execution speed. When speed is concern, the programmer
may choose a few variables that are most frequently accessed and
declared them to be of storage class register.

Sample program. Program with Extern and Auto

#include<stdio.h>
#include<conio.h>
int a =3;
main()
{ clrscr();
int funct1( int count);
for(count = 1; count <= 5; ++count)
{ a = finct1(count);
printf(%d,a);
}
OUTPUT
getch();
4
6
return 1;
}

13

18

Seatwork: Logic trace the program and write the final output
inside the box.
#include<stdio.h>
#include<conio.h>
int a = 100, b = 200;
funct1(int x)
{ int c, d;
int funct2(int c);
c = funct2(x);
d = (c < 100) ? (a + c): b;
return(d);
}
funct2(int x)
{ static int prod = 1;
prod *= x;
return(prod);}
main()
{ int count;
int funct1(int count);
clrscr();
for(count = 1; count < = 5; ++count)

printf(%d, funct1(count));
getch();
return 1;
}
FUNCTION IN C
The

heart

decomposition.

of

effective

Taking

problem

problem

and

solving

breaking

is

it

problem

into

small,

manageable pieces is critical to writing large programs. In C,


the

function

construct

is

used

to

implement

this

program

which

top-down

method of programming.
A

function

is

section

of

perform

specific task. The task assigned to a function is performed


whenever C encounters the function name. A function is actually a
subprogram that is, a function performs a task within a program
and is written in a form similar to C main program.

1.1 The advantages using FUNCTION


1. Using function fits naturally with a top-down design approach.
Use of function helps to streamline the design of a program and
prevents small details from obscuring the program logic.
2. Functions can often be used than once in a program and in
several different programs, thereby sharing programming time. A
function can be viewed as a blank box which performs a particular
task within a program. It accepts input and produces certain
output. When programming with function, you are plugging various
block boxes into your program to accomplish various necessary
tasks. Certain common task appears regularly in totally unrelated
programs.
repeatedly.

In

such

cases,

the

same

function

can

be

used

3.

Using

function

provides

natural

method

for

dividing

programming task among a team of programmers. By defining a


function as a block box which accepts certain inputs and produces
certain output, the function can be programmed as an independent
entity.
4. Function can be tested individually. By testing functions at a
time, the process of debugging an entire program is organized and
simplified.

FUNCTION DECLARATIONS
The function declaration has a name of a function, the type
of the value to be returned (if there are any) and the number and
types of the arguments that must be supplied in a call of the
function. A function declaration may contain argument names.
syntax:
type function_name (parameter list)
Example
int ccmit (int bsit, int bscs);
void ccmit ();
float ccmit (float x, float y);

FUNCTION DEFINITION
The code that describes what a function does is called a
function definition. It must not be confused with the function
declaration.
general form:

The

function

definition

must

have

the

following

type function_name (parameter list)


{

declaraction

local variables

statement;
}
Everything before the first brace comprises the header of
the

function

definition,

and

everything

between

the

braces

comprises the body of the function definition. The parameter-list


is a comma-separated list of declaration.
A function definition starts with the type of the function.
If no value is returned, then the type is void. If the type is
something other than void, then the value is returned by the
function will be converted, if necessary, to this type. The name
of the function is followed by a parenthesized list of parameter
declarations. The parameter act as a placeholders for values that
are passed when the function is invoked. Sometimes, to emphasize
their

role

as

placeholders,

these

parameters

are

called

the

formal parameters of the function. The function body is a block,


or compound statement, and it too may contain declarations.
Example
double twice(double x)
{
return(2.0*x)}

/*function definition*/

int all_add(int a, int b)


{ int c;
:
return(a+b+c);}

/*function definition*/

LOCAL VARIABLES TO A FUNCTION


Any variables declared in the body of function are said to
be local to that function. Other variables ay be declared
external to the function. These are called global variables.

Variables that are declared inside the function are called


local variables. In C, they are referred to as AUTOMATIC
VARIABLES or the keyword auto.

Local variables can be reference only by statements that are


inside the block in which the variables are declared.

Local variables are not known outside their own code.


should

remember

that

block

of

code

is

begun

when

You
an

opening curly brace is encountered and terminated when a


closing curly brace is found.

One of the most important things to remember about local


variable is that they EXIST only while the block code in
which they are declared is executing That is, local variable
is created upon entry into its block and destroyed upon
exit.

The most common code block in which local variables are


declared is in function.

Sample Program
#include<stdio.h>
#include<conio.h>
int a=33
main()
{
int b = 77;
/*b is local variable to main()*/
printf(a = %d\n,a); /*a is global variable to main()*/
printf(b=%d\n,b);
return 0;

getch();
}

GLOBAL VARIABLE TO A FUNCTION

Known throughout the entire program and maybe used by any


piece of code. Also, they hold their values during the
entire execution of the program.

Global variables are created by declaring them outside of


any

function.

They

maybe

accessed

by

any

expression

regardless of what function that expression is in.

Storage for global variables is in fixed region of memory


set aside for this purpose by the compiler.

Global variables are very helpful when the same amount of


data is used in many functions in your program.

You

should

avoid

using

unnecessary

global

variables,

however, three(3) reasons:


1. They

take-up

memory

the

entire

time

your

program

is

executing not just when they are needed.


2. Using global variables when local variable will do makes
a function less general because it relies on something
that must be defined outside by itself.
3. Using a large number of global variables can lead to
program
effects.

error

because

of

unknown

and

unwanted,

side

THE return STATEMENT

The return statement may or may not include an expression.


Syntax:
return;

The

return(expression);

expression

being

returned

can

be

enclosed

in

parenthesis, but this is not required. When a return statement is


encountered, execution of the function is terminated and control
is

passed

statement

back

to

contains

the
an

calling

environment.

expression,

then

the

If

the

value

return
of

the

expression is passed back to the calling environment as well.


Moreover, this value will be converted, if necessary to the type
of the function as specified in the function definition.
Example
float f(char a, char b, char c)
{
int i;
:
:
return i;
/*the value returned will be converted to a
float*/
}

There can be zero or more return statements in a function. If


there is no return statement, then control variable is passed
back to the calling environment when the closing brace of the
body is encountered. This is called falling off the end.
Program segment

double absolute_value( double x)


{
if(x >= 0.0)
return x;
else
return x;
}

FUNCTION PROTOTYPES

Functions should be declared before they are used. ANSI C


provides for a new function declaration syntax called the
functional prototype.

A function prototype tells the compiler the number and the


type of arguments that are to be passed to the function and
the

type

of

the

value

that

is

to

be

returned

by

the

function.

Example
double sqrt(double);
this tells the compiler that sqrt() is a function that takes a
single argument of type double and returns a double.
Syntax:
type function_name(parameter type list);

The parameter type list is typically a comma-separated list


of types. Identifiers are optional.

Example of function prototype:


void funct1(char c, int i); is equivalent
int);

to void funct1(char,

Function prototype allows the compiler to check the code


more thoroughly.

Also, values passed to function are properly coerced.

Note: Function Prototype in C++


In C++, function prototypes are required and the use of void in
the parameter type list in both function prototypes and the
function definition is optional.
Example
void funct1()

is equivalent to void funct1(void)

GIVING NAMES TO PARAMETER/PARAMETER LISTS


A function header identifies the parameters which are to be
passed to the function. In the header and in the actual body of
the function, the parameters used are FORMAL parameters which are
replaced by the ACTUAL parameter when the function is called.
Since the FORMAL parameters are eventually replaced, they are not
program

variable.

In

particular,

you

can

assign

to

FORMAL

parameters the names of program variable which will eventually


replace them.
FUNCTION INVOCATION AND CALL BY VALUE
A program is made up of one or more function definitions,
with one of these being main(). Program execution always begin
with main (). When program control encounters a function name,
the function is called, or invoked. This means that the program
control passes to that function. After the function does its

work, program control is passed back to the calling environment,


which then continues with its work.
Functions
appropriate

are

list

of

invoked

by

arguments

writing
within

their

names

parenthesis.

and

an

Typically,

these arguments match in number and type(or compatible type) the


parameters in the parameter list in the function definition. The
compiler enforces type compatibility when function prototypes are
used. All arguments are passed call by value. This means that
each argument is evaluated and its value is used locally in
place of the corresponding formal parameter.
A function call comes from either the main program or within
a function. The function originating a function call is referred
to as the calling function or calling environment.

HOW VALUE PARAMETER/CALL BY VALUE WORKS


A value parameter is a copy of a variable which is private
to the function. The function is given a copy of the actual
parameter

to

manipulate.

However,

the

manipulation

affect any of the variables in the calling program.

Sample Program
#include<stdio.h>
#include<conio.h>
int sum;
/*global declaration*/
void funct_sample ( int y);
void main()
{
int n =5; clrscr();
print(The value of n here is %d,n);
funct_sample(n);
printf(\nValue of n is %d,n);
getch();
}
funct_sample( int y)
{

does

not

/* Sample function using call by value */


y*= 3;
printf(The new value of y is %d, y);}
OUTPUT:
The value of n here is 5
The new value of y is 15
Value of n here is 5

Even though n is passed to funct_sample() and received by formal


parameter y, the value n which y in the body of that function is
changed,

the

value

of

in

the

calling

environment

remains

unchanged. It is the value of n that is being passed, not n


itself.

CALL BY REFERENCE OR VARIABLE PARAMETERS

To change the value of variable in the calling environment,


other languages provide the call by reference mechanism.

The use of addresses of variables as argument to function


can produce the effect of

call by reference

For the function to effect call by reference, pointers


must

be

used

in

the

parameter

list

in

the

function

definition. When the function is called, address of the


variables must be passed as argument.

In passing a variable parameter to a function, C does not


pass the actual value. Instead, it passes a pointer to a
variable being passed, that is, we pass the address of the

memory location holding the value of the variable being


passed.

& is used as address operator means the address of

* is called as indirection operator means the content of


address

Example
Address of the parameter value of parameter
16825

*50126
address of parameter is
being passed to the function

Sample program 1
#include<stdio.h>
#include<conio.h>
compute_rating(float midterm, float final, float *rating)
{
/* Function that will compute the final rating */
*rating = (midterm + final)/2;
}
main()
{
char name[25];
float mid,fin,fin_grd;
clrscr();
puts(Please enter you name);
gets(name);
printf(Enter your midterm grade);
scanf(%f,&mid);
printf(\nEnter you final grade);
scanf(%f,&fin);
compute_rating(mid,fin, &fin_grd);
printf(%s got a final rating of %f, name,fin_grd);
getch();
return 0;
}

Sample Program 2
void swap_ref(int &a,int &b);
void swap_val(int a,int b);
int main()

{
int a=3,b=6;
printf(\\na=%d
swap_val(a,b);

b=%d,a,b);

printf(\\na=%d b=%d,a,b);
swap_ref(&a,&b);
printf(\\n a=%d b=%d,a,b);
return 1;
}
void swap_ref(int *a, int *&b)
{
//function accepts a reference
*a= *a + b;
//to original parameter variable
b= *a-b;
*a= *a-b;
}
void swap_val(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
}

OUTPUT:
a=3 b=6
a=3 b=6
a=6 b=3

Swapping is an important technique in solving many programming


problems, and is often not well understood. The principle is
simple enough: we want to assign the value of variable (a) to the
value of variable (b) and vice versa. This is, however, an often
complex 3-stage process:
1. Put the value of variable (a) into variable (temp)

2. Put the value of variable (b) into variable (a)


3. Put the value of variable (temp) into variable (b)

Sample Program 3
Void

swap (int *x, int *y);


main()
{ int a= 3, b = 5;
puts(before);
printf( a is %d and b is % b, a,b);
swap(&a,&b);
puts(after:);
printf( a is %d and b is %d, a, b);
getch();
return;
}
Void

void swap(int *x,int *y)


{int z;
z = *x;
*x= *y;
*y = z;
}

LESSON TWO

ARRAYS

OBJECTIVES

To know in details the basic concepts of Arrays.


To be more familiar with the different uses of Arrays.
To be able to apply the use of Arrays in some complicated
applications.
To make the student develop good programming techniques
using Arrays

Introduction
ARRAY CONCEPTS
Imagine we have a problem that requires 20 integers to be
processed. We need to read them, process them, and print them.
We must also keep these 20 integers in memory for the duration of
the program. We can declare and define 20 variables, each with a
different name, as shown in the figure below.

Numbers0
Numbers1
Numbers2

Numbers19

Illustration:

Twenty variables

But having 20 different names creates another problem. How


can we read 20 integers from the keyboard and store them? To
read 20 integers from the keyboard, we need twenty references,
each to one variable. Furthermore, once we have them in memory,
how can we print them? To print them, we need another twenty
references.
Although this may be acceptable for 20 integers, it is
definitely not acceptable for 200 or 2000 or 20000 integers. To
process large amounts of data we need a powerful data structure,
such as array.

Characteristics of an Array
An array is a fixed-size, sequenced collection of elements of
the same data type.
An array is a sequence of data items that are of the same type,
that are indexible, and that are stored contiguously.
Arrays are data type that is used to represent a large number
of homogenous values.
Since an array is a sequenced collection, we can refer to
the elements in the array as the first element, the second
element, and so forth until we get to the last element. If we
were to put our twenty numbers into an array, we could designate
the first element as shown below.
Numbers0
In similar fashion, we could refer to the second number as
numbers1, and the third number as numbers2. Continuing the
series, the last number would be numbers19.
Process twenty variables
Numbers0 numbers1, , numbersn-1
What we have seen is that the elements of the array are
individually addressed through their subscripts. This concept is
graphically shown in the next figure to be presented. The array
as a whole has a name, numbers, but each member can be accessed
individually using its subscript.

The advantages of the array would be limited if


also have programming constructs that would allow us
the data more conveniently. Fortunately, there is a
of programming constructs Loops that makes array
easy.

we didnt
to process
powerful set
processing

Number0

Number[0]

Number1

Number[1]

Number18

Number[18]

Number19

Number[19]
Numbers
a. Subscript form

Numbers
b. Index form

An array of numbers
We can use loops to read and write the elements in an array.
We can use loops to add, subtract, multiply, and divide the
elements. We can also use loops for more complex processing such
as calculating averages.
But one question still remains. How can we write an
instruction so that at one time it refers to the first element of
an array, and the next time it refers to another element? It is
really quite simple: we simply borrow from the subscript concept
we have been using.
Rather than using subscripts, however, we will place the
subscript value in square brackets. Using this notation, we
would refer to number0 as:
numbers[ 0 ].

Following the convention, numbers1 becomes numbers[1] and


numbers19 becomes numbers[19]. This is known as indexing. Using
reference, we now refer to our array using the variable i.
Numbers [i]
USING ARRAYS IN C
We will first show how to declare and define arrays. Then
we will look at several typical applications using arrays
including reading values into arrays, accessing and exchanging
elements in arrays, and printing arrays.
Declaration and Definition
An array must be declared and defined before it can be used.
Declaration and definition tell the compiler the name of the
array, the type of each element, and the size or number of
elements in the array. The size of the array is a constant and
must have a value at compilation time.

#include<stdio.h>
#include<conio.h>
int scores[20], i, sum=0;
void main
{
clrscr();
printf(please enter 20 scores:\n);
for(i=0; i<20; i++)
{
scanf(%d,&scores[ i ]);
sum=sum + scores[ i ];
}
getch();
}

array declaration

Declaring and defining arrays


An array are defined in much the same manner as ordinary
variables, except that each array name must be accompanied by a
size specification ( the number of elements). For One dimensional
array, the size is specified by a positive integer expression
enclosed in square brackets. The expression is usually written
as a positive integer constant.
The general form One dimensional array
storage class data- type array[expression];
where storage class refers to storage class of the array, datatype is the data type, array is the array name and expression is
positive-valued integer expression that indicates the number of
array elements. Storage class is optional.
Example of one-dimensional array definition or array declarations
int ccmit[5];
char bscs[30];
float bsit[20];
double ITCS[12];
the first line indicates that ccmit is a 5 element integer array,
the second line describes that bscs is a 30 element character
array. In line 3, bsit is defined as 20 element floating point
array and the last line, ITCS is 12 element double array.

Consider the following array definition:


int x[4] ={1,2,3};
float y[5] = { 1.0, 1.25,1.5};

The results on an element by element basis are


x[0] = 1

y[0] = 1.0

x[1] = 2

y[1] = 1.25

x[2] = 3

y[2] = 1.5

x[3] = 0

y[3] = 0
y[4] = 0

In each case, all of the array elements are automatically set to


zero except those that have been explicitly initialized within
the array definition.
One dimensional array string data type - a character in a string
can be accessed either as an element in an array by making use
of a pointer to character. The flexibility it provides makes C
specially useful in writing string processing programs. The
standard library provides many useful string handling functions.
Strings are handled somewhat differently. In particular, when a
string constant is assigned to an external or a static character
array as part of the array definition, the array size
specification is usually omitted. The proper array size will be
assigned automatically. This will include a provision for the
null character which is \0 and automatically added at the end
of every string.

Example
Consider the character array definition. It includes an initial
assignment of the string constant CCMIT.
char college[6] = CCMIT;

It defines the following five element character array


college[0] = C;
college[1] = C;
college[2] = M;
college[3] = I;
college[4] = T;
college[5] = \0;
The array definition could have been written as
char college[ ] = CCMIT;

Accessing Elements in Arrays


C uses an index to access individual elements in an array. The
index must be an integral value or an expression that evaluates
to an integral value. The simplest form for accessing an element
is a numeric constant. For example, given an array scores[20],
we could access the first element as follows:
scores[0]

Typically, however, the index is a variable or an


expression. To process all the elements in scores, a loop
similar to the following code is used.
for(i=0;i<10,i++)
scores[i] .. ;

You might be wondering how C knows where an individual


element is located in memory. In scores, for example, there are
ten elements. How does it find just one? The answer is simple.
The arrays name is a symbolic reference for the address to the
first byte of the array. Whenever we use the arrays name,
therefore, we are actually referring to the first byte of the
array. The index represents an offset from the beginning of the
array to the element being referred to. With these two pieces of
data, C can calculate the address of any element in the array
using the following simple formula:
element address = array address + (sizeof (element) * index)
For example, assume that scores is stored in memory at
location 10,000. Since scores is an integer, the size of one
element is the size of an integer. Assuming an integer size of
two, the address of the element at index 3 is
element address = 10,000 + 2 * 3 = 10,006
STORING VALUES IN ARRAY
Declaration and definition only reserve space for the
elements in the array. No values will be stored. If we want to
store values in the array, we must either initialize the
elements, read values from the keyboard, or assign values to each
individual element.
Initialization
Initialization of all elements in an array can be done at
the time of declaration and definition, just as with variables.
For each element in the array we provide a value. The only
difference is that the values must be enclosed in braces and, if
there are more than one, separated by commas. It is a compile
error to specify more values than there are elements in the
array.
The initial values must appear on the order in which they will be
assigned to the individual array elements, enclosed in braces and
separated by commas.
The general form is

Storage class data type arrayname[expression] = { value1, value2,


value n};
Where value1 refers to the value of the first array element,
value 2 refers to the value of the second element and so on. The
appearance of the expression which indicates the number of array
elements is optional when initial values are present.
Examples of array initialization.
int first_array[5] = {5, 3, 2, 7, 9};
int second_array[ ] = {11, 21, 75, 24, 5};
int third_array[15] = {3, 7, 4, 6,1};
The first example is a simple array declaration of five
integers. It is typically the way array initialization is coded.
When the array is completely initialized, it is not necessary to
specify the size of the array. This case is seen in the second
example. It is a good idea, however to define the size
explicitly because it allows the compiler to do some checking and
it is also good documentation.
If the number of values provided is less than the number of
elements in the array, the unassigned elements are filled with
zeros. This case is seen in the third example. We can use this
rule to easily initialize an array to all zeros by supplying just
the first zero value of the first element.
INPUTING VALUES
Another way to fill the array is to read the values from the
keyboard or a file. This can be done using a loop when the array
is going to be completely filled, the most appropriate loop is
the for because the number of elements are fixed and known.
Example:
int scores[10];

for(i = 0;i<10,i++)
scanf(%d,scores[i]);
Several concepts need to be studied in this simple
statement. First, we start the index, i, at zero. Since there
are ten elements in the array, we must load the values from index
locations zero through nine. The limit test, therefore, is set
at i < 10, which conveniently is the number of elements in the
array. Then, even though we are dealing with array elements, the
address operator (&) is still necessary in the scanf call.
Finally,
are not going
(while or do
depend on the

when there is a possibility that all the elements


t be filled, then one of the event-controlled loops
while) should be used. Which one you use would
application.

Individual elements can be assigned values using the


assignment operator. Any value that reduces to the proper type
can be assigned to an individual array element.
Example:
scores [4] = 23;
On the other hand, you cannot assign one array to another
array, even if they match full in type and size. You have to
copy arrays at the individual element level. For example, to
copy an array of 25 integers to a second array of 25 integers,
you could use a loop as shown below.
for(i=0;i<25;++)
second [ i ] = first [ i ];
If the values of an array follow a pattern, we can use a
loop to assign values. For example, the following loop assigns a
value that is twice the index number to array scores.
for(i=0;i<10;i++)

scores [ i ] = i * 2;

Sample program 1
This is a program that sorts the values of the array num.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
in num[3] = {5, 3, 7};

array declaration and

initialization

int h, I, temp;
for(h=0;h<3;++h)
for(i=0;i<h;++i)
{
if (nm[i] > num[i+1])
{
temp = num[i];
num[i] = num [i+1];
num[i+1] = temp;
}
}
for(i=0;i<3;i++)
printf(%d\n, num[i]);
getch();
}
sample run:
Output:
3
5
7
Sample program 2

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >

#include<conio.h>
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
clrscr();
printf(Enter the size of the arrayn);
scanf(%d,&n);
printf(Enter the elements of the arrayn);
for I=0;I < n;I++)
scanf(%d,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(There are %d negative numbers in the array\n,count_neg);
printf(There are %d positive numbers in the array\n,count_pos);
getch();
return;
}

Multidimensional Arrays
Multidimensional arrays are defined in much the same manner
as one-dimensional. A two-dimensional array requires two pairs of
square brackets.
In general term, a multidimensional array definition can be
written as
storage-class data-type array[expression1][expression2];
where storage-class refers to the storage class of the array,
data-type is its data-type, array is the array name and
expression1, expression2 are positive-values integer expression
that indicate the number of array elements associated with each
subscript. Remember that storage-class is optional; the default
are automatic for arrays that are defined inside of a function
and external for arrays, defined outside of a function.
Several multidimensional array definition are shown below
float IT[5][3];
int CS [3][3];

The first line defines array IT as floating-point array having 5


rows and 3 columns while the second line indicates that array
name CS has 3 row and 3 column integer array elements.
Multidimensional array definition includes the assignment of
initial values, then care must be given to the order in which the
initial values are assigned to the array elements.

Consider the following two dimensional array definition


int ccmit[3][3] = {1,2,3,4,5,6,7,8,9};
Note that the values can be thought of as a table having 3 rows
and 3 columns. Since the initial values are assigned by rows
( last subscript increasing most rapidly), the result of this
initial assignment are as follows;
ccmit[0][0] = 1
ccmit[0][1] = 2
ccmit[0][2] = 3 ccmit[1]
[0] = 4
ccmit[1][1] = 5
ccmit[1][2] = 6 ccmit[2][0] = 7
ccmit[2][1] = 8
ccmit[2][2] = 9
The natural order in which the initial values are assigned can be
altered by forming groups of initial values enclosed within
braces. The values within each innermost pair of braces will be
assigned to those array elements whose last subscript changes
most rapidly. In a two-dimensional array, for example, the values
within an inner part of braces will be assigned to the elements
of a row, since the second subscript increases most rapidly. If
there are few values within the pair of braces, the remaining
elements of that row will be assigned zeros.

Remember: On the other hand, the number of values within each


part of braces cannot exceed the defined row size.
Example. Here is a variation of the two-dimensional array
definition presented in the last
example
int ccmit[3][3] = {{1,2,3},{4,5,6},{7,8,9} };
This definition results in the same initial assignment as in the
last example. Thus the three values in the first inner pair of

braces are assigned to the array elements in the first row, the
values in the second inner part of braces are assigned to the
array elements in the second row, and so on. Note that an outer
pair of braces is required.

Now consider the following two dimensional array definition


int ccmit [3][4] = {

{ 1,2,3},{4,5,6},{7,8,9}};

This definition assigns values only to the first three elements


in each tow. Therefore, the array elements will have the
following initial values.
ccmit[0][0]
ccmit[0][3]
ccmit[1][0]
ccmit[1][3]
ccmit[2][0]
ccmit[2][3]

=
=
=
=
=
=

1
0
4
0
7
0

ccmit[0][1] = 2

ccmit[0][2] = 3

ccmit[1][1] = 5

ccmit[1][2] = 6

ccmit[2][1] = 8

ccmit[2][2] = 9

Notice that the last character in each row is assigned a value


zero.
If the preceding array definition is written as
int ccmit [3][4] = {1,2,3,4,5,6,7,8,9};
then three of the array elements will again be assigned a value
zeros, though the order of the assignment will be different. In
particular, the array elements will have the following initial
order

ccmit[0][0]
ccmit[0][3]
ccmit[1][0]
ccmit[1][3]
ccmit[2][0]
ccmit[2][3]

=
=
=
=
=
=

1
4
5
8
9
0

ccmit[0][1] = 2

ccmit[0][2] = 3

ccmit[1][1] = 6

ccmit[1][2] = 7

ccmit[2][1] = 0

ccmit[2][2] = 0

Finally, consider the array definition


int ccmit [3][3] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
This will result in a compilation error since the number of
values in each inner pair of braces exceeds the defined array
size.

Sample program 3
/* example program to add two matrices & store the results
in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(enter the order of the matrix\n);
scanf(%d%d,&p,&q);
if(m==p && n==q)
{
printf(matrix can be added/n);
printf(enter the elements of the matrix a);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(%d,&a[i][j]);
printf(enter the elements of the matrix b);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(%d,&b[i][j]);
printf(the sum of the matrix a and b is);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
c[i][j]=a[i][j]+b[i][j];

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


{
for(j=0;j < n;j++)
printf(%dt,&a[i][j]);
printf(\n);
getch();
return;
}
}

You might also like