Array Teach

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

PROG0101 Fundamentals of Programming

Unit 3:
Array

1
Suppose you have a long list of numbers, but you don’t want
to assign them to variables individually.
For example, you are writing a simple program for a restaurant
to keep a list of the amount each diner has, but you don’t want
to write a list like:

float joe, betty, charls…;


Joe = 88.33;
Betty = 17.23;
charls = 55.55; etc.

A list like that could


run to hundreds or
thousands of entries.
Array in C
That is why arrays were invented:
Arrays are a convenient way to group many variables under
a single variable name.
An array is a variable that can store multiple values.

Array can be:


1. one-dimensional like a list
2. two-dimensional like a chessboard
3. three-dimensional like an apartment building
4. or can have any arbitrary dimensionality, including ones
humans can't visualise easily.
Declaring Arrays
To declare an array in C, a programmer specifies the type of
the elements and the number of elements required by an array
as follows −

This is called a single-dimensional array. The arraySize must


be an integer constant greater than zero and type can be any
valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
An array is defined using square brackets [ ]

Declaration of array: array of 3 integers called my_array


would be declared as:
int my_array[3]; // no space between name of array and ‘[’.

This statement would cause space for three adjacent


integers to be created in memory as:
my_array:

Three integer in the above array are called its locations


Values filling them are called the array’s elements.
The position of an element in the array is called its
index (the plural is indices).
Arrays in C are zero-based, so the indices of array run (0, 1, 2)

int my_array[3];
my_array[0] = 5;
my_array[1] =
17;
my_array[2] =
23;

In this example, 5, 17, and 23 are the array’s elements, and 0, 1, and 2 are
its corresponding indices.
The above example would result in an array like:

Index:
my_array:

Note that every element in an array must be of the same type, for
example, integer. It is not possible in C to have arrays that contain multiple
Array bounds
The code below defines an array with 9 elements (C arrays are zero-
based.) : char my_array[9];
The first and last positions in an array are called its bounds.
Remember that the bounds of an array are zero and the integer that
equals the number of elements it contains, minus one.
In C’s, the compiler does not complain if you try to write to elements of
an array that do not exist(i.e. if you exceed the bounds of an array), the
debugger can tell you at run-time.
Initializing Arrays
You can initialize an array in C either one by one or using a
single statement as follows −

The number of values between braces { } cannot be larger


than the number of elements that we declare for the array
between square brackets [ ].
If you omit the size of the array, an array just big enough to
hold the initialization is created. Therefore, if you write −
You will create exactly the same array as you did in the
previous example. Following is an example to assign a single
element of the array −

The above statement assigns the 5th element in the array with a
value of 50.0. All arrays have 0 as the index of their first
element which is also called the base index and the last index
of an array will be total size of the array minus 1.
We can initialize each element of the array one by one using the
index.
Consider the following example.
int marks[5];
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example
Example: Sorting an Array
Arrays and for loops
When you declare an array, the computer allocates a block of
memory for it, but the allocated block contains garbage
(random values).
So, before using an array, you should initialise it. The
easiest way to initialise an array is with a for loop.
It is usually a good idea to set all elements in the array to
zero.
my_array[index] = 0;

You can also fill the array with different values.


my_array[index] = index;
this fills each element of the array with its own index:
● s

Output: my_array[0] = 0
my_array[1] = 0
my_array[2] = 0
my_array[3] = 0
my_array[4] = 0
Multidimensional arrays
These are Arrays with more than one dimension.
Suppose that you are writing a chess-playing program. A chessboard
is an 8-by-8 grid. What data structure would you use to represent it?
You could use an array that has a chessboard-like structure, that is, a
two-dimensional array, to store the positions of the chess pieces.
You can declare an array of two dimensions as follows:
variable_type array_name[size1][size2]
Example: int chessboard[8][8];

Two-dimensional arrays use two indices to pinpoint an individual


element of the array.
Two-dimensional Arrays
The simplest form of multidimensional array is the two-
dimensional array.
A two-dimensional array is, in essence, a list of one-
dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you
would write something as follows −

Where type can be any valid C data type and arrayName will
be a valid C identifier.
A two-dimensional array can be considered as a table which
will have x number of rows and y number of columns. A two-
dimensional array a, which contains three rows and four
columns can be shown as follows −

Thus, every element in the array a is identified by an element


name of the form a[ i ][ j ], where 'a' is the name of the array,
and 'i' and 'j' are the subscripts that uniquely identify each
element in 'a'
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying
bracketed values for each row. Following is an array with 3
rows and each row has 4 columns.

The nested braces, which indicate the intended row, are


optional. The following initialization is equivalent to the
previous example −
Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using


the subscripts, i.e., row index and column index of the array.
For example −
Arrays and nested loops
To initialize multidimensional arrays, you can use
nested for loops.

The last index is always the one that varies fastest


(then the next-to-last, and so on).

In the example output, you can see that the column


index changes every line, while the row index changes
every three lines.
Example:
Properties of Array
The array contains the following properties.

1. Each element of an array is of same data type and carries


the same size, i.e., int = 4 bytes.
2. Elements of the array are stored at contiguous memory
locations where the first element is stored at the smallest
memory location.
3. Elements of the array can be randomly accessed since we
can calculate the address of each element of the array.
Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve


the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need


a few lines of code only.

4) Random Access: We can access any element randomly


using the array.
Ist no=0
2nd no=1
3rd no=(0+1)=1
4th no=1+1=2
5th no=2+1=3
6th no=3+2=5
011235
1
23
456
7 8 9 10
Strings and Character array in C
String is a sequence of characters that is treated as a single
data item and terminated by null character '\0' .

C language does not support strings as a data type. A string is


actually one-dimensional array of characters in C language.
These are often used to create meaningful and readable
programs.

For example: The string "hello world" contains 12 characters


including '\0' character which is automatically added by the
compiler at the end of the string.
Declaring and Initializing a string variables

There are different ways to initialize a character array variable.

Remember that when you initialize a character array by listing


all of its characters separately then you must supply the ‘\0’
character explicitly.

Some examples of illegal initialization of character array are,


String Input and Output

Input function scanf() can be used with %s format specifier to


read a string input from the terminal.
But there is one problem with scanf() function, it terminates its
input on the first white space it encounters. Therefore if you try
to read an input string "Hello World" using scanf() function, it
will only read Hello and terminate after encountering white
spaces.

However, C supports a format specification known as the edit set


conversion code %[..] that can be used to read a line containing
a variety of characters, including white spaces.
Another method to read character string with white spaces from
terminal is by using the gets() function.
String Handling Functions
• C language supports a large number of string handling functions that
can be used to carry out many of the string manipulations. These
functions are packaged in string.h library.
• You must include string.h header file in your programs to use these
functions.
• The following are the most commonly used string handling functions.

You might also like