0% found this document useful (0 votes)
7 views

Array

Array in c

Uploaded by

Imran Hossen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Array

Array in c

Uploaded by

Imran Hossen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

C ARRAY

ARRAY
Variable with
Multiple
Elements
What is variable?

Data_type Variable_name;
10 First Element

20

30

40

50

60
Last Element
• Arrays
– Declaration
– Initialization
– Input/Output
– Passing arrays to functions

6
Declaring Array

Data_type arrayName [ arraySize ];

• This is called a single-dimensional array.

• The arraySize must be an integer constant


greater than zero.

• Data_type can be any valid C data type.


Declaring Array
• For example, to declare a 10- element array
called balance of type double, use this
statement:

double balance[10];

• Now balance is a variable array which is


sufficient to hold up-to 10 double numbers.
Arrays
• A group of contiguous memory locations
used to store a series of related values
• The array name is a pointer to the first
element
• All values have the same type
• Individual elements of an array are
accessed via an integer index:
array[index]
• Element indices start at 0, array[0] is
the first element

9
Initializing Arrays
• Arrays may be initialized with a list of suitable
values
• No need to specify the number of elements for a
1D (1-dimensional) array

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

10
Accessing Array Elements

0 1 2 3 4
balance 1000.00 2.0 3.4 17.00 50.00
Accessing Array Elements
• An element is accessed by indexing the array
name. This is done by placing the index of the
element within square brackets after the name
of the array.
balance[0]=1000.00;
balance[1]=2.00;
balance[2]=3.4;
balance[3]=17.00;
balance[4]=50.00;
double salary = balance[0];
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Example: MonthlyRainfall
Problem: using month mean rainfall (in mm)
0 30
Rainfall Table 1 40
• input month 2 45
• output mean 3 95
rainfall for that 4 130
5 220
month 6 210
7 185
8 135
9 80
10 40
11 45
Rainfall Table

16
Example (cont): MonthlyRainfall (v.1)
#include <stdio.h>

int main()
{
int month;
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };

printf("Enter month: ");


scanf("%d", &month);

printf("Average rainfall: %d mm.\n", table[month-1]);

return 0;
} rainfall1.c

17
Example (cont): MonthlyRainfall (v.1)
#include <stdio.h>

int main()
{
int month;
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };

printf("Enter month: ");


scanf("%d", &month);

printf("Average rainfall: %d mm.\n", table[month-1]);

return 0;
} rainfall1.c

18
Input / Output of Arrays
• Library functions printf() and scanf() do not
know about arrays
So we have to do I/O ourselves

19
Example: IORainfall-1
#include <stdio.h>
#define NMONTHS 12

/* Store and print rainfall */

int main()
{
int data[NMONTHS];
int month;

for ( month=0; month < NMONTHS; month++ )


{
scanf("%d", &data[month] );
}

... rainio1.c

20
Example (cont): IORainfall-1
#include <stdio.h>
#define NMONTHS 12

/* Store and print rainfall */

int main()
{
int data[NMONTHS];
int month;

for ( month=0; month < NMONTHS; month++ )


{
scanf("%d", &data[month] );
}

... rainio1.c

21
Example (cont): IORainfall-2 (v.1)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
rainio1.c
return 0;
}
22
Example (cont): IORainfall-2 (v.1)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
return 0;
} rainio1.c

23
Example (cont): IORainfall-2 (v.2)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%5d ” , data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%5d ” , data[month] );
}
printf("\n");

return 0;
} rainio2.c
24
Handling Indices
• Arrays have a fixed size
• There is no built-in way of checking if the
supplied index is within range
• We must check for valid indices ourselves

25
Passing Arrays to Functions

• The array is passed


– as an array of unspecified size (int array[])
OR
– as a pointer (int *array)
• Changes to the array within the function
affect the “original” array

26
Example (cont): IORainfall-1 (v.3)

#include <stdio.h>
#define NMONTHS 12

void loadRain ( int arrayPtr[] )


{
int month;

for (month=0; month < NMONTHS; month++)


{
scanf("%d", &arrayPtr[month]);
}
}
rainio3.c

27
Example (cont): IORainfall-2 (v.3)

void printRain ( const int arrayPtr[] )


{
int month;

for (month=0; month < NMONTHS; month++)


{
printf("%5d", arrayPtr[month]);
}

printf("\n");
}
rainio3.c

28
Example (cont): IORainfall-3 (v.3)
#include <stdio.h>
#define NMONTHS 12

void loadRain ( int arrayPtr[] );


void printRain ( const int arrayPtr[] );

/* Store and print rainfall */


int main()
{
int data[NMONTHS];

loadRain(data);
printRain(data);

return 0;
}
rainio3.c

29
Example: IORainfall -- v.3 (cont)
#include <stdio.h>
#define NMONTHS 12
void loadRain ( int arrayPtr[] );
void printRain ( const int arrayPtr[] );
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
loadRain(data);
printRain(data);
return 0;
}
/* Read in rainfall for each month*/
void loadRain ( int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ scanf("%d", &arrayPtr[month]); }
}
/* Print rainfall for each month*/
void printRain ( const int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ printf("%5d", arrayPtr[month]); } rainio3.c
printf("\n");
} 30
Topics

• Two-dimensional arrays
• Passing two-dimensional arrays to
functions

31
Two-dimensional Arrays
• Each element of an array is like a single item of
a particular type
• But an array itself is an item of a particular type
So, an array element could be another array
• An “array-of-arrays” is called “multi-
dimensional” because you need to specify
several ordinates to locate an actual element

32
Example: YearlyRainfall
month

0 1 2 3 4 5 6 7 8 9 10 11
0 30 40 75 95 130 220 210 185 135 80 40 45
1 25 25 80 75 115 270 200 165 85 5 10 0
year

2 35 45 90 80 100 205 135 140 170 75 60 95


3 30 40 70 70 90 180 180 210 145 35 85 80
4 30 35 30 90 150 230 305 295 60 95 80 30
Average Yearly Rainfall (in mm)

Problem: using the Yearly Rainfall table


• input month and year
• output mean rainfall for that month and year
33
Example (cont): YearlyRainfall-1
#define NYEARS 5
#define NMONTHS 12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <= year) && (year < NYEARS) &&


(0 <= month) && (month < NMONTHS))
{
return table[year][month];
}
else
{
return -1; yearly1.c
}
} 34
Example (cont): YearlyRainfall-2
int main()
{
int year;
int month;
int rainfall;

printf("Enter year and month: ");


scanf("%d %d", &year, &month);

rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0; yearly1.c
}
35
Example (cont): YearlyRainfall-1
#define NYEARS 5
#define NMONTHS 12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <= year) && (year < NYEARS) &&


(0 <= month) && (month < NMONTHS))
{
return table[year][month];
}
else
{
return -1; yearly1.c
}
} 36
Example (cont) : YearlyRainfall-1
#define NYEARS 5
#define NMONTHS 12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <= year) && (year < NYEARS) &&


(0 <= month) && (month < NMONTHS))
{
return table[year][month];
}
else
{
return -1; yearly1.c
}
} 37
Example (cont): YearlyRainfall-2
int main()
{
int year;
int month;
int rainfall;

printf("Enter year and month: ");


scanf("%d %d", &year, &month);

rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;
}
yearly1.c
38
Example (cont): YearlyRainfall-2
int main()
{
int year;
int month;
int rainfall;

printf("Enter year and month: ");


scanf("%d %d", &year, &month);

rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;
}
yearly1.c
39
Example (cont): YearlyRainfall-2
int main()
{
int year;
int month;
int rainfall;

printf("Enter year and month: ");


scanf("%d %d", &year, &month);

rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;
}
yearly1.c
40
Passing Two-Dimensional Arrays to
Functions

• In the function definition, the size of the


array needs to be specified
• Any changes to array elements within the
function affect the ``original’’ array
elements

41
Example 2: 2-D Array-1
#include <stdio.h>

#define NROWS 3
#define NCOLS 5

void inputEntry(float table[][NCOLS]);


void printTable(float table[NROWS][NCOLS]);

int main()
{
float table[NROWS][NCOLS] = {{0}};

printTable(table);

while (1)
{
inputEntry(table);
printTable(table);
}
return 0;
}
twod2.c

42
Example 2 (cont): 2-D Array-1
#include <stdio.h>

#define NROWS 3
#define NCOLS 5

void inputEntry(float table[][NCOLS]);


void printTable(float table[NROWS][NCOLS]);

int main()
{
float table[NROWS][NCOLS] = {{0}};

printTable(table);

while (1)
{
inputEntry(table);
printTable(table);
}
return 0;
}
twod2.c

43
Example 2 (cont): 2-D Array-2
/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[NROWS][NCOLS] )
{
int row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
}
twod2.c
44
Example 2 (cont): 2-D Array-2
/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
}
twod2.c
45
Example 2 (cont): 2-D Array-2
/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
}
twod2.c
46
Example 2 (cont): 2-D Array-2
/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
}
twod2.c
47
Example 2 (cont): 2-D Array-3

/* Prints the table page-by-page, and each page


row-by-row */
void printTable ( float table[NROWS][NCOLS] )
{
int row, column;
for (row=0; row < NROWS; row++)
{
for (column=0; column < NCOLS; column++)
{
printf("%10.2f", table[row][column]);
}
printf("\n");
}
}
twod2.c

48
Example 2 (cont): 2-D Array-3

/* Prints the table page-by-page, and each page


row-by-row */
void printTable ( float table[NROWS][NCOLS] )
{
int row, column;
for (row=0; row < NROWS; row++)
{
for (column=0; column < NCOLS; column++)
{
printf("%10.2f", table[row][column]);
}
printf("\n");
}
}
twod2.c

49
QUESTIONS?
Array-Bounds Checking
• C, unlike many languages, does NOT check array bounds subscripts
during:
– Compilation (some C compilers will check literals)
– Runtime (bounds are never checked)
• If you access off the ends of any array, it will calculate the address
it expects the data to be at, and then attempts to use it anyways
– may get “something…”
– may get a memory exception (segmentation fault, bus error, core
dump error)
• It is the programmer’s responsibility to ensure that their programs
are correctly written and debugged!
– This does have some advantages but it does give you all the rope you
need to hang yourself!
Initializing Arrays
• Initialization of arrays can be done by a comma separated
list following its definition.
• For example:
int array [4] = { 100, 200, 300, 400 };
– This is equivalent to:
int array [4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
• You can also let the compiler figure out the array size for
you:
int array[] = { 100, 200, 300, 400};
A Simple Example
#include <stdio.h>
int main() {
float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9, 10.2, 11.5,
7.8};
int count,month;
float total;
for (month=0, total=0.0; month < 12; month++)
{
total+=expenses[month];
}
for (count=0; count < 12; count++)
printf ("Month %d = %.2f K$\n", count+1, expenses[count]);
printf("Total = %.2f K$, Average = %.2f K$\n", total, total/12);
return 0;
}
Multidimensional Arrays
• Arrays in C can have virtually as many
dimensions as you want.
• Definition is accomplished by adding
additional subscripts when it is defined.
• For example:
– int a [4] [3] ;
• defines a two dimensional array
• a is an array of int[3];
• In memory:
a[0][0] a[0][1] a[0][2]

a[0] a[1] a[2] a[3]


Initializing Multidimensional Arrays
• The following initializes a[4][3]:
int a[4] [3] = { {1, 2, 3} , { 4, 5, 6} , {7, 8, 9} , {10, 11, 12} };
• Also can be done by:
int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
– is equivalent to
a[0][0] = 1;
a[0][1] = 2; :D ^_^
a[0][2] = 3;
a[1][0] = 4;
...
a[3][2] = 12;
An Example
#include <stdio.h>
#include <stdlib.h>
int main () {
int random1[8][8];
int a, b;
for (a = 0; a < 8; a++)
for (b = 0; b < 8; b++)
random1[a][b] = rand()%2;
for (a = 0; a < 8; a++)
{
for (b = 0; b < 8; b++)
printf ("%c " , random1[a][b] ? 'x' : 'o');
printf("\n");
}
return 0;
}
The value of the array name
#include <stdio.h> for (i=0; i<3; i++) {
int main(){ printf( "a[%d] <- ",i);
int i; scanf( "%d", &a[i]);
int a[3] = { 1, 2, 3 }; }
printf( "a ? %d\n", a); printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ? %d\na[2] ? printf( "a[0] ? %d\na[1] ? %d\na[2] ?
%d\n", a[0], a[1], a[2]); %d\n", a[0], a[1], a[2]);
printf( "&a[0] ? %d\n&a[1] ? printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n", &a[0], %d\n&a[2] ? %d\n", &a[0],
&a[1], &a[2]); &a[1], &a[2]);
}
printf( "\na[0] <- 4 \n");
a[0] = 4; • When the array name is used
printf( "a ? %d\n", a); alone, its value is the address of
printf( "a[0] ? %d\na[1] ? %d\na[2] ? the array (a pointer to its
%d\n", a[0], a[1], a[2]); address).
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n\n", &a[0],
• &a has no meaning if used in this
&a[1], &a[2]); program.
Arrays as Function Parameters
• In this program, the array
addresses (i.e., the values of
the array names), are passed to void inc_array(int a[ ],int size);
the function inc_array(). main()
• This does not conflict with the {
rule that “parameters are int test[3]={1,2,3};
passed by values”. int ary[4]={1,2,3,4};
void inc_array(int a[ ], int size) int i;
inc_array(test,3);
{ for(i=0;i<3;i++)
int i; printf("%d\n",test[i]);
for(i=0;i<size;i++) inc_array(ary,4);
{ for(i=0;i<4;i++)
a[i]++; printf("%d\n",ary[i]);
return 0;
} }
}
An Example
void mysort(int a[ ],int size)
-- Sorting
int main()
{ {
int i,j,x; int i;
for(i=0; i<size; i++) int tab[10] = {3,6,3,5,9,2,4,5,6,0};
{
for(j=i; j>0; j--) for(i=0;i<10;i++)
{ printf("%d ",tab[i]);
if(a[ j ] < a[ j-1])
{ /* Change the order of a[ j ] and a[ printf("\n");
j-1] */ mysort(tab,10);
x=a[ j ];a[ j ]=a[ j-1]; a[j-1]=x;
} for(i=0;i<10;i++)
} printf("%d ",tab[i]);
}
} printf("\n");
return 0;
}

You might also like