26
Lecture 8 ARRAYS Declaration of arrays One-dimensional arrays Strings Multi-dimensional arrays

Declaration of arrays One-dimensional arrays …atitech.unitbv.ro/ungureanu/docs/Programming_I_-_Courses/...One-dimensional arrays Strings Multi-dimensional arrays Array declaration

  • Upload
    others

  • View
    23

  • Download
    0

Embed Size (px)

Citation preview

Lecture 8

ARRAYS

Declaration of arrays

One-dimensional arrays

Strings

Multi-dimensional arrays

Array declaration

An array is a series of objects (called its elements) of the

same type placed in contiguous memory locations

Declaration syntax of an array with N dimensions:

type array_name [dim_1] [dim_2]…[dim_N];

Reserved memory area contains:

dim_1 x dim_2 x ... x dim_N elements.

The array has a symbolic name (array_name )

Each element is identified by indexes which denotes the

position of the element in the array.

The number of elements in an array is called its dimension.

Array declaration

Examples:

float vect1[5]; // declares an array with 5 elements of type float;

// it is allocated memory for 5 * sizeof (float) bytes

int dimensiuni[4][12]; // declares an array with 4*12 elements of

// type int; is allocated memory for

// 4*12*sizeof(int) bytes

double tab[2][3][4]; // declares an array with 2*3*4 elements of

// type double; is allocated memory for

// 2*3*4*sizeof(double) bytes

type name

dimensions

Array declaration

Array declaration with initialization

int vect2[10]={2, 7, -1, 0, 9, 15, -5, 22, 6, 11}; // declares an array with 10

// elements of type int with

// initial values;

int mat[2][3]={{3, 5, -3},{2, -1, 0}}; // declares an bidimensional array

// with 2*3 elements of type int with

// initial values;

float vect[5] = { 1.5, 3.2, 7.1}; // initializes the first three values, two

// remain uninitialized

float vect[5] = { 1.5, 3.2, 7.1, -2.5, 6, 10 };// error, the number of initialization

// values is greater than the number

// of array elements

float vect[ ]={ 1.5, 3.2, 7.1, -2.5, 6 }; // number of initialization values is 5,

// so the default size of the array will

// be 5

Array declaration

Using the array elements

float vect1[5]; // declares an array with 5 elements of type float

// without initialization

vect[0] = 1.5; // to the element of index 0 is assigned the value 1.5

vect[1] = -2.5; // to the element of index 1 is assigned the value -2.5

vect[5] = 3.2; // although no error is reported, the index is used

// incorrectly, the correct values are 0 ... 4, this may

// lead to uncontrolled effects on the development

// of the program

int mat[2][3]={{3, 5, -3},{2, -1, 0}}; // declares an bidimensional array

// with 2*3 elements of type int with

// initial values;

mat[1][2]= 23; // to element of indexes 1 and 2, is assigned

// the value 23

Array declaration

The name of the array (unaccompanied by index) is the

memory address that is assigned to the array.

The first element index is 0 (zero), then the maximum value of

the index is dimension -1.

After allocating the necessary memory or to compile or to

execution, are no longer checks for size, so not check that the

indexes used are correct values.

If indexes exceed the size of the array, there is a risk to

modify values in memory locations used for any purpose,

destroying data or program code.

Array declaration

Uninitialized elements of the arrays take values, like any

variable, as follows:

value zero if the array has a global declaration

residual value, if the declaration of the array is local to

a block of instructions.

When declaring an array, the size is specified by constant

integers (literal or named constants), such as:

#define dim1 15

const int dim2 = 99;

int vector1[20];

float vector2[dim1];

double vector3[dim2];

Literal constant

Named constant

One-dimensional array

The syntax for declaring a one-dimensional array:

type array_name [dimension];

The syntax for declaring a one-dimensional array with initialization of

elements:

type array_name [dimension] = { value_list };

To mention an element use the following syntax:

array_name[index]

One-dimensional array

Declaration of an array:

int nums[6];

or: int nums[6]={3, 5, -7, 15, 99, 43};

One-dimensional array

float array[8];

int i = 5;

array[ 0 ] = 11.11; // index is expressed by a constant

array [ i ] = 12.12; // index is expressed by a variable

array[ i+2 ] = 13.13; // index is expressed by an expression

array [ ++i ] = 14.14; // index is expressed by an expression

One-dimensional array

Examples:

//declares an array with 5 elements of type int without initialization

int tab1[5];

// tab1 item values displayed

printf(“Element values: ");

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

printf("\ntab1[%d]=%d", i, tab1[i]);

// be read from the keyboard element values of tab1

printf("\n\nReading values for elements: ");

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

{ printf("\ntab1[%d]=", i);

scanf("%d", &tab1[i]);

}

One-dimensional array

// tab1 item values displayed

printf("\n\n Element values: ");

for(i=4 ; i>=0 ; i--)

printf("\ntab1[%d]=%d", i, tab1[i]);

//display elements divisible by 3

printf("\n\n Element values: - divizibile by 3");

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

if (!(tab1[i] % 3))

printf("\ntab1[%d]=%d", i, tab1[i]);

One-dimensional array

Specific language operators can be applied to elements of the array to

the extent that such items permits.

No operation can’t be made with array as a whole, but with elements of

their.

int tab1[5];

float tab2[10];

// …

tab1=tab2 ; // error, can not be made the assignment, tab1 and

// tab2 are memory addresses that are assigned to

// arrays and they can not be changed

tab1+tab2 ; // error, operator + is not defined to work with arrays

// (memory addresses)

tab1[0]+tab2[0]; // correct, tab1[0] and tab2[0] are data type int and

// float, so the addition can be made

One-dimensional array

Examples:

1. Write a program that:

• Declares an array with 12 elements of type int.

• Displays memory address that is assigned to the array and the number of

bytes occupied.

• Displays memory address that is assigned to each element and the number

of bytes occupied by them.

• Elements are read from the keyboard and then they are displayed.

• Displays the array elements in ascending order of indexes and than in

reverse order.

• Determines and display the maximum element of the array.

• Determines and display the arithmetic mean of the items.

• Displays the even elements and then the odd elements.

2. Write a program that:

• Reads from the keyboard elements of two arrays with 8 elements of type

double.

• Displays the elements of the two arrays.

• Calculates and displays elements of the 3rd array as the sum of the two

first ( every element is sum of the elements of the same index).

Strings (Character Sequences)

One-dimensional arrays with elements of type char are used for storing

strings (character sequences).

Declaring a string is as specific syntax of single dimensional arrays, the

type of items (char):

char string_name[dimension];

char name[6]; (1)

char name[6] = { ’S’, ’M’, ’I’, ’T’, ’H’, ’\0’}; (2) char name[6] =”SMITH”; (3)

Strings (Character Sequences)

// declaring a char array with 17 elements (a string) with initialization (the

last character in the series is the terminator. ‘\0’

char sir3[ ]=”character sequence”;

// size was not stated explicitly, but implicitly determined by the length of

initialization string

sir3[0]=’C’; // first character of the string receives value ‘C’

Strings (Character Sequences)

Strings can be treated like any one-dimensional array, making

processed item by item, so character by character.

In addition, there are defined in standard header files a set of functions

for processing strings.

char string [20] = “example”;

puts(string); // displays the string

printf(“%s”, string); // displays the string

for(int i=0 ; i<20; i++) // displays all elements

printf(“%c”, string[i]);

for(i=0 ; sir[i] != ‘\0’; i++) // displays all elements up to the terminator

printf(“%c”, string[i]);

Strings (Character Sequences)

If the string is empty, the first element of the picture is even the

terminator of the string, for example:

string[0]=’\0’;

The size specified when declare a string must be one unit higher than

the number of significant characters to allow saving terminator so.

The terminator of the string enables easy testing of the end of the

string.

Defined functions to work with strings do not refer to their size, but they

use the terminator of the string to indicate the end of strings.

Strings (Character Sequences)

header file string.h contains functions which work with strings.

strcpy(sir_destinatie, sir_sursa); - copy content of source string to destination

string

strcat(sir_destinatie, sir_sursa); - add content source string to destination

string (merges the two strings)

strlen(sir); - returns the number of elements of the

string (length string)

strcmp(sir1, sir2); - compares two strings, returning the value

0 if strings are equal, and different value of

0 if they are different (the value is given by

the difference between the first different

characters)

strupr(sir); - replace all lowercase characters with

appropriate capitalization

strlwr(sir); - replaces all uppercase characters with

lowercase letters corresponding

Strings (Character Sequences)

Examples:

1. Write a program that:

• Declares a string wits dimension 12.

• Read the string from the keyboard Elements are read from the keyboard.

• Displays memory address that is assigned to the string and the number of

bytes occupied.

• Displays memory address that is assigned to each element and the number

of bytes occupied by them.

• Displays the string using a function.

• Displays the string character by character.

• Prints on the screen only digit characters (‘0’, ‘1’, ...).

• Transform the string changing the lowercases with capitals.

1. Write a program that:

• Reads from the keyboard elements of two strings.

• Displays the elements of the two strings

• Determines a string by … and print it.

Multi-dimensional arrays

Declaration syntax of a multi-dimensional array :

type array_name [dim_1] [dim_2]…[dim_N];

Reserved memory area contains:

dim_1 x dim_2 x ... x dim_N elements.

A multidimensional array has more than one subscript

There is no limit to the number of dimensions a C++ array can

have

Multidimensional arrays are interpreted as arrays whose

elements are of type of the array.

Multi-dimensional arrays

Frequently there are used arrays with two dimensions

named matrix.

// declaration with initial values

int matrix[3][4] = { { 10, 20, 30, 40},

{ 50, 60, 70, 80},

{ 90, 100, 110, 120} };

Multi-dimensional arrays

matrix is an one-dimensional array with 3 elements; each

element is also an array with 4 integers.

The name of the matrix is the address where the array is

allocated and it is the same address with the address of the

first row of the matrix (matrix[0]) and the same with the

address of the first element (&matrix[0][0]).

The name of the array with one subscript is the name of a row

of matrix (matrix[0], matrix[1], matrix[2]).

One element of matrix can be used like any variable of the

same type.

Multi-dimensional arrays

/* working with multi-dimensional array*/

#include <stdio.h>

int main(void)

{

int matrix[3][4] = { { 10, 20, 30, 40},

{ 50, 60, 70, 80},

{ 90, 100, 110, 120}};

int row, col;

for (row =0; row < 3; row++)

for (col =0; col < 4; col++)

printf(“matrix[%d][%d]=%d\n”, row, col, matrix[row][col]);

return 0;

}

Multi-dimensional arrays

#include <stdio.h>

#include <conio.h>

int main()

{ int x; int y;

int array[8][8]; /* Declares an array */

for ( x = 0; x < 8; x++ )

for ( y = 0; y < 8; y++ )

array[x][y]=x * y; /* Set each element to a value */

printf( "Array Indexes:\n" );

for ( x = 0; x < 8;x++ )

{ for ( y = 0; y < 8; y++ )

printf( "[%d][%d]=%d", x, y, array[x][y] );

printf( "\n" );

}

getch();

}

Multi-dimensional arrays

Examples:

1. Write a program that:

• Declares an matrix with 4 rows and 4 columns (4x4=16 elements) of type

float.

• Displays memory address that is assigned to the array and the number of

occupied bytes.

• Displays memory address that is assigned to each row and the number of

bytes occupied by them.

• Displays memory address that is assigned to each element and the number

of bytes occupied by them.

• Reads from keyboard elements and then displays the matrix.

• Displays the elements of the second row.

• Displays the elements of the main diagonal of the matrix.

• Displays the elements of the secondary diagonal of the matrix.

1. Write a program that:

• Reads from the keyboard elements of two matrix with equal dimensions

with elements of type double.

• Displays the elements of the two arrays.

• Calculates and displays elements of the 3rd array as the sum of the two

first ( every element is sum of the elements of the same indexes.)