1-d Arrays

Post on 31-Dec-2015

30 views 0 download

description

1-d Arrays. Array. Many applications require multiple data items that have common characteristics In mathematics, we often express such groups of data items in indexed form: x 1 , x 2 , x 3 , …, x n - PowerPoint PPT Presentation

Transcript of 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 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/…)

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

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

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”);}

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

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];

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

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.

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,…)

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]

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

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

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

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’};

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

17

Passing Arrays to Function

Array element can be passed to functions as ordinary arguments

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

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

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

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.

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

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

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

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

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);}

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

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);

28

Recall

29

Recall

Recall

30

x=a++ - ++a;

Right to left evaluation of the expression.

First update (rightmost) a to 11.

Leftmost a =>11

x=0

a=12

31

Revisit loops

32

33

SUM = 12 + 22 + 32 + …+ N2

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;}

35

Maximum of positive Numbers

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) ;

}

37

Find the sum of digits of a number

digit-sum.c

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

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);

}

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);

}

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);

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

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;

44