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

Arrays

in
‘C’
Needs …

So far, our programs have been very limited because


we could assign only one value to one specific variable.
What we would like to do is to assign values to a whole
group of variables and manipulate the entire group of
data. For example, if you take 6000 readings in an
experiment and you want to calculate their average, it
would be ridiculous if you had to type in your ‘C’
program a statement such as:

avg = (x1 + x2 + x3 + x4 + x5 + . . . + etc )/6000


Needs …

Therefore, let's look at the problem from a


mathematical viewpoint and express it using a
mathematical equation:

This expression is much simpler to understand than


our first expression with the 6000 terms as it uses a
summation sign and a subscripted variable, xk.
Subscripted Variables

We have already learned how to implement a


summation in C, namely by using a loop
statement, but we have not yet learned how to
express something like an indexed variable or
subscripted variable in C.
Hence, we need to learn about 'arrays' which
are the computer equivalent of subscripted or
indexed variables.
Array Declaration

• In computer science an array is a data structure consisting


of a group of homogeneous elements that are accessed by
indexing or subscripting.
• An array is a series of elements of the same type placed in
contiguous memory locations that can be individually
referenced by adding an index/subscript to a unique
identifier.
• Like other variables an array needs to be declared so that
the compiler will know what kind of an array and how
Array Declaration

• One-Dimensional Array Declaration:


Where each sizei
<data_type> array_name1 [size1], (i=1,2,3…, n) is an
array_name2 [size2],unsigned positive
integer constant.
…… array_namen [sizen]It; can not be a
variable.
For example the declaration:
• float mydata[ 5000 ];
sets aside sufficient memory for 5000 members of an array
called 'mydata'. Each member of the array is type 'float'.
Each individual member of the array can be accessed by
Accessing the elements of an array

Each element is taking 4 bytes

To assign a value to the 3rd element of the above declaration,

we write: e.g. numbers[2] = 23;


To access and display the same value, we write:

printf(“%d”, numbers[2]);
Create an array of 10 integers, store 10
numbers to them. Then display them.
void main()
{ /* Create and Reading part */
int no[10], index;
printf(“Enter 10 numbers\n”);
for( index = 0; index < 10; index ++ )
{
printf (“Number-%d”, index + 1);
scanf(“%d”, & no[ index ]);
}
Pgm contd…

printf(“Numbers are \n”); /* Display part */


for( index = 0; index < 10; index ++ )
{
printf (“%d\n”, no[ index ] );
}
} /* end of main() */
Output
Enter 10 numbers Numbers are
Number-1: 12 12
Number-2: 13 Users Entry 13
Number-3: 34 34
…. …
Arrays and Addresses
In the following array, the name number identifies the
address of the area of memory where your data is stored,
and the specific location of each element is found by
combining this with the index value, because the index value
represents an offset of a number of elements from the
beginning of the array.
long number[4];
When you declare an array, you give the compiler all the
information it needs to allocate the memory for the array.
You tell it the type of value, which will determine the
number of bytes that each element will require, and how
many elements there will be. The array name identifies
where in memory the array begins.
An index value specifies how many elements from
the beginning you have to go to address the element
you want. The address of an array element is going
to be the address where the array starts, plus the
index value for the element multiplied by the
number of bytes required to store each element of
the type stored in the array. Following Figure
represents the way that array variables are held in
memory.
You can obtain the address of an array element in a
fashion similar to ordinary variables. For an integer
variable called value, you would use the following
statement to print its address:
printf("\n%p", &value);
To output the address of the third element of an
array called number, you could write the following:
printf("\n%p", &number[2]);
The following fragment sets the value of the elements in an
array and outputs the address and contents of each
element:
int data[5];
for(int i = 0 ; i<5 ; i++)
{
data[i] = 12*(i+1);
printf("\ndata[%d] Addr: %p Content: %d", i, &data[i], data[i]);
}
The for loop variable i iterates over all the legal index values
for the data array. Within the loop, the value of the element
at index position i is set to 12*(i+1). The output statement
displays the current element with its index value, the
address of the current array element determined by the
current value of i, and the value stored within the element.
Initializing a 1-Dim Array
To initialize the elements of an array, you just specify
the list of initial values between braces and
separated by commas in the declaration
<data_type> array_name [ size ] = { val1, val2, … };

Size may be optional, if Number of values


ignored size will may be equal or
automatically be set to the less to the size of
number of values supplied. the array
e.g.
double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
int num[ ] = { 34, 67, 77, 89 }; Unsized Array, size set to 4
char text[5]={ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ };
examples
text ‘a‘ ‘b’ ‘c’ ‘d’ ‘e’

char t[10] = { ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ };


t ‘a‘ ‘b’ ‘c’ ‘d’ ‘e’ Unused space
char s[ ] = { ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ };
s ‘a‘ ‘b’ ‘c’ ‘d’ ‘e’
char str[ ] = “comp”;
str ‘c‘ ‘o’ ‘m’ ‘p’ ‘\0’
char st[ ] = { ‘c’ , ‘o’ , ‘m’ , ‘p’ , ‘\0’ };
st ‘c‘ ‘o’ ‘m’ ‘p’ ‘\0’
int num[10] ={ 12, 34, 56, 76, 8, 33 };
num 12 34 56 76 8 33 Unused space
char st[ ] ={ ‘a’ , ‘b’ , ‘c’ }; examples
printf(“%c%c%c”, st[0], st[1], st[2]);
Output abc
char st[ ] ={ ‘a’ , ‘b’ , ‘c’ };
printf(“%s”, st );
Output abcÅ Unwanted symbol
%s in printf searches a nul character
( \0 ) from the starting address
designated by the array variable (st).
printf() function displays all the
characters until it gets a nul
character.
char st[ ] ={ ‘a’ , ‘b’ , ‘c’, ‘\0’ }; examples
printf(“%s”, st );
Output abc
char st[ ] = “abc”;
printf(“%s”, st );
Output abc
char st[4] = "comp" , s[4] = "uter" ;
clrscr ();
printf ("%s" , s );
Output utercomp
n-Dim Array Declaration

• Multi-Dimensional Array Declaration:


<data_type> array_name1 [size1] [size2]. . . [sizer],
array_name2 [size1] [size2]. . .
[sizer],
…… array_namen [size1] [size2]. . .
[sizer];

For example the declaration:


• int no[3] [4];
Creates an array of 3 x 4 = 12 consecutive memory slots.
0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3
Each member of the array is type ‘int'.
int numbers[3][5]

Organization of a 3 × 5 element array in memory


Read marks in 3 subjects of 10 students in a class.
Display the total and average marks of each student.
int marks[10][3], sub, stud; /* Declaration
*/
/* Reading */
for( stud = 0; stud < 10; stud ++)
{
printf(“Enter Marks for sudent-%d \n ”, stud +1);
for( sub = 0; sub < 3; sub ++)
{
scanf( “%d”, &marks [stud] [sub] );
}
Initializing Multidimensional Arrays

Let’s first consider how you initialize a two-dimensional


array. The basic structure of the declaration, with
initialization, is the same as you’ve seen before, except that
you can optionally put all the initial values for each row
between braces {}:
int numbers[3][4] = {
{ 10, 20, 30, 40 }, /* Values for first row */
{ 15, 25, 35, 45 }, /* Values for second row */
{ 47, 48, 49, 50 } /* Values for third row */
};
int numbers[2][3][4] = {
{ /* First block of 3 rows */
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 }
},
{ /* Second block of 3 rows */
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 }
}
};
char text [3] [5] = {
{ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘\0’ },
{ ‘x’ , ‘y’ , ‘z’ , ‘\0’ },
{ ‘m’ , ‘n’ , ‘\0’ }
};
Is equivalent to
char text [3] [5] = { “abcd” , “xyz” , “mn” };

a b c d \0 x y z \0 m n \0

Unused slots
Unsized double dimensional array

int num[ ][6] = {


{1 , 2 , 3 , 4} ,
{11 , 22 , 33 , 44 },
{5 , 6 , 7 , 8 , 9 , 10}
};
1st dimension size
automatically set to
number of grouping
i.e. 3
Examples Sized and Unsized double
dimensional array
int first[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

int second[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8,


9,10,11}}; /* a clearer definition than the first */

int third[][5] = {0,1,2,3,4};


/* third[] only has one index of 1 */

int fourth[][6] = {0,1,2,3,4,5,6,7,8,9,10,11};


/* fourth[] has 2 indices - 0 or 1 */
Declare array to store:
• Single NAME which can hold a maximum of 50
characters
– char NAME [50];
• 10 names each capable to store a maximum of
20 characters.
– char names[10][20];
• 3 marks of 5 toppers each from 4 classes.
– int marks[4][5][3];

You might also like