44
1 1-d Arrays

1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics In mathematics, we often express such groups of

Embed Size (px)

Citation preview

Page 1: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

1

1-d Arrays

Page 2: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

2

Array

Many applications require multiple data items that have common characteristics In mathematics, we often express such groups

of data items in indexed form: x1, x2, x3, …, xn

Array is a data structure which can represent a collection of data items which have the same data type (float/int/char/…)

Page 3: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

3

int a, b, c;

scanf(“%d”, &a);

scanf(“%d”, &b);

scanf(“%d”, &c);

printf(“%d ”, c);

printf(“%d ”, b);

printf(“%d \n”, a);

int a, b, c, d;

scanf(“%d”, &a);

scanf(“%d”, &b);

scanf(“%d”, &c);

scanf(“%d”, &d);

printf(“%d ”, d);

printf(“%d ”, c);

printf(“%d ”, b);

printf(“%d \n”, a);

3 numbers4 numbers

Example: Printing Numbers in Reverse

Page 4: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

4

The Problem

Suppose we have 10 numbers to handle Or 20 Or 100 Where do we store the numbers ? Use 100

variables ?? How to tackle this problem? Solution:

Use arrays

Page 5: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

Printing in Reverse Using Arrays

void main(){ int n, A[100], i;

printf(“How many numbers to read? “); scanf(“%d”, &n); for (i = 0; i < n; ++i)

scanf(“%d”, &A[i]); for (i = n -1; i >= 0; --i)

printf(“%d ”, A[i]); printf(“\n”);}

Page 6: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

6

Using Arrays

All the data items constituting the group share the same name

int x[10]; Individual elements are accessed by

specifying the index

x[0] x[1] x[2] x[9]

X is a 10-element one dimensional array

Page 7: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

7

Declaring Arrays Like variables, the arrays used in a program must be

declared before they are used General syntax:

type array-name [size]; type specifies the type of element that will be contained

in the array (int, float, char, etc.) size is an integer constant which indicates the maximum

number of elements that can be stored inside the array

marks is an array that can store a maximum of 5 integersint marks[5];

Page 8: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

8

Examples: int x[10];

char line[80];

float points[150];

char name[35]; If we are not sure of the exact size of the array, we can define

an array of a large size

int marks[50];

though in a particular run we may only be using, say, 10 elements

Page 9: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

9

Accessing Array Elements A particular element of the array can be accessed by

specifying two things:Name of the array Index (relative position) of the element in the array

In C, the index of an array starts from zero Example:

An array is defined as int x[10];The first element of the array x can be accessed as

x[0], fourth element as x[3], tenth element as x[9], etc.

Page 10: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

10

Contd.

The array index must evaluate to an integer between 0 and n-1 where n is the maximum number of elements possible in the array a[x+2] = 25; b[3*x-y] = a[10-x] + 5;

Remember that each array element is a variable in itself, and can be used anywhere a variable can be used (in expressions, assignments, conditions,…)

Page 11: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

11

A first example

void main()

{

int i;

int data[10];

for (i=0; i<10; i++) data[i]= i;

i=0;

while (i<10)

{

printf("Data[%d] = %d\n", i, data[i]);

i++;

}

}

“data refers to a block of 10

integer variables, data[0], data[1],

…, data[9]

Page 12: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

12

The result

void main()

{

int i;

int data[10];

for (i=0; i<10; i++) data[i]= i;

i=0;

while (i<10)

{

printf("Data[%d] = %d\n", i, data[i]);

i++;

}

}

Data[0] = 0

Data[1] = 1

Data[2] = 2

Data[3] = 3

Data[4] = 4

Data[5] = 5

Data[6] = 6

Data[7] = 7

Data[8] = 8

Data[9] = 9

Array size should be a constant

Output

Page 13: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

13

How is an array stored in memory? Starting from a given memory location, the

successive array elements are allocated space in consecutive memory locations

x: starting address of the array in memory k: number of bytes allocated per array element

a[i] is allocated memory location at address x + i*k

Array a

Page 14: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

14

Storage

void main()

{

int i;

int data[10];

for(i=0; i<10; i++)

printf("&Data[%d] = %u\n", i, &data[i]);

}

&Data[0] = 3221224480

&Data[1] = 3221224484

&Data[2] = 3221224488

&Data[3] = 3221224492

&Data[4] = 3221224496

&Data[5] = 3221224500

&Data[6] = 3221224504

&Data[7] = 3221224508

&Data[8] = 3221224512

&Data[9] = 3221224516

Output

Page 15: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

15

Initialization of Arrays General form:

type array_name[size] = { list of values }; Examples:

int marks[5] = {72, 83, 65, 80, 76};

char name[4] = {‘A’, ‘m’, ‘i’, ‘t’}; The size may be omitted. In such cases the

compiler automatically allocates enough space for all initialized elements

int flag[ ] = {1, 1, 1, 0};

char name[ ] = {‘A’, ‘m’, ‘i’, ‘t’};

Page 16: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

16

How to read the elements of an array? By reading them one element at a time

for (j=0; j<25; j++)

scanf (“%f”, &a[j]);

The ampersand (&) is necessary

The elements can be entered all in one line or in

different lines

Page 17: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

17

Passing Arrays to Function

Array element can be passed to functions as ordinary arguments

IsFactor (x[i], x[0]) sin (x[5])

Page 18: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

18

Passing Entire Array to a Function

An array name can be used as an argument to a function Permits the entire array to be passed to the function The way it is passed differs from that for ordinary

variables Rules:

The array name must appear by itself as argument, without brackets or subscripts

The corresponding formal argument is written in the same manner

Declared by writing the array name with a pair of empty brackets

Page 19: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

19

Whole Array as Parametersconst int ASIZE = 5;float average (int B[ ]){

int i, total=0;for (i=0; i<ASIZE; i++)

total = total + B[i];return ((float) total / (float) ASIZE);

}

void main ( ) {int x[ASIZE] ; float x_avg;

x [] = {10, 20, 30, 40, 50};x_avg = average (x) ;

}

Only Array Name/address passed.

[ ] mentioned to indicate that

is an array.

Called only with actual array name

Page 20: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

20

Contd.void main(){ int n; float list[100], avg; : avg = average (n, list); :}

float average (int a, float x[]){ : sum = sum + x[i];}

We don’t need to write the array size. It works with arrays of any size.

Page 21: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

21

Arrays used as Output Parametersvoid VectorSum (int a[ ], int b[ ], int vsum[ ], int length) {

int i;for (i=0; i<length; i=i+1)

vsum[i] = a[i] + b[i] ;}void PrintVector (int a[ ], int length) {

int i;for (i=0; i<length; i++) printf (“%d “, a[i]);

}

void main () {int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3];VectorSum (x, y, z, 3) ;PrintVector (z, 3) ;

}vector-sum.c

Page 22: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

22

Reading into an arrayvoid main()

{

const int MAX_SIZE = 100;

int i, size;

float marks[MAX_SIZE];

float total=0;

scanf("%d",&size);

for (i=0; i<size; i++)

{

scanf("%f",&marks[i]);

total = total + marks[i];

}

printf("Total = %f \n Avg = %f\n", total, total/size);

}

4

2.5

3.5

4.5

5

Total = 15.500000

Avg = 3.875000

Output

Page 23: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

23

A Warning

In C, while accessing array elements, array bounds are not checked

Example:int marks[5];::marks[8] = 75;

The above assignment would not necessarily cause an error

Rather, it may result in unpredictable program results

Page 24: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

24

How to copy the elements of one array to another?

By copying individual elements

for (j=0; j<25; j++)

a[j] = b[j];

The element assignments will follow the rules

of assignment expressions

Destination array must have sufficient size

Page 25: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

25

Example 1: Find the minimum of a set of 10 numbers

void main(){ int a[10], i, min;

for (i=0; i<10; i++) scanf (“%d”, &a[i]);

min = a[0]; for (i=1; i<10; i++) { if (a[i] < min) min = a[i]; } printf (“\n Minimum is %d”, min);}

Page 26: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

26

Example 2:Computing

cgpa

const int nsub = 6;

void main(){ int grade_pt[nsub], cred[nsub], i, gp_sum=0, cred_sum=0; double gpa;

for (i=0; i<nsub; i++) scanf (“%d %d”, &grade_pt[i], &cred[i]);

for (i=0; i<nsub; i++) { gp_sum += grade_pt[i] * cred[i]; cred_sum += cred[i]; } gpa = ((float) gp_sum) / cred_sum; printf (“\n Grade point average: is %.2lf”, gpa);}

Handling two arraysat the same time

Page 27: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

27

Things you cant do

You cannotuse = to assign one array variable to another

a = b; /* a and b are arrays */use == to directly compare array variables

if (a = = b) ………..directly scanf or printf arrays

printf (“……”, a);

Page 28: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

28

Recall

Page 29: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

29

Recall

Page 30: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

Recall

30

Page 31: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

x=a++ - ++a;

Right to left evaluation of the expression.

First update (rightmost) a to 11.

Leftmost a =>11

x=0

a=12

31

Page 32: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

Revisit loops

32

Page 33: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

33

SUM = 12 + 22 + 32 + …+ N2

Page 34: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

34

SUM = 12 + 22 + 32 + …+ N2

void main() { int N, count, sum; scanf (“%d”, &N) ; sum = 0; count = 1; while (count <= N) { sum = sum + count count; count = count + 1; } printf (“Sum = %d\n”, sum) ; return 0;}

Page 35: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

35

Maximum of positive Numbers

Page 36: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

36

Maximum of positive Numbers

void main() {

double max = 0.0, next;

printf (“Enter positive numbers, end with 0 or a negative number\n”);

scanf(“%lf”, &next);

while (next > 0) {

if (next > max) max = next;

scanf(“%lf”, &next);

}

printf (“The maximum number is %lf\n”, max) ;

}

Page 37: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

37

Find the sum of digits of a number

digit-sum.c

Page 38: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

38

Find the sum of digits of a numbervoid main()

{

int n, sum=0;

scanf (“%d”, &n);

while (n != 0) {

sum = sum + (n % 10);

n = n / 10;

}

printf (“The sum of digits of the number is %d \n”, sum);

}

digit-sum.c

Page 39: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

39

Test if a number is prime or notvoid main() {

int n, i=2;

scanf (“%d”, &n);

while (i < n) {

if (n % i == 0) {

printf (“%d is not a prime \n”, n);

break;

}

++i;

}

if (i == n) printf (“%d is a prime \n”, n);

}

Page 40: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

40

More efficient??void main() {

int n, i = 2, flag = 0; double limit;

scanf (“%d”, &n); limit = sqrt(n);

while (i <= limit) {if (n % i == 0) {printf (“%d is not a prime \n”, n);flag = 1; break;}i = i + 1;

}if (flag == 0) printf (“%d is a prime \n”, n);

}

Page 41: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

41

Some Loop Pitfalls

while (sum <= NUM) ;

sum = sum+2;for (i=0; i<=NUM; ++i); sum = sum+i;

for (i=1; i!=10; i=i+2) sum = sum+i;

double x;for (x=0.0; x<2.0; x=x+0.2) printf(“%f\n”, x);

Page 42: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

42

Some observations on for Initialization, loop-continuation test, and update

can contain arithmetic expressions for ( k = x; k <= 4 * x * y; k += y / x )

Update may be negative (decrement)

for (digit = 9; digit >= 0; --digit) If loop continuation test is initially 0 (false)

Body of for structure not performed No statement executed

Program proceeds with statement after for structure

Page 43: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

43

Example

We can give several expressions separated by commas in place of expr1 and expr3 in a for loop to do multiple assignments for example

for (fact=1, i=1; i<=10;++ i)

fact = fact * i;

for (sum=0, i=1; i<=N; ++i)

sum = sum + i * i;

Page 44: 1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of

44