You are on page 1of 58

Unit II – Arrays, Strings & Storage classes

One & two dimensional arrays

Initialisation

String variables

Declaration, reading, writing

String handling functions

User-defined functions

Variables & storage classes

Example C programs

CDS 1
Unit II – Arrays, Strings & Storage classes

FUNCTIONS
The advantages of using functions are
• Easy to write a small function and correctly
• Easy to read, write and debug a function
• Easier to maintain or modify such a function
• Small function tend to be a self documenting and
highly readable.
• A function can be called any number of times in
any place with different parameters

main ( ) {
printf ("programming in C is easy");
}
This program when executed would print the
message "programming in C is easy".

If we modify the name main to my_message this


would look something like this
my_message (){
printf ("programming in C is easy");
}

This code defines a function called my_message(),


whereas the previous one was called main().
Remember that way that valid C program should
contain a main ( ) function, where the execution of
the program begins.
Now we shall add a main ( ) function or routine to the
above code to complete our program.

CDS 2
Unit II – Arrays, Strings & Storage classes

my_message ( ){
printf ("programming in C is easy");
}
main ( ){
my_message ( );
}

This program now actually has two functions:


my_message ( ) and main ( ).

Program execution always begins at main ( ).

Inside the main ( ) routine we have the statement


my_message ( ); when the control comes to this
statement which is a function with no arguments, the
control is transferred to the definition of the function.

Inside the print-message function we have one printf


( ) statement which prints the specified message.
After the message is printed the function will be
finished (closing brace) and the program will return
to the main ( ) routine, where the program execution
will continue at the point where the function call was
executed.

Calling the function my_message ( ) from inside the


main ( ) function (or any other function in general) is
what is called as a function call statement or also
known as accessing the defined function.

CDS 3
Unit II – Arrays, Strings & Storage classes

Again recalling scanf( ) and printf( ), from our


program we are only calling them, we as
programmers have not defined them, it is defined &
provided to us in the form of C library.

Let us see a variation of the above program.


my_message ( ){
printf ("programming is really fun \n");
}
main ( ){
my_message ( );
my_message ( );
}
Can you guess what would be the output of this
program. Yes! The message would be printed twice,
once for the first call of my_message ( ) and another
time because we are again calling the function
my_message ( ) second time. This is the major
advantage of using a function. If we have to repeat
something then we don't have to write those
statements in a function and call them as many times
as needed from wherever you want and wherever you
need to call it.

CDS 4
Unit II – Arrays, Strings & Storage classes

Finally try & work out this program.


my_message ( ){
printf ("programming in C is easy \n");
}
main ( ){
int i;
for (i =1; i < = 100; ++i)
my_message ( );
}
The message will be printed 100 times.

Specification of arguments their types and return


values
Simple program to calculate the factorial of a number
using a function.
factorial (n)
int n;
{
int i, fact;
fact = 1,
for (i=1; i<=n; ++i){
fact = fact * i
}
printf ("factorial of %d =%d ,n, fact);
}
main ( ){
factorial (10);
factorial (20);
}

CDS 5
Unit II – Arrays, Strings & Storage classes

In brief, we have defined a function factorial, which


takes one argument called n, so this statement i.e.
factorial (n) is called function declaration which
defines the name of the function and also the
arguments i.e. number of arguments.

In this case, we have only one argument 'n'.

The arguments of the function are called as formal


parameters. The arguments can be used (referred)
anywhere inside the body of the function.

The next line immediately after the function


declaration is the line containing the declaration of
the types of the argument.

Here we have int n; which gives the information to


the compiler that the data type of 'n' is int.

After the formal parameter has been declared, the


body of the function is defined as usual. Here we
have written the code to calculate the factorial of n.

Note that we have declared & defined two integer


variables called i & fact inside the body of the
function factorial.

The variables inside the body of the function are


known as local variables. i.e. variables defined inside
a function. These are called because, their values are
not accessible outside the body of the function.

CDS 6
Unit II – Arrays, Strings & Storage classes

Coming to the main ( ) routine, we have two function


calls to the function factorial. One is factorial (10)
and another is factorial (20). When the control
comes to the statement factorial (10); the control is
transferred to the function factorial (n), while
transferring the value 10 becomes the value of the
formal parameter i.e. n. Then the function calculates
and prints the factorial of 10 & returns back to the
point from where the function was called. The next
statement is again a function call factorial (20) now n
will be assigned the value 20 and hence we will be
able to calculate the factorial of 20 this time.
The values, which we pass to the formal parameters
of the function from the function call in the main
program, are known as actual parameters. (Like here
10 & 20 are actual parameters).

All functions in 'C' have the form:


function- name (argument list)
argument declaration;
{
local variable declaration;
executable statements
return (expression)
}
The argument list is optional; declaration of local
variables is required only when they are needed in the
function. Return statement is also an optional
statement, which is used as a mechanism to for
returning a value to the calling function.

CDS 7
Unit II – Arrays, Strings & Storage classes

The function name must follow the same rules for


forming the variable names. Care should be taken
that you don't select the duplicate library function
names or operating system commands.

The argument list contains valid variable, names


separated by commas. The list must be surrounded
by parentheses. No semicolon should be placed after
closing parentheses. No semicolon should be placed
after the closing parenthesis. All argument variables
must be declared for their types after the function
header and before the opening brace of the function
body as we shown in the previous example.

The Return Statement is used to send back any


information to the calling function.

A function may or may not send back the


information. It can be return only a single value, per
call. The return statement can be written as
return;
return (value);
where value could be any expression.

Wherever a return statement is encountered in the


function, the control is immediately transferred to the
calling function.

CDS 8
Unit II – Arrays, Strings & Storage classes

Example
add (x, y)
int x, y;
{
int t;
t = x + y;
return (t);
}
A function may even have more than one return
statement like
if (a > 100)
return (1);
else
return (2);
The function, which returns a value, can be called
from the main program as
main ( ){
int a;
a = add (10,20);
printf ("%d, a);
}
The function is called at a = add (10,20) and control
is transferred to the function with the actual values,
then it is executed, after execution the sum of two
numbers is returned using the return statement back
to the main program and the return value is assigned
to the integer variable a.

Remember, a function cannot be used on the left


hand side of an assignment statement like
add (a, b) = 20;

CDS 9
Unit II – Arrays, Strings & Storage classes

Types of functions
Functions are classified according to the presence of
arguments and return values:
(i) Function with no arguments and no return values:
That means there is no data transfer between the
calling function and the called function.
Example:
Function_a( ) function_b( )
{ {
S1; ---
S2; ---
... ---
function_b ( ) }
...
}
function_a is calling function with no arguments and
there is no return statement in function_b.

(ii) Function with arguments but No Return values:


The function is called with same arguments and there
is no return value from the called function.
Example:
Function_a( ) function_b(y1,y2)
{ ---
S1; {
... ...
function_b(x1,x2); ...
... }
}
function_b is called from function_a with two
arguments x1 & x2. In the function declaration also,

CDS
10
Unit II – Arrays, Strings & Storage classes

we should have only two arguments of the same type


as those of formal arguments. Otherwise you'll get
type mismatch error.

(iii) Functions with arguments and also with return


values:
function_a( ) function_b(x, y)
{ ---
--- {
function_b(a, b); ---
--- return (p);
} }
To illustrate this let us write the factorial program
which returns the factorial value of the main
program.
#include < stdio.h >
factorial (n)
int n;
{
int i, fact;
fact = 1;
for (i =1; i< = n; ++i)
fact = fact * i;
return (fact);
}
main ( ){
int number, result;
scanf ("%d", &number);
result = factorial (number);
printf ("%d", result);
}

CDS
11
Unit II – Arrays, Strings & Storage classes

(iv) Functions returning Non-Integer values:


If the type-specifier is not present in the declaration
statement of the function, then the function will
always return an integer value with the return
statement by default.

However to return a value other than an integer one,


we have to write the function using this form:
type-specifier function-name (argument-list)
argument declaration;
{
function statements;
return ( ); /optional/
}
The type-specifier tells the compiler, the type of data
the function is to return. Also the called function
must be declared at the start of the body in the calling
function, like any other variable. This is to tell the
calling function, the type of data that the function is
actually returning.
Example:
main ( ){
int a, b, c;
float x, y, z;
char display ( );

}
The statement char display ( );
informs the compiler that display( ) is a function
which returns a character type.

CDS
12
Unit II – Arrays, Strings & Storage classes

Note: we can even have functions not returning any


values. This can be done with the qualifier void,
which states that function does not return any value.
Example:
main ( ){
void my_message ( ); /* function declaration */
my_message ( );
}
void my_message ( ) /* function definition */
{
printf ("Hello world");
}

There are several points to be noted:


a) Here we have defined the function
my_message() after the main program, in which
case you have to declare the function at the stare
of the body of the main program, which informs
the compiler that my_message is a function
which will be defined somewhere within this file
or in another file and the return type is void.
b) When the type specifier is void then it means,
function does not return any value, therefore
there should not be any return statement within
the body of the function. Otherwise you'll get
syntax error.

Note: The type and the number of arguments should


match in the called function and the calling function.

CDS
13
Unit II – Arrays, Strings & Storage classes

Function Prototypes
ANSI standard compiles the function definition and
arguments declaration in one line, with the function
header.

The general form of such a declaration is:


return-type function-name(type1 a, type2 b, . . ., typen z)
{
----
body of the function;
----
----
}

Example
float mul (float a, float b)

we cannot write it as
float mul (float a, b)

Every argument should be specified with its type


individually even if they are same & should be
separated by commas.

The new type of definition, which combines the


argument list and the argument declaration, is called
function prototype.

The function declaration in the function, which


informs to the compiler about he return type of the
function does not need the argument list.

CDS
14
Unit II – Arrays, Strings & Storage classes

With the introduction of function prototypes, the


function declaration not only requires the return type
of the function but also the type and number of
arguments, as illustrated below.
main ( ){
float a ,b, c;
float mul();
//function declaration with no argument list
---
---
c = mul((a),b);
}

Consider the same program with function prototypes


main ( ){
float a, b, c;
float mul (float a, float b); function prototype
---
--- /Ansi form
c = mul (a, b);
}

Some compilers can even accept in the form


float mul (float, float);
that means only the type of the argument (formal
parameter) would suffice.

Function prototype enables the compiler to check for


any mismatch of type and number of arguments
between the function calls and the function
definitions.

CDS
15
Unit II – Arrays, Strings & Storage classes

Note: The header files like stdio.h, conio.h, math.h,


etc. Contains the function prototypes and the
declaration statements of the standard variables like
NULL EOF etc.

It is advised that you open these files in an editor and


browse through to get your self-familiarized.

The header files contain only the declaration of


functions, the definition of function is present in the
library files in the form of an object code which will
be liked with the object code of users source
program.

Parameter passing mechanisms


There are several ways of passing the parameters
from the calling function of the called function. The
important one's supported in C are call by value and
call by reference.

The one which we have used so far is call by value.

In call by value, separate memory locations will be


created for both actual and formal parameters. If we
have three actual parameters in a function then
definitely there would be 3 formal parameters, so
totally six memory locations will be created.

At the time of calling the function using call by value


mechanism, the present values of the actual

CDS
16
Unit II – Arrays, Strings & Storage classes

parameters would be copied into the memory


locations of the formal parameters.

Whenever we reference the formal parameters inside


the function, the values contained in the memory
locations of the formal parameters will be taken and
modified.

The modified values of the formal parameters will


not be reflected back into the actual parameters.

This is illustrated below with an example, to swap


two values.
void swap (int c, int d){
int t;
t = c;
c = d;
d = t;
printf ("The swapped values in the function are c
= %d, d = %d", c, d);
}
main ( ){
int a, b;
scanf ("%d% d", &a, &b);
swap(a, b);
printf("The values after calling swap are a = %d,
b = %d", a, b);
}

CDS
17
Unit II – Arrays, Strings & Storage classes

Nesting of Functions
Example:
main ( ){
---
---
f1( );
---
---
}
f1( ){
---
---
f2 ( );
---
---
}
f2 ( ){
---
---
}
Note that main ( ) has called f1( ), which calls f2( ).

After finishing f2( ) has finished the control is


transferred to the function f1( ), when function f1( )
finishes the control is transferred to the main ( )
program.

CDS
18
Unit II – Arrays, Strings & Storage classes

Recursion
The function, which calls itself again and again
directly or indirectly, is called recursive function and
this technique is known as recursion.

The recursive function will be called by itself directly


or indirectly as long as the condition is satisfied.

Consider this example:


main ( ){
f1( );
---
---
}
f1( ){
---
---
f1 ( );
}

Examples:
main ( ){
printf ("I am in an infinite loop");
main ( );
}

Note that main ( ) is also a function and hence we call


itself again and again. So the message "I am in an
infinite loop" will be printed continuously until you
press the Del key or adopt some other means to
terminate the program.

CDS
19
Unit II – Arrays, Strings & Storage classes

Recursive program to find the sum up to a given


positive integer n.
Sum = 1+ 2 + 3 + . . . + n.
main ( ){
int number;
printf ("Enter the number");
scanf("%d, & number);
printf("the sum of first n numbers is %d",
sum(number);
}
sum (n)
int n;
{
int value = 0;
if (n == 0)
return (value);
else
value + = sum (n-1);
return (value);
}
Recursive factorial function.
factorial (n)
int n;
int fact = 1;
{
if (n ==1 || n == 0) return (1);
else
fact = fact * factorial (n-1);
return (fact);
}

CDS
20
Unit II – Arrays, Strings & Storage classes

Exercises
(1) The following function returns the value of x/y.
ratio (x, y)
float x, y;
{
return (x/y);
}
What will be the value of the following function
calls?
(a) ratio(10,2) (b) ratio(9,2) (c) ratio(4.5, 1.5)

(2) Determine the o/p of the following program:


main ( ) mul (a, b)
{ int a, b;
int x = 10; {
int y = 20; return(a * b);
int p, q; }
p = mul (x,y);
q = mul (p, mul (x,2));
printf ("%d %d", p,q);
}

(3) Determine the output of the following


main ( ){
printf ("I am in main");
display ( );
}
display ( ){
printf ("I am in display");
}

CDS
21
Unit II – Arrays, Strings & Storage classes

(4) Write a function swap(a, b) which accepts two


integer values and interchanges their values
without using a temporary variable.

(5) Write a function power(a, b) which returns a


raised to b.

(6) Give the output of the following:


main ( ){
int i = 5, j = 2
change (i, j);
printf ("%d %d", i, j);
}
change (int i, int j){
i = i * j;
j = j * j;
}

STORAGE CLASSES
Variables in ‘C’ language differ in behaviour from
those in most other languages, for instance in most
other languages, the variables retain their value
throughout the program.

It is not always the case in C. It depends on the


storage class of the variable.

Every identifier also has a storage class that provides


information about its visibility, lifetime and location.

CDS
22
Unit II – Arrays, Strings & Storage classes

Normally, in C the variable can be declared as any


one of the following groups:
1) Automatic variables.
2) External variables.
3) Static variables.
4) Register variables.

Automatic variables
They are declared inside a function.

They are created inside a function and destroyed


automatically when a function is terminated.

Automatic variables are private or local to the


function in which they are declared. Hence automatic
variables are referred to as local or internal variables.

The scope of a variable refers to the extent of the


meaning of the variable within the program.

The scope of local or automatic variables is limited to


the function. They are not accessible outside the
function.

We may also use the keyword auto to declare


automatic variables, explicitly.

By default the variables declared without any storage


class is termed to be auto.

CDS
23
Unit II – Arrays, Strings & Storage classes

Examples
main ( ) {
auto int n;
---
---
}

auto int n; or just int n; is same, in which case the


variable n is not accessible outside of the function n.

main ( ) {
int n = 100;
func1( );
printf(“n in main is %d,” n);
}

func1( ){
int n = 10;
printf(“n in func1 is %d, n);
}

func2( ) {
int n = 1000;
func1( );
printf(“n in func2 is %d”, n);
}
The output of the above program is:
10
1000
100

CDS
24
Unit II – Arrays, Strings & Storage classes

One important point to note is that, every function


main(), func1() and func2( ), is having the same value
‘n’, but is not accessible in the other functions i.e.
they are local to the functions.
Note: Automatic variables can be defined within a
set brace known as “blocks”. They are defined and
accessible within the blocks where they are defined.
Example
main ( ) {
int x, y, z;
---
--- block 1
if (x < = 100) {
int x,y, sum;
--- block 2
---
}
----
---- ← sum is not accessible here
----
}

The variables x & y in block will be different from


the variables x & y of block1 even though they have
the same name.

The lifetime & scope of x & y of block 2 is limited to


the block2 and also that of the local variable sum
defined inside block2.

CDS
25
Unit II – Arrays, Strings & Storage classes

However if x & y are not declared & defined in


block2 then the variables of x &y of block 1 are
accessible in block2 which becomes the global
variables as discussed in next section.

External variables
Variables that are alive and active throughout the
entire program are known as external variables or
global variables.

Unlike local variables global variables can be


accessed by any function, in the program.

Example
int n = 100;
float m = 10.5; global or external variables
main ( ) {
---
---
}

f1 ( ){
---
---
}

f2 ( ){
}

CDS
26
Unit II – Arrays, Strings & Storage classes

Then the variables m and n are called global variables


and are accessible for use in all the three functions
i.e. main, f1 & f2.

Note: In case if the global & local variable have the


same name, then local variable will have precedence
over the global variable.

Example
int n;
main ( ) {
n = 10;
---
---
}

f1 ( ){
int n = 0;
---
---
n = n+1;
}

When the function f1, references n, it will reference


the local variable ‘n’.

However in the main program, when we reference ‘n’


the global variable is referenced.

Once a variable has been declared as global, any


function can use it and change its value.

CDS
27
Unit II – Arrays, Strings & Storage classes

Example
int n;
main ( ) {
n = 10;
printf(“n = %d \n”, n);
printf(“n = %d \n”, f1( ));
printf(“n = %d \n”, f2());
}
f1( ){
n = n+10;
return (n);
}
f2 ( ){
int n;
n = 1;
n + +;
return (n);
}
The output of this program is
n = 10
n = 20
n=2
The global variables are visible only from the point
of declaration to the end of the program.
Consider the program fragment:
main ( ){
y = 100;
---
---
}
int y;

CDS
28
Unit II – Arrays, Strings & Storage classes

f1( ){
y = y+1;
}

‘y’ is declared after the main program and hence is


not accessible in the main program.

However it is accessible in the function f1. So you


will get a syntax error.

Unlike local variables, all global variables are


initialised to zero.

External declaration
In the above program segment, we have seen that
main( ) cannot access the variable y since it was
declared after main( ).

This can be solved by using the extern declaration as


follows:
main ( ) {
extern int y; /declaration */
---
---
}
f1( ){
extern int y; /declaration */
---
---
}
int y; /* definition */

CDS
29
Unit II – Arrays, Strings & Storage classes

Eventhough the variable y has been defined after


both the functions, the extern declaration informs the
complex that the variable y has been defined
somewhere else in the program.

Accessing variables in multiple files


Multiple source files can share a variable provided it
is declared as an external variable appropriately.

Variables that are shared by two or more files are


global variables and therefore we must define them
accordingly in one file and then explicitly declare
them with extern in other files.

This is shown below:


f1.c f2.c

main ( ) int a; / *global variable */


{ func2 ( )
extern int a; {
int i; int k;
--- ---
--- ---
} }
func1 ( ) func3 ( )
{ {
int j; float c;
--- ---
--- ---
} }

CDS
30
Unit II – Arrays, Strings & Storage classes

With these declarations, we can access the global


variable ‘a’ defined in f2.c in the main ( ) function of
f1.c with the extern declaration.

Note: The extern declaration does not result in the


allocation of storage to the variable. Storage is
allocated only at the definition of the global. Also
the local variables are not accessible even with the
extern declaration.

Note: When a function is defined in one file and


accessed in another, the later file must include a
function declaration (prototype), which identifies the
function as an external function whose definition
appears somewhere else.

Static variables
The value of static variables persists until the end of
the program.

A variable can be declared static using the keyword


static as shown below:
static int a;
static float b;

static variable can be either internal (local) or global


(external).

Internal or local static variables are those which are


declared inside a function and its scope will be till the
end of the function.

CDS
31
Unit II – Arrays, Strings & Storage classes

Therefore, internal static variables are like automatic


variables with the only difference in lifetime.

The lifetime of static local variables is till the end of


the program execution, hence they will hold the
values even if you come out of the function.

Note: Static variables are initialised only once i.e.


when the program is compiled.

An external static variable is declared outside all


functions and is available to all functions in that file
or program.

The external static variables not accessible outside


the file unlike the auto or ordinary external variables
which are accessible even in other files with extern
declaration.

These rules are accordingly applicable to the


functions also.

A function declared as static is not accessible outside


the file.
Example
main ( ) {
int i;
for (i = 1; i < = 4; i ++)
static-fun ( );
}

CDS
32
Unit II – Arrays, Strings & Storage classes

static-fun ( ) {
static int x = 0;
x + = 3;
printf (“x = %d \n”, x);
}

The output would be:


x=3
x=6
x=9

Suppose in static-fun (), the word static wouldn’t


have been these, then the output would have been:
x=3
x=3
x=3

REGISTER VARIABLES
The features of a variable to be of register storage
class are as under:
• stored in CPU registers
• default initial value is garbage value
• scope is local to the block in which the variable is
defined.
• the life time is till the control remains within the
block in which the variable is defined.

A value stored in a CPU register can always be


accessed faster than the one, which is stored in
memory.

CDS
33
Unit II – Arrays, Strings & Storage classes

Therefore if a variable is used quite often and at


various places in the program, it is better to declare
its storage class as register.

Example
main ( ){
register int i;
for (i = 1; i < = 10; i ++)
printf (“%d \n”,i)
}
Even though we have declared the storage class of ‘i’
as register, we cannot be sure that the value of i
would be stored in CPU register, because of the
limited number of CPU registers.

In such cases, the variable works as auto storage


class.

Note: We cannot use storage class register for all


types of variables. We cannot have for types float,
double etc.

CDS
34
Unit II – Arrays, Strings & Storage classes

ARRAYS
The ‘C’ language provides the capability to define a
set of ordered data elements known as an array.

It is also known as a subscribed variable or a vector.

Definition
An array is a group of related data items that share a
common name.

The main advantage of using arrays is to develop


concise and efficient programs.

Vector or a Single Dimensional Arrays


A variable which stores a group of similar elements
with only one subscript is known as a one-
dimensional array or a vector.

To represent a set of 5 numbers (integers) in an array


numbers, we may declare such a variable as int
numbers [5]; then this would allocate 5 memory
locations for each number [i], starting from 0, as
shown below:
number [0]
number [1]
number [2]
number [3]
number [4]

CDS
35
Unit II – Arrays, Strings & Storage classes

These memory locations can contain integer values,


which may be either read in or be assigned through
assignment statement.

Array Declaration
Like other variables, arrays must be declared before
they are to be used.

The general from of array declaration is:


data-type variable-name [size];

data-type could be int, float, char etc.

Size has to be a constant expression.

Example:
float height[100];
declares height as an array variable which can store
100 floating values.

int code[10];
creates 100 memory locations which can store integer
values each addressed by code [i].

char name [10];


creates 10 memory locations each one capable of
storing a single character.
The array ‘name’ is also called as a string.
When the compiler sees a character string, it
terminates it with an additional null character \0.

CDS
36
Unit II – Arrays, Strings & Storage classes

With char name [10], we can have a sample string


like this:

name 0 W
1 E
2 L
3 C
4 O
5 M
6 E
7 M
8 A
9 N
10 ‘\0’

name [0] = ‘W’;


name [1] = ‘E’ etc.
Note that name [10] = ‘\0’.

Note: When declaring character arrays, we should


always allow one extra element to be reserved for
null character.

Array Initialisation
Array elements can also be initialised like other
scalar variables, in the declaration itself.

Ordinary variables capable of storing a single value


also known as scalar variables.

CDS
37
Unit II – Arrays, Strings & Storage classes

The general format of array initialisation in the


declaration is
static type array-name [size] = {list of values};

The list of values should be separated be commas.

Examples
Static int marks [3] = {10,20,30};
initialises marks[1] to 10; marks[2] to 20 and
marks[3] to 30.

If the number of values in the list is less than the


number of elements in an array then the remaining
elements will be initialised to zero.

Static float avg [5] = {0.0, 1.5, 2.5};


initialises the first three elements of avg. to 0.0, 1.5 &
2.5 respectively, & the remaining elements will be
initialised to zero.

The size parameter may be omitted, in which case,


the compiler allocates enough space for all initialised
elements.

static int marks [ ] = {0,0,0,0};


declares marks as an integer array to contain 4
elements and also initialise them to zeros.

CDS
38
Unit II – Arrays, Strings & Storage classes

Similarly we can initialise character arrays


static char my-name [ ] = {‘R’, ‘A’, ‘J’, ‘U’};
declares my-name as an array of 4 characters
initialised to “RAJU”.

Note: The size may not be needed if initialisation is


done in the declaration of the array itself. However
size is essential if initialisation of array elements is
not done in the declaration statement.

Like, int marks [ ]; is not correct, size is always


required if only declaration is there without
initialisation.

The word static may be omitted in the initialisation


statement of arrays if we use ANSI C compiler.

The other rules of arrays are almost the same as those


applied for ordinary variables. The same operations
can be preferred on array elements, which are
performed on ordinary variables.

CDS
39
Unit II – Arrays, Strings & Storage classes

Example Programs
Program to read a set of n numbers in an integer
array and calculate their sum and average.
#include <stdio.h>
main ( ) {
int i, n;
float sum, average;
int number [100]; ← array definition
scanf (“%d”, &n);
for (i = 0; i < = n; ++i)
scanf (“%d”, & numbers [i]);
sum = 0;
for (i = 0; i <=n; ++i)
sum + = numbers [i];
average = sum/n;
printf(“sum = %f, Average = %f”, sum, average);
}

First, we read the number of numbers in n.

Then we read the numbers in an array numbers [ ]


using a for loop. Then we use another for loop to add
all the numbers [i] to the variable sum.

This program can be optimised, by adding the


number in the for loop when we read it. Thereby we
can avoid the second for loop, as follows:
for (i = 0; i < n; ++i) {
scanf (“%d”, & numbers [i]);
sum + = numbers [i];
}

CDS
40
Unit II – Arrays, Strings & Storage classes

Program to read a set of numbers in an array &


determine their largest & smallest.
# include <stdio.h>
main ( ){
int a [100];
int i, n, max, min;
scanf (“%d”, &n);
for (i = 0, I <= n; ++i)
scanf (“%d”, &a[i]);
max = a[0];
min = a[0];
for (i=1;i<=n;++i){
if (a[i] > max)
max = a[i]
else
if (a[i]<min)
min = a[i];
}
printf (“max = %d; min = %d, max, min);
}

CDS
41
Unit II – Arrays, Strings & Storage classes

Exercises
(1) Give the output of the following:
(a) int i = 0;
main ( ) {
auto int i = 1;
printf (“%d”, i);
{
int i = 10;
printf (“%d”, i);
{
i + = 10;
printf (“%d”, i);
}
printf (“%d”, i);
}
printf (“%d”, i);
}

(b) main ( ) {
int i,r;
for (i=1; i<=3; ++i){
r = check (i);
printf (“%d”, r);
}
}
check (int i) {
static int k = 1;
k = k * i;
return (k);
}

CDS
42
Unit II – Arrays, Strings & Storage classes

(2) Declare a character-based array called name of


ten elements. Assign the character value ‘k’ to
the fourth element of the name array.

(3) Use for loop to total the contents of can integer


array called marks which has 10 elements. Store
the result in an integer called total.

(4) Assign the text string “Hello” to the character


based array words at declaration time.

(5) Write for loop which will read five characters


(use scanf) and deposit them into the character
based array words beginning at element zero.

(6) Give the output of the following program.


main ( ) {
static int a [10];
int i;
for (i=0; i<=9; ++i)
printf(“%d”, a[i]);

CDS
43
Unit II – Arrays, Strings & Storage classes

Like the simple variables, it is also possible to pass


the values of an array to a function.

To pass an array to a called function, it is sufficient to


list the name of the array, without any subscripts and
the size of the array arguments.
Example:
max (a, n);
where a is an integer array containing n elements.

The function called expecting this call must be


appropriately defined.

The function header of the max may look like:


int max (b,m)
int b[ ];
int m;

The declaration of formal argument is made as


int b[ ];
It is not necessary to specify the size of the array
here.

Example:
Program to find the largest and smallest element in an
array of ‘n’ elements:
main ( ){
int max_min ( );
int values [100];
int n; i;
printf(“%d”, & n);

CDS
44
Unit II – Arrays, Strings & Storage classes

for (i=1; i<=n; ++i){


scanf (“%d”, & values [i]);
}
max_min (values, n);
}
max_min (numbers, m)
int numbers [ ];
int m;
{
int i, max, min;
max = min = numbers [1];
for (i=1; i<=n; ++i){
if (numbers [i] > max)
max = numbers [i];
else
if (numbers [i] < min)
min = numbers [i];
}
printf (“%d %d”, max, min);
}

(2) Program to sort an array of integers in ascending


order:
main ( ){
int i; n; void sort ( );
int array [100];
scanf (“%d. &n);
for (i=1; i<=n; ++i)
scanf (“%d”, & n);
sort (array, n);
printf (“the sorted list is “);

CDS
45
Unit II – Arrays, Strings & Storage classes

for (i=1; i < = n; ++ i)


printf (“%d”, array [i]);
}
void sort (a,m)
int a[ ];
int n;
{
int i,j, temp;
for (i=1; i<=n-1; ++i)
for (j=i+1; j<=n; ++j)
if (a[i]>a[j]{
temp = a[i]
a[i] = a[j];
a[j] = temp;
}
}

In a similar fashion, we can pass the float and char


arrays.

Note: you might have noticed in both the programs


that, the changes made to the array inside the
function were reflected in the main program from
where it was called.

If the function changes the value of an array element,


then that change will be made to the original array
that was passed to the function. This change will
remain in effect even after the execution of the
function is finished & has returned to the calling
routine (function.)

CDS
46
Unit II – Arrays, Strings & Storage classes

The reason for this is that, the entire contents of the


array are not copied into the formal parameter array.
Instead, the function gets passed information
describing where in the computer memory the array
is located. Any changes made to the formal
parameter array by the function are actually made to
the original array passed to the function, and not to a
copy of the array. That is why, when the function
returns, these changes still remain in effect.

Multidimensional arrays
Two-dimensional arrays
So far, we have seen how to handle single
dimensional arrays, which can be referenced by a
single subscript.

There will be situations where a table of values needs


to be read and stored. Table of values, which are in a
matrix form like:

10 20 30 40
50 60 70 80
90 15 25 35
45 55 65 75

This is a matrix, which consists of four rows and four


columns.

C allows us to define such tables of items by means


of two-dimensional arrays.

CDS
47
Unit II – Arrays, Strings & Storage classes

The above matrix or table can be defined as matrix[4]


[4];

The general format for declaring a two dimensional


array is:
type array-name [row-size][column-size];

Two dimensional arrays are stored in memory as


shown below:
col.0 col.1 col.2 col.3
[0][0] [0][1] [0][2] [0][3]
Row 0 10 20 30 40
[1][0] [1][1] [1][2] [1][3]
Row 1 50 60 70 80
[2][0] [2][1] [2][2] [2][3]
Row 2 90 15 25 35
[3][0] [3][1] [3][2] [3][3]
Row 3 45 55 65 75

As with the single dimensional arrays, each


dimension of the array is indexed from zero to its
maximum size minus one; the first row element by a
constant ‘k’ and print the resultant matrix:
main ( ){
int m, n, i, j, matrix [10][10];
scanf (“%d %d, &m, &n); /*subscripts i&j */
scanf (“%d”, &K);
for (i=1; i<=m’ ++i)
for (j=1; j<=n; ++j){
scanf (“%d”, &matrix [i] [j]);

CDS
48
Unit II – Arrays, Strings & Storage classes

matrix [i] [j] * = K;


}
for (i=1; i<=m; ++i)
for (j=1; j<=n; ++j)
printf (“%d \t”, matrix[i] [j]);
}

First we read the matrix indices, m & n, and the


constant ‘K’ with which, we want to multiply each
and every element.

Then we read the two dimensional matrix by means


of two nested for loops. First we read the first row,
followed by second row and so on till m rows.

We follow the same pattern for printing the matrix.


However the matrix will not be printed in matrix
form.

To print it in matrix form, we have to modify the for


loops as shown:
for (i = 1; i < = m; ++i){
for (j = 1; j < = n; ++ j){
printf (“%d \t”, matrix [i,j]);
}
printf (“ \n”);
}
Now this would first print the first row separated by
tab spaces, then we print a newline with printf (“ \n”);
next we go for new iteration for printing the next row
and so on.

CDS
49
Unit II – Arrays, Strings & Storage classes

Programming problems
(1) Write a program using functions to add, and
multiply two matrices.

(2) Write a program to find the transpose of a


matrix.

(3) Write a program to find the sum of the squares of


the diagonal elements of a matrix of order m x
m.

Initialisation of two-dimensional Arrays


There are several ways of initialising two-
dimensional arrays:
(1) Static int mat [2][3] = {0, 0, 0, 2, 2, 2};
This would initialise the first row to zero and the
second row or two, i.e., initialisation is done row
wise.

(2) Another way of initialisation is:


static int mat [2] [3] = {{0,0,0}, {2,2,2,}};

(3) Still another way is


static int mat [2] [3] = {
{0,0,0}
{2,2,2}
};

If the values are missing in initialise, they are set to


zero by default.

CDS
50
Unit II – Arrays, Strings & Storage classes

When all the elements are to be initialised to zero, we


can write it as
static int m[3] [5] = {{0}, {0}, {0}};
Note that commas are needed to separate each row.

Note: C allows arrays of three or more dimensions.


The compiler defines the exact limit.

The general form of a multidimensional array is


type array-name [s1] [s2] [s3]...[sn];

Where is the size of the ith dimension.

Examples:
int abc [3] [5] [4];
int xyz [5] [4] [2];

The number of elements present in the array abc is (3


x 5 x 4 = 60) & in xyz is 40.

The other rules of multidimensional array remains the


same as those of two-dimensional array and one-
dimensional array.

CDS
51
Unit II – Arrays, Strings & Storage classes

Strings
A string is an array of characters.

(a) Reading and writing a string:


There are two ways of reading a string.
The first is using scanf( ) statement as follows:
char name [15];
scanf (“%S”, name);

The format specifications is %s and also note that for


reading strings, we don’t need to precede the variable
with ‘&’ operator or address operator.

With scanf function, it terminates its input on the first


white space it finds (white space like blanks, carriage
returns, form feeds etc.)

suppose if we have the declarations:


char first-name [15];
char last-name [15];
scanf (“%s %s”, first-name, last-name);

if we have the input as 'Sree Nidhi' then the first-


name would be assigned 'Sree' and last-name would
be assigned 'Nidhi'.

The second method of reading strings is using the


gets( ) function.

CDS
52
Unit II – Arrays, Strings & Storage classes

The gets() function is used to read a set of


alphanumeric characters from standard input until a
carriage return key typed.
The general format is
gets (variable-name);

Example:
#include <stdio.h>
main ( ){
char name [20];
gets (name);
}

On similar lines we can use printf and puts to write


strings onto the screen.

Example:
printf((“%s”, first-name);
would print the contents of the string first-name of
the screen.

Similarly puts (last name) would print the same.

(b) concatenating strings using strcat ( )


The strcat ( ) function joins two strings together. It
takes the following form:
strcat (string1, string2);
where string1 and string2 are character arrays.

When executed, string2 is appended to string1.

CDS
53
Unit II – Arrays, Strings & Storage classes

It does by removing the null character at the end of


string1 and placing string2 from there.

Suppose if we have the following declarations:


char str1 = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};
char str2 = {‘w’, ‘o’, ‘r’, ‘l’, ‘d’};
then strcat (str1, str2);

The result of str1 would be “helloworld”;

we can also have nesting of strcat functions:

Example:
strcat(strcat(str1, str2), str3);
The result would be str3 would be concatenated with
the concatenation of str1 and str2.

(C) copying one string to another


The general form is strcpy (string1, string2);
and assigns the contents of string2 to string1.

String2 can be a character array variable or a string


constant.

Example:
The statement strcpy (State, “Delhi”);
will assign the character constant “Delhi” to the
character array state, assuming that we have declared
the variable state as:
char state [15];

CDS
54
Unit II – Arrays, Strings & Storage classes

Similarly we can have,


strcpy(str1, str2);
would copy the contents of str2 to str1.

(D) Comparing two strings


The strcmp( ) function can be used to compare two
strings.
It takes the form:
strcmp (str1, str2);
where str1 and str2 can be variables or string
constants.

If the two strings are equal, then zero will be returned


by strcmp.

Otherwise, it remains the numeric difference between


the first non-matching characters in the strings.

Example:
strcmp(“their”, “there”);
will the return the difference between i & r in terms
of the ASCII value.

If the value is -ve, then str1 is alphabetically above


string2.

CDS
55
Unit II – Arrays, Strings & Storage classes

(E) Determining the length of the string


The function strlen( ) can be used to return the
number of characters present in a string.
The syntax is
n = strlen (str);
where n is an integer variable, which receives the
values of the length of the siring. The argument can
be a string variable or a string constant. The counting
ends at the null character.

Multidimensional character strings


A list of strings can be treated as a two dimensional
array of characters or a table of strings.

For instance we can have a character array branches


[10] [10] to store the 10 names of the branches each
of probably ten character log. This can be stored as:
static char branches [ ] [ ]{
“civil”,
“mechanical”,
“electronics”,
“computers”,
“IT”
}
then the branches[0] gives the name “civil”. Similarly
branches[3] gives “computers”. We can also access
the individual characters of the string by using
branches[i][j].

CDS
56
Unit II – Arrays, Strings & Storage classes

For instance branches[3][4] denotes the 5th character


in the 4th row (remember index starts from 0); so it
will give the character ‘4’.

Example:
Program to read two strings str1 and str2, compare
them, if they are not equal then concatenate str1 and
str2 and then copy str1 to str3.
#include <string.h>
main ( ){
char str [10], str2 [10], str3 [10];
scanf (“%s %s”, str1, str2);
if (strcmp (str1, str2) !=0){
strcat (str1, str2);
}
strcpy (str3, str1);
printf(“str1=%s, str2=%s, str3=%s”, str1, str2, str3);
}

CDS
57
Unit II – Arrays, Strings & Storage classes

Programming problems on arrays


(1) Write a program to extract a portion of a
character string and print the extracted string.

(2) Write a program to replace a particular word by


another word in a given string.

(3) Given two one-dimensional arrays A and B,


which are sorted. Write a program to merge
them into a single sorted array C.

(4) Write a program to read a text of characters and


count the number of lines, tabs, blank spaces,
words and characters.

(1) Write a program to read a line and count the


number of vowels and constants.

(6) Write a function to search for an element present


in an array and call this function from the
main program.

CDS
58

You might also like