Anda di halaman 1dari 40

Week 9, 10

Arrays (one-dimensional and twodimensional)

ONE-DIMENSIONAL ARRAYS

Arrays
An array is like a large data variable that can store multiple data items of
the same type.
Arrays are a series of elements (variables) of the same type placed
consecutively in memory that can be individually referenced by adding
an index to a unique name.

X
X[0]

Each individual
element is referred to by
the array name and the
subscript (or index).
Index starts with 0 and ends
with is the size-1;

The ith element is referred to by X[i-1]

Arrays
We can store 5 values of type int without having to declare 5 different
variables each one with a different identifier. Instead of that, using an
array we can store 5 different values of the same type, int for example,
with an unique identifier.
Example: Use an array called Arr to contain 5 integer values of type int.

Arr
int
The cells are numbered from 0 to 4 since in arrays the first index is
always 0, independently of its length .

Declaration of Array variables


A typical array declaration in C is as follows:
type name [elements];
Example:
int X[10]; // Array X will contain 10 elements of integer
type. The elements will be X[0] to X[9]
We can have arrays of any type and dimension:
Example: char X[20]
float Y[50]
double Z[10]
NOTE: The elements field within brackets [] when declaring
an array must be a constant value, since arrays are blocks of
static memory of a given size and the compiler must be able to
determine exactly how much memory must assign to the array
before any instruction is considered.
5

Initialising Arrays (1)


When declaring an array of local scope (within a function), if we
do not specify otherwise, it will not be initialized. So, its content is
undetermined until we store some values in it.
If we declare a global array (outside any function) its contents will
be initialized with all its elements filled with zeros. Thus, if in the
global scope we declare int billy [5] :

billy

0
0

1
0

2
0

3
0

4
0

int
But additionally, when we declare an Array, we have the possibility to assign initial
values to each one of its elements using curly brackets { }.
Example:
int billy [5] = { 16, 2, 77, 40, 12071 };
6

Initialising Arrays (2)


The number of elements in the array that we initialized within
curly brackets { } must match the length in elements that we
declared for the array enclosed within square brackets [ ].
Example: int array1 [5] = { 16, 2, 77, 40, 12071};
Because this can be considered an useless repetition, C++ includes
the possibility of leaving empty the brackets [ ], being the size of the
Array defined by the number of values included between curly
brackets { }:
Example: int array2 [] = { 16, 2, 77, 40, 12071};

Input/Output of array elements (1)


Exercise: Write a program to input values into all elements of an
integer array A of size 10 and display back the values.
#include <stdio.h>
int main()
{
int A[10];
int i;
printf("Enter 10 integer values: ");
for (i=0; i<10; i++)
scanf("%d",&A[i]);
/*Displaying back the values */

To read and write in an


array, we make use of a
loop

printf("Elements input are: ");


for (i=0; i<10; i++)
printf("%d ",A[i]);
printf("\n");
return 1;
}

Input/Output of array elements (2)


Exercise: Write a program to input values into all elements of an
integer array A of size 10 and display back the values in reverse
order.

Solution
#include <stdio.h>
int main()
{
int A[10];
int i;
printf("Enter 10 integer values: ");
for (i=0;i<10;i++)
scanf("%d",&A[i]);
/*Displaying back the values */
printf("Elements input (in reverse order): ");
for (i=0;i<10;i++)
printf("%d,",A[9-i]);
printf("\n");
//for (i=9;i>=0;i--)
// printf("%d, ", A[i]);
//printf("\n");
return 1;
}

10

Input/Output of array elements (3)


Exercise: Write a program to input an integer n (n<=10) value followed by n
real-numbers into an array A of size 10 and display the maximum value
stored as well as the position where it is stored in the array .

11

Solution
#include <stdio.h>
int main()
{
int i;
float A[10];
int maxposn;
float max;
printf("Input 10 integer numbers:
", n);
maxposn=0;
max=0;

for (i=0;i<n;i++)
{
scanf("%f",&A[i]);
if(i==0)
max=A[i];
else
if (A[i]>max)
{
max=A[i];
maxposn=i;
}
}
printf("largest is %.2f at posn
%d\n", max, maxposn);
}

12

Array of characters (1)


Character arrays can be treated in a similar way to arrays of integers and
real numbers.
Example: char x[20]
Each element can be input as follows:
for (i=0; i <20;i++)
scanf("%c", &x[i]);
Each element can be accessed/output separately:
for (i=0; i < 20;i++)
printf(%c, x[i]);

13

Arrays of characters (2)


With the declaration char x[20], the array
x can contain a string of characters.
But a string contains \0 as the last character
Reading a string:
char x[20];
scanf("%s",x);
After reading the characters (must be less than 20), a \0 will be
appended at the end.
NOTE: It will stop input when a space is encountered or end of line is
encountered.

Displaying the value of x:


printf(%s,x);

14

Exercise - Write a program to input the name of a person


and display the number of vowels in the name.

15

Solution
#include <stdio.h>
int main()
{
char name[20];
char ch;
int i,count;
count = 0;
printf("Input name: ");
scanf("%s", name);
i=0;
while ((name[i]!='\0') && (i<20))
{ ch=name[i];
if ((ch=='A') || (ch=='E')|| (ch=='I') ||(ch=='O')|| (ch=='U'))
count++;
i++;
}
printf("No. of vowels is %d\n",count);
return 1;
}
16

Strings/Array of characters (2)


Initialization of strings:
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
The above example shows a string of characters (array) of 6
elements of type char initialized with the characters that compose
Hello plus a null character '\0'.
Nevertheless, string of characters have an additional way to
initialize its values: using constant strings:
Example:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
In both cases the Array or string of characters mystring is
declared with a size of 6 characters (elements of type char): the 5
characters that compose Hello plus a final null character ('\0')
which specifies the end of the string. However, in the second case,
when using double quotes ("), the null character
it is
17
automatically appended.

Strings/Array of characters (3)


Note:
We can "assign" a multiple constant to an Array only at the
moment of initializing it, that is, at the moment it is being
declared.
The following examples are invalid:
astring = "Hello";
astring[] = "Hello";
astring = { 'H', 'e', 'l', 'l', 'o', '\0' };
However, the following is valid:
char astring[10] ;
astring[0] = 'H';
astring[1] = 'e';
astring[2] = 'l';
astring[3] = 'l';
astring[4] = 'o';
astring[5] = '\0;

18

Strings/Array of characters (4): string.h


#include<string.h>
can be used to access string manipulation functions
e.g char name[]=John, x[5];

Useful functions are:


strlen
Int L;
L=strlen(name);

strcpy
strcpy(x,name);

strcmp
if(strcmp(name,x)==0)
printf(same\n);
else
printf(not same\n);

19

Strings/Array of characters (5): string.h


#include <stdio.h>
#include <string.h>
int main()
{
char name1[20], name2[20],
tmp[20];
int i,L1,L2;

printf("Input name1: ");


scanf("%s",name1);
L1=strlen(name1);

printf("name1=%s, length is %d\n", name1,L1);


printf("name2=%s, length is %d\n", name2,L2);
strcpy(tmp,name1);
printf("tmp=%s, length is %d\n",
name1,strlen(tmp));
if(strcmp(name1,tmp)==0)
printf("same\n");
else
printf("not same\n");
return 1;
}

printf("Input name2: ");


scanf("%s",name2);
L2=strlen(name2);
20

Arrays as Parameters to functions (1)


Arrays can also be parameters to functions
The following should however be noted:
The dimension of the array should not be included
in the function declaration and the prototype
When a whole array is a parameter it always
behaves as a reference parameter.
Example: void procedure (int arg[])
Example: int myarray [40];
A typical function call for where this array is being
passed as parameter is:
procedure (myarray);
21

Arrays as Parameters to functions (2)


// Example of using arrays as parameters
# include <stdio.h>
void printarray (int arg[], int length);
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}
void printarray (int arg[], int length)
{
int n;
for (n=0; n<length; n++)
printf("%d ",arg[n]);
printf("\n");
}

22

TWO-DIMENSIONAL ARRAYS

23

Two-Dimensional Arrays (1)


Two dimensional arrays can be used to
manipulate tables, and are defined as
follows:
<type> <array_name>[dimesion1][dimension2];

Example
int a[3][4];
We have defined a table with 3 rows and 4
columns

24

Two-dimensional arrays (2)

The elements of a may be shown as a


table, as follows
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]

25

Two-dimensional arrays (3) - Rows

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

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

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

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

row 0
row 1
row 2

26

Two-dimensional arrays (4) - Columns

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

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

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

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

column 0 column 1 column 2 column 3

27

Two-dimensional arrays (5) - Example


Consider
int M[5][3];

Inputting values in array table:


for(row=0;row<5;row++)
{
printf(3 numbers for Row %d : ",(row+1));
for(col=0;col<3;col++)
scanf("%d",&M[row][col]);
}
28

Two-Dimensional Arrays (2)


Outputting values of array table:
for (x=0; x<5; x++)
{
for(y=0;y<3;y++)
printf("%d\t",M[x][y]);
printf("\n");
}
29

Two-dimensional arrays as parameters to functions (1)

When we pass a two dimensional array as


a parameter to a function, the value of the
first dimension is ignored(as for onedimensional arrays) but the value of the
second dimension has to be specified

30

Two-dimensional arrays as parameters to functions (2)


void printarray (int arg[][3], int rows)
{
int x, y;
for (x=0; x<rows; x++)
{
for(y=0;y<3;y++)
printf("%d\t",arg[x][y]);
printf("\n");
}
printf("\n");
}
31

Two-dimensional arrays as parameters to functions (3)


A program calling a function that takes as parameter a two-dimensional array

#include <stdio.h>
void printarray (int arg[][3], int rows);
int main ()
{
int M[5][3];
int row,col;
for(row=0;row<5;row++)
{
printf("3 numbers for Row %d : ",(row+1));
for(col=0;col<3;col++)
scanf("%d",&M[row][col]);
}
printarray(M,5);
return 1;
}
32

Arrays An additional note


Since arrays are always passed as
reference parameters to functions,
We can write functions to input values in an
array

33

Arrays A simple program with functions to input and


output elements in one-dimensional arrays
#include <stdio.h>
void inputarray(int arg[], int length);
void printarray (int arg[], int length);
int main ()
{
int firstarray[3];
int secondarray[5];
printf("Input details for firstarray\n");
inputarray(firstarray,3);
printf("Input details for secondarary\n");
inputarray(secondarray,5);
printf("firstarray contains: ");
printarray (firstarray,3);
printf("secondarray contains: ");
printarray (secondarray,5);
return 0;
}

void inputarray(int arg[], int length)


{
int i;
printf("\tInput %d values: ", length);
for(i=0;i<length;i++)
scanf("%d",&arg[i]);
printf("\n");
}
void printarray (int arg[], int length)
{
int n;
for (n=0; n<length; n++)
printf("%d ",arg[n]);
printf("\n");
}

34

Arrays A simple program with functions to input and


output elements in a two-dimensional array
#include <stdio.h>
void inputarray(int arg[][3], int rows);
oid printarray (int arg[][3], int rows);
int main ()
{
int M[5][3];
inputarray(M,5);
printarray(M,5);
return 1;
}
void inputarray(int arg[][3], int rows)
{
int row,col;
for(row=0;row<rows;row++)
{
printf("3 numbers for Row %d : ",(row+1));
for(col=0;col<3;col++)
scanf("%d",&arg[row][col]);
}
}

void printarray (int arg[][3], int rows)


{
int x, y;
for (x=0; x<rows; x++)
{
for(y=0;y<3;y++)
printf("%d\t",arg[x][y]);
printf("\n");
}
printf("\n");
}

35

Class Exercise
Write a program that declares a 2dimensional array to store marks for 15
students, in 6 modules for each student. The
program also declares a 1-dimensional array
to store average marks (in 6 modules) for 15
students.
Make use of functions:
To input marks of 15 students in six modules
To output marks of 15 students in six modules
To output average marks of students

In the function main(), calculate the average


marks and store in corresponding array.
36

void input(float M[][6], int num)


{
int row,col;
for(row=0;row<num;row++)
{
printf("Marks for Student %d : ",(row+1));
for(col=0;col<6;col++)
scanf("%f",&M[row][col]);
}
}
37

void output(float M[][6], int num)


{
int row,col;
for(row=0;row<num;row++)
{
printf("Marks for Student %d : ",(row+1));
for(col=0;col<6;col++)
printf("%.2f ",M[row][col]);
printf("\n");
}
}
38

void output_average(float A[], int num)


{
int x;
for(x=0;x<num;x++)
{
printf("Average for student %d: ",(x+1));
printf("%.2f\n",A[x]);
}
}
39

# include <stdio.h>
for(x=0;x<15;x++)
{
sum=0;
for(y=0;y<6;y++)
sum=sum+Marks[x][y];
Avg[x]=sum/6;
}

void input(float M[][6], int num);


void output(float M[][6], int num);
void output_average(float A[], int
num);
int main()
{
float Marks[15][6];
float Avg[15];
int x,y;
float sum;
input(Marks,15);
output(Marks,15);

output_average(Avg,15);
return 1;
}

40

Anda mungkin juga menyukai