algor-06 new array 1

145
1 LARIK (ARRAY) – BAGIAN 1 Program Studi S1 Reguler Teknik Elektro DTE FTUI Slides ©2011 3/4/2011

Upload: velayati-puspa-pertiwi

Post on 06-Mar-2015

95 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Algor-06 New Array 1

1

LARIK (ARRAY) – BAGIAN 1Program Studi S1 Reguler Teknik Elektro DTE FTUI Slides ©20113/4/2011

Page 2: Algor-06 New Array 1

Pendahuluan2

Struktur data dasar yang sangat berdaya gunaStruktur data dasar yang sangat berdaya gunaSekumpulan data sejenis, mudah dikelola.Pengoperasian yang sangat sederhana fleksibel Pengoperasian yang sangat sederhana, fleksibel dan canggih.

3/4/2011

Page 3: Algor-06 New Array 1

Pendahuluan3

Dapat digunakan untuk mensimulasikan struktur Dapat digunakan untuk mensimulasikan struktur data yang lain:

StackQueueTreeGraph

3/4/2011

Page 4: Algor-06 New Array 1

Pendahuluan4

Larik : Variabel yang terdiri dari beberapa bagianLarik : Variabel yang terdiri dari beberapa bagianSetiap bagian sama ukuran dan jenisnya serta dapat diolah sendiri-sendiridapat diolah sendiri sendiriMasing-masing bagian larik disebut elemen atau unsur larikunsur larik

3/4/2011

Page 5: Algor-06 New Array 1

Pendahuluan5

Ilustrasi:Ilustrasi:Kotak K terdiri dari 12 bagian

K

0 1 2 3 4 5 6 7 8 9 10 11

3/4/2011

Page 6: Algor-06 New Array 1

Pendahuluan6

Perintah: “Taruh kelereng warna biru pada kotak K”Perintah: Taruh kelereng warna biru pada kotak KDengan adanya pengkotakan dan penomoran maka perintah dapat diubah sehingga tidak maka perintah dapat diubah sehingga tidak membingungkan harus ditaruh dimana kelereng tersebut.Ubah Perintah: “Taruh kelereng warna biru pada kotak nomor 7.”

3/4/2011

Page 7: Algor-06 New Array 1

Pendahuluan7

Perintah: “Taruh kelereng warna biru pada kotak Perintah: Taruh kelereng warna biru pada kotak nomor 7.”

KK

0 1 2 3 4 5 6 7 8 9 10 11

3/4/2011

Page 8: Algor-06 New Array 1

Pendahuluan8

ArrayArrayMenenpati kelompok lokasi memori berturut-turutNama dan tipe yang samaNama dan tipe yang sama

Bila ingin merefer sebuah elemen harus menspesifikasi p

Nama arrayNomor posisip

Page 9: Algor-06 New Array 1

Format9

Nama array[nomor posisi]y[ p ]

Elemen pertama diberi nomor 0Array C dengan n element :

c[ 0 ], c[ 1 ]...c[ n – 1 ]

Page 10: Algor-06 New Array 1

Array dengan 12-elementy g10

Page 11: Algor-06 New Array 1

Arrayy11

Elemen array seperti variabel biasaElemen array seperti variabel biasac[ 0 ] = 3;printf( "%d", c[ 0 ] );

Melaksanakan operasi dalam subscript. Jika x sama dengan 3

c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 12: Algor-06 New Array 1

Pendahuluan12

Pada algoritma, array dibuat dengan perintah sebagai berikut:

c[12] array integer c[12] : array integer

Akan muncul larik bernama c yang terdiri dari 12 y gelemen Setiap elemen diberi nomor 0 s.d 11 yang disebut indeks larikindeks larik.Diisi oleh bilangan bulat.Bisa juga untuk aksara

3/4/2011

Page 13: Algor-06 New Array 1

Pendahuluan13

Untuk menyimpan bilangan 7681 pada elemen ke c Untuk menyimpan bilangan 7681 pada elemen ke –3 larik c, dibuat perintah sebagai berikut:

C[3] : = 76817681

c

C[3] : 7681

0 1 2 3 4 5 6 7 8 9 10 11

3/4/2011

Page 14: Algor-06 New Array 1

14

Operators Associativity Typep y yp

[] () left to right highest

++ -- !

(type) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

g

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment Operator precedence. , left to right comma

p p

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 15: Algor-06 New Array 1

Definisikan Arrayy15

Mendefinisikan array, harus menspesifikasikan:Mendefinisikan array, harus menspesifikasikan:Nama Tipe arrayTipe arrayJumlah element

TypeArray NamaArray [ jumlahElemen ];

Contoh : int c[ 10 ]; float myArray[ 1765 ];

Page 16: Algor-06 New Array 1

Definisikan Arrayy16

Untuk mendefinisikan array lebih dari satu dengan Untuk mendefinisikan array lebih dari satu dengan tipe yang sama

Format sesuai variabel biasaContoh :

int b[ 100 ], x[ 27 ];

Page 17: Algor-06 New Array 1

Contoh arrayy17

InisialisasiInisialisasiint n[ 5 ] = { 1, 2, 3, 4, 5 };

int n[ 5 ] = { 0 } int n[ 5 ] { 0 } All elements 0

Jika ukuran dihilangkan, akan ditentukan oleh Jika ukuran dihilangkan, akan ditentukan oleh inisialisasi

int n[ ] = { 1, 2, 3, 4, 5 };

Ada 5 inisialisasi, ada 5 elemen pada array

Page 18: Algor-06 New Array 1

Membalik Isi Larik18

Pengembangan AlgoritmaPengembangan AlgoritmaDiubah dengan mempertukarkan isi elemen larik pertama dengan isi elemen larik terakhir, kemudian pertama dengan isi elemen larik terakhir, kemudian tukar isi elemen larik yang kedua dengan isi elemen larik kedua dari akhir, dst.

3/4/2011

Page 19: Algor-06 New Array 1

Membalik Isi Arrayy

Ada 2 cara untuk membalik isi array:Ada 2 cara untuk membalik isi array:Dengan dummy arrayDengan membalik yang paling kiri dengan paling Dengan membalik yang paling kiri dengan paling kanan dan seterusnya

Page 20: Algor-06 New Array 1

Dummy Arrayy y

Menggunakan array sementara untuk membalik isi Menggunakan array sementara untuk membalik isi arraySetelah dibalik, diisi ke array aslinyaSetelah dibalik, diisi ke array aslinya

Page 21: Algor-06 New Array 1

Algoritmag

/* Membalikkan isi berkas *// /

Prog Utama ( )/* M b k l l*/ /* Memberikan nilai array awal*/

for i = 0 to 5, do n[ i ] = k /* set element at location i to 0 */n[ i ] = k / set element at location i to 0 /k = k + 1

efor

cetak("Array 1“)

Page 22: Algor-06 New Array 1

Algoritmag

/ //* dummy array*/ i = 0for j = 5 to 0, j = j-1, do

[ j ] = [ i ] m[ j ] = n[ i ] i = i +1

efor

/* kembalikan ke array semula*/ for i = 0 to 5, i = i + 1, do

n[ i ] = m[ j ][ ] [ j ]j = j + 1

efor

Page 23: Algor-06 New Array 1

Algoritmag

/* Mencetak hasil */ / Mencetak hasil /

for i = 0 to 5 i = i + 1 dofor i = 0 to 5, i = i + 1, docetak (n[ i ], m[ i ] )

feforeprog

Page 24: Algor-06 New Array 1

Program dalam Cg

/* Membalikkan isi berkas */#include <stdio.h>

/* function main begins program execution *// g p g /int main( void ){

int n[ 6 ]; /* n is an array of 10 integers */int n[ 6 ]; / n is an array of 10 integers /int m[ 6 ];int i; /* counter */i jint j;int k = 10;

Page 25: Algor-06 New Array 1

Program dalam Cg

/* inisialisasi aray pada nilai awal*/ / inisialisasi aray pada nilai awal / for ( i = 0; i < 6; i++ ) {

n[ i ] = k; n[ i ] = k; k++;

} /* d f */ } /* end for */

printf( "%s\n", "Array 1");

Page 26: Algor-06 New Array 1

Program dalam Cg

i = 0;;/* dummy array*/

for ( j = 5; j >= 0; j-- ) { ( j ; j ; j ) {

m[ j ] = n[ i ]; [ j ] [ ];i++;

} /* end for */ } / /j = 0;

Page 27: Algor-06 New Array 1

Program dalam Cg

/* kembalikan ke array semula*/ / y /for ( i = 0; i < 6; i++ ) {

n[ i ] = m[ j ]; /* set element at location i to 0 */j++;

} /* d f */ } /* end for */ /* output contents of array n in tabular format */ for ( i = 0; i < 6; i++ ) { for ( i 0; i < 6; i++ ) {

printf( "%4d\n", n[ i ]); } /* end for */

Page 28: Algor-06 New Array 1

Membalik Isi Larik28

2

10 11 12 13 14 15 15 14 13 12 11 10

(a) Proses Pembalikan isi larik temp

(b) Proses pertukaran isi larik1 3

( ) p a an a

3/4/2011

Page 29: Algor-06 New Array 1

Membalik Isi Larik29

Untuk menukar dua elemen larik diperlukan satu Untuk menukar dua elemen larik diperlukan satu variabel yaitu temp dan tiga proses pemuatan (assignment) seperti pada gambar.( g ) p p gSimpan isi elemen larik pertama ke variabel temp, kemudian salin isi elemen larik terakhir ke elemen pertama, dan akhirnya salin isi temp ke elemen terakhir.Bilangan n adalah indeks elemen terkahir

3/4/2011

Page 30: Algor-06 New Array 1

Membalik Isi Larik30

temp = n[i]p [ ]n[i] =n[j]n[j] = temp

Prosedur yang sama dilakukan untuk elemen ke-2,3,4 dst.Bila jumlah elemen larik adalah r maka nomor elemen tengah larik adalah t = r /2, yaitu hasil bagi bilangan bulat bilangan r dengan 2. g gContoh: 6 / 2 = 3

5 / 2 = 2

3/4/2011

Page 31: Algor-06 New Array 1

Membalik Isi Larik31

Algoritma pembalikan isi larik dapat g p pdiformulasikan sbb:

t = r / 2 (t adalah nomor tengah larik )for i = 0 to t do

(tukar elemen ke-i dengan elemen ke-i dari akhir ).

Elemen ke-i adalah l[i] sedang elemen i dari akhir d l h l[j] di j l i d i d adalah l[j] dimana j mulai dari n dengan

pengurangan 1, sedang i mulai dari dengan pertambahan 1.

3/4/2011

pertambahan 1.

Page 32: Algor-06 New Array 1

Membalik Isi Larik32

Cuplikan Algoritma pembalikan isi larik adalah:t := r / 2 (nomor tengah larik).j := r (indeks elemen terakhir)f 1 dfor i = 1 to t do

temp := n[i]n[i] := n[j]n[i] := n[j]n[j] := tempj := j-1

eforeproc

3/4/2011

Page 33: Algor-06 New Array 1

Program dalam Cg

/* Membalikkan isi berkas */#i l d di h#include <stdio.h>int main( void ){

int n[ 6 ]; /* n is an array of 6 integers */[ ]; / y g /int m[ 6 ];int i; /* counter */int j;int r;int t;int temp;

/* inisialisasi aray pada nilai awal*/ / inisialisasi aray pada nilai awal / for ( i = 0; i < 6; i++ ) {

n[ i ] = i; /* set element at location i to 0 */} /* end for */

Page 34: Algor-06 New Array 1

Program dalam Cg

printf( "%s\n", "Array 1");

for ( i = 0; i < 6; i++ ) { i f( "%4d\ " [ i ] ) printf( "%4d\n", n[ i ] );

} /* end for */

Page 35: Algor-06 New Array 1

Program dalam Cg

/* coba balik array */r = i-1;t = r / 2t = r / 2;j = r;for (i = 0; i <= t; i++) {

temp = n[ i ];n[ i ] = n[ j ];n[ j ] = tempn[ j ] = temp;j = j - 1;

}}

Page 36: Algor-06 New Array 1

Program dalam Cg

printf( "%s\n", "Array 1"); printf( %s\n , Array 1 ); for ( i = 0; i < 6; i++ ) {

printf( "%4d\n" n[ i ] ); printf( %4d\n , n[ i ] ); } /* end for */

0 /* i di f l i i */return 0; /* indicates successful termination */} /* end main */

Page 37: Algor-06 New Array 1

Menghilangkan Duplikasig g p37

Untuk menghilangkan duplikasi data yang ada Untuk menghilangkan duplikasi data yang ada didalam suatu larik akan dibuat algoritma.Contoh:Contoh:

T d p t d plik i

10 10 10 14 15 16 16 17 17 19 (a)L

Terdapat duplikasi

10 14 15 16 17 19 (b)L

t d lik i

3/4/2011

tanpa duplikasi

Page 38: Algor-06 New Array 1

1 /* Fig. 6.3: fig06_03.c

2 initializing an array */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

5 / function main begins program execution /

6 int main( void )

7 {

8 int n[ 10 ]; /* n is an array of 10 integers */

9 int i; /* counter */

10

fig06_03.c

(1 of 2 )10 11 /* initialize elements of array n to 0 */ 12 for ( i = 0; i < 10; i++ ) { 13 n[ i ] = 0; /* set element at location i to 0 */ 14 } /* end for */

for loop initializes each array element separately

15 16 printf( "%s%13s\n", "Element", "Value" ); 17 18 /* output contents of array n in tabular format */ 19 for ( i = 0; i < 10; i++ ) { for loop outputs all array9 o ( 0; 0; ) {

20 printf( "%7d%13d\n", i, n[ i ] ); 21 } /* end for */ 22 23 return 0; /* indicates successful termination */ 24

for loop outputs all array elements

24 25 } /* end main */

38 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 39: Algor-06 New Array 1

Element Value

0 0

1 0

2 0

Outline

3 0

4 0

5 0

6 0

7 0

fig06_03.c

(2 of 2 )

8 0

9 0

39 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 40: Algor-06 New Array 1

1 /* Fig. 6.4: fig06_04.c

2 Initializing an array with an initializer list */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

6 int main( void )

7 {

8 /* use initializer list to initialize array n */

9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

10 int i; /* counter */

fig06_04.c

(1 of 2 )

11 12 printf( "%s%13s\n", "Element", "Value" ); 13 14 /* output contents of array in tabular format */ 15 for ( i = 0; i < 10; i++ ) {

initializer list initializes all array elements simultaneously15 for ( i 0; i < 10; i++ ) {

16 printf( "%7d%13d\n", i, n[ i ] ); 17 } /* end for */ 18 19 return 0; /* indicates successful termination */ 20

simultaneously

20 21 } /* end main */

40 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 41: Algor-06 New Array 1

Element Value

0 32

1 27

2 64

3 18

Outline

3 18

4 95

5 14

6 90

7 70

8 60

fig06_04.c

(2 of 2 ) 8 60

9 37

41 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 42: Algor-06 New Array 1

1 /* Fig. 6.5: fig06_05.c

2 Initialize the elements of array s to the even integers from 2 to 20 */

3 #include <stdio.h>

4 #define SIZE 10 /* maximum size of array */

5

Outline#define directive tells compiler to replace all

instances of the word SIZE with 10 5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* symbolic constant SIZE can be used to specify array size */

10 int s[ SIZE ]; /* array s has SIZE elements */

fig06_05.c

(1 of 2 )

instances of the word SIZE with 10

SIZE i l d ith 10 b th10 int s[ SIZE ]; /* array s has SIZE elements */ 11 int j; /* counter */ 12 13 for ( j = 0; j < SIZE; j++ ) { /* set the values */ 14 s[ j ] = 2 + 2 * j;

SIZE is replaced with 10 by the compiler, so array s has 10 elements

for loop initializes each array 15 } /* end for */ 16 17 printf( "%s%13s\n", "Element", "Value" ); 18 19 /* output contents of array s in tabular format */

p yelement separately

19 / output contents of array s in tabular format /

20 for ( j = 0; j < SIZE; j++ ) { 21 printf( "%7d%13d\n", j, s[ j ] ); 22 } /* end for */ 23 24 t 0 /* i di t f l t i ti */ 24 return 0; /* indicates successful termination */ 25 26 } /* end main */

42 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 43: Algor-06 New Array 1

Element Value

0 2

1 4

2 6

Outline

3 8

4 10

5 12

6 14

7 16

fig06_05.c

(2 of 2 )

8 18

9 20

43 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 44: Algor-06 New Array 1

1 /* Fig. 6.6: fig06_06.c

2 Compute the sum of the elements of the array */

3 #include <stdio.h>

4 #define SIZE 12

5

Outline

5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* use initializer list to initialize array */

10 int a[ SIZE ] { 1 3 5 4 7 2 99 16 45 67 89 45 };

fig06_06.c

10 int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; 11 int i; /* counter */ 12 int total = 0; /* sum of array */ 13 14 /* sum contents of array a */

initializer list initializes all array elements simultaneously

15 for ( i = 0; i < SIZE; i++ ) { 16 total += a[ i ]; 17 } /* end for */ 18 19 printf( "Total of array element values is %d\n", total );

for loop adds each element of the array to variable total

19 printf( Total of array element values is %d\n , total );

20 21 return 0; /* indicates successful termination */ 22 23 } /* end main */

Total of array element values is 383

44 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 45: Algor-06 New Array 1

1 /* Fig. 6.7: fig06_07.c

2 Student poll program */

3 #include <stdio.h>

4 #define RESPONSE_SIZE 40 /* define array sizes */

5 #define FREQUENCY SIZE 11

Outline

#define directives create symbolic constants 5 #define FREQUENCY_SIZE 11

6 7 /* function main begins program execution */

8 int main( void )

9 {

10 int answer; /* counter to loop through 40 responses */

fig06_07.c

(1 of 2 )

symbolic constants

10 int answer; /* counter to loop through 40 responses */ 11 int rating; /* counter to loop through frequencies 1-10 */ 12 13 /* initialize frequency counters to 0 */ 14 int frequency[ FREQUENCY_SIZE ] = { 0 };

frequency array is defined with 11 elements15

16 /* place the survey responses in the responses array */ 17 int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 18 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };

defined with 11 elements

responses array is defined with 40 elements and its 19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };

20 21 /* for each answer, select value of an element of array responses 22 and use that value as subscript in array frequency to

23 determine element to increment */

24 f ( 0 RESPONSE SIZE ) {

elements are initialized

24 for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) { 25 ++frequency[ responses [ answer ] ]; 26 } /* end for */ 27

subscript of frequency array is given by value in responses array

45 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 46: Algor-06 New Array 1

28 /* display results */ 29 printf( "%s%17s\n", "Rating", "Frequency" ); 30 31 /* output the frequencies in a tabular format */ 32 for ( rating = 1; rating < FREQUENCY SIZE; rating++ ) {

Outline

32 for ( rating 1; rating < FREQUENCY_SIZE; rating++ ) {

33 printf( "%6d%17d\n", rating, frequency[ rating ] ); 34 } /* end for */ 35 36 return 0; /* indicates successful termination */ 37

fig06_07.c

(2 of 2 )37 38 } /* end main */

Rating Frequency

1 2

2 2 2 2

3 2

4 2

5 5

6 11

7 5

8 7

9 1

10 3

46 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 47: Algor-06 New Array 1

1 /* Fig. 6.8: fig06_08.c

2 Histogram printing program */

3 #include <stdio.h>

4 #define SIZE 10

5

Outline

5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* use initializer list to initialize array n */

10 int n[ SIZE ] { 19 3 15 7 11 9 13 5 17 1 };

fig06_08.c

(1 of 2 )10 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 11 int i; /* outer for counter for array elements */ 12 int j; /* inner for counter counts *s in each histogram bar */ 13 14 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); 15 16 /* for each element of array n, output a bar of the histogram */ 17 for ( i = 0; i < SIZE; i++ ) { 18 printf( "%7d%13d ", i, n[ i ]) ; 1919 20 for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */ 21 printf( "%c", '*' ); 22 } /* end inner for */

23 24 i tf( "\ " ) /* d hi t b */

nested for loop prints n[ i ] asterisks on the ith line

24 printf( "\n" ); /* end a histogram bar */ 25 } /* end outer for */ 26 27 return 0; /* indicates successful termination */ 28

47

29 } /* end main */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 48: Algor-06 New Array 1

Element Value Histogram

0 19 *******************

1 3 ***

2 15 ***************

Outline

3 7 *******

4 11 ***********

5 9 *********

6 13 *************

7 5 *****

fig06_08.c

(2 of 2 )

8 17 *****************

9 1 *

48 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 49: Algor-06 New Array 1

1 /* Fig. 6.9: fig06_09.c

2 Roll a six-sided die 6000 times */

3 #include <stdio.h>

4 #include <stdlib.h>

5 #include <time.h>

Outline

5 #include <time.h>

6 #define SIZE 7

7 8 /* function main begins program execution */

9 int main( void )

10 {

fig06_09.c

(1 of 2 )10 { 11 int face; /* random die value 1 - 6 */ 12 int roll; /* roll counter 1-6000 */ 13 int frequency[ SIZE ] = { 0 }; /* clear counts */ 14 15 srand( time( NULL ) ); /* seed random-number generator */ 16 17 /* roll die 6000 times */ 18 for ( roll = 1; roll <= 6000; roll++ ) { 19 face = 1 + rand() % 6; 19 face 1 + rand() % 6;

20 ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */ 21 } /* end for */

for loop uses one array to track p ynumber of times each number is rolled instead of using 6 variables and a switch statement

49 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 50: Algor-06 New Array 1

22 23 printf( "%s%17s\n", "Face", "Frequency" ); 24 25 /* output frequency elements 1-6 in tabular format */ 26 for ( face = 1; face < SIZE; face++ ) {

Outline

26 for ( face 1; face < SIZE; face++ ) {

27 printf( "%4d%17d\n", face, frequency[ face ] ); 28 } /* end for */ 29 30 return 0; /* indicates successful termination */ 31

fig06_09.c

(2 of 2 )31 32 } /* end main */

Face Frequency

1 1029

2 951 2 951

3 987

4 1033

5 1010

6 990

50 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 51: Algor-06 New Array 1

Contoh Arrayy51

Character arraysString “first” is really a static array of charactersCharacter arrays can be initialized using string literals

char string1[] = "first";Null character '\0' terminates stringsstring1 actually has 6 elements

It is equivalent to

h t i 1[] = { 'f' 'i' ' ' ' ' 't' '\0' }char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };Can access individual characters

string1[ 3 ] is character ‘s’A i dd f & d d f f Array name is address of array, so & not needed for scanf

scanf( "%s", string2 );Reads characters until whitespace encounteredBe careful not to write past end of array as it is possible to do soBe careful not to write past end of array, as it is possible to do so

Page 52: Algor-06 New Array 1

1 /* Fig. 6.10: fig06_10.c

2 Treating character arrays as strings */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

5 / function main begins program execution /

6 int main( void )

7 {

8 char string1[ 20 ]; /* reserves 20 characters */

9 char string2[] = "string literal"; /* reserves 15 characters */

10 int i; /* counter */

fig06_10.c

(1 of 2 )10 int i; /* counter */ 11 12 /* read string from user into array string1 */ 13 printf("Enter a string: "); 14 scanf( "%s", string1 ); /* input ended by whitespace character */

string2 array is defined with one element for each character, so 15 elements including null character /0

15 16 /* output strings */ 17 printf( "string1 is: %s\nstring2 is: %s\n" 18 "string1 with spaces between characters is:\n", 19 string1, string2 ); 19 string1, string2 ); 20 21 /* output characters until null character is reached */ 22 for ( i = 0; string1[ i ] != '\0'; i++ ) { 23 printf( "%c ", string1[ i ] ); 24 } /* d f */

for loop prints characters of string1array with spaces in between24 } /* end for */

25 26 printf( "\n" ); 27 28 return 0; /* indicates successful termination */

array with spaces in between

52

29 30 } /* end main */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 53: Algor-06 New Array 1

Enter a string: Hello there

string1 is: Hello

string2 is: string literal

string1 with spaces between characters is:

Outline

H e l l o

fig06_10.c

(2 of 2 )

53 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 54: Algor-06 New Array 1

1 /* Fig. 6.11: fig06_11.c

2 Static arrays are initialized to zero */

3 #include <stdio.h>

4 5 void staticArrayInit( void ); /* function prototype */

Outline

5 void staticArrayInit( void ); / function prototype /

6 void automaticArrayInit( void ); /* function prototype */

7 8 /* function main begins program execution */

9 int main( void )

10 {

fig06_11.c

(1 of 4 )10 { 11 printf( "First call to each function:\n" ); 12 staticArrayInit(); 13 automaticArrayInit(); 14 15 printf( "\n\nSecond call to each function:\n" ); 16 staticArrayInit(); 17 automaticArrayInit(); 18 19 return 0; /* indicates successful termination */ 19 return 0; / indicates successful termination /

20 21 } /* end main */ 22

54 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 55: Algor-06 New Array 1

23 /* function to demonstrate a static local array */ 24 void staticArrayInit( void ) 25 { 26 /* initializes elements to 0 first time function is called */ 27 static int array1[ 3 ];

Outline

static array is created only once when27 static int array1[ 3 ]; 28 int i; /* counter */ 29 30 printf( "\nValues on entering staticArrayInit:\n" ); 31 32 /* output contents of array1 */

fig06_11.c

(2 of 4 )

static array is created only once, when staticArrayInit is first called

32 /* output contents of array1 */ 33 for ( i = 0; i <= 2; i++ ) { 34 printf( "array1[ %d ] = %d ", i, array1[ i ] ); 35 } /* end for */ 36 37 printf( "\nValues on exiting staticArrayInit:\n" ); 38 39 /* modify and output contents of array1 */ 40 for ( i = 0; i <= 2; i++ ) { 41 printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 ); 41 printf( array1[ %d ] %d , i, array1[ i ] + 5 );

42 } /* end for */ 43 44 } /* end function staticArrayInit */

55 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 56: Algor-06 New Array 1

45 46 /* function to demonstrate an automatic local array */ 47 void automaticArrayInit( void ) 48 { 49 /* initializes elements each time function is called */

Outline

49 / initializes elements each time function is called /

50 int array2[ 3 ] = { 1, 2, 3 }; 51 int i; /* counter */ 52 53 printf( "\n\nValues on entering automaticArrayInit:\n" ); 54

fig06_11.c

(3 of 4 )

automatic array is recreated every time automaticArrayInit is called

54 55 /* output contents of array2 */ 56 for ( i = 0; i <= 2; i++ ) { 57 printf("array2[ %d ] = %d ", i, array2[ i ] ); 58 } /* end for */ 59 60 printf( "\nValues on exiting automaticArrayInit:\n" ); 61 62 /* modify and output contents of array2 */ 63 for ( i = 0; i <= 2; i++ ) { 63 for ( i 0; i < 2; i++ ) {

64 printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 ); 65 } /* end for */ 66 67 } /* end function automaticArrayInit */

56 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 57: Algor-06 New Array 1

First call to each function:

Values on entering staticArrayInit:

array1[ 0 ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0

Outline

Values on exiting staticArrayInit:

array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5

Values on entering automaticArrayInit:

array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3

fig06_11.c

(4 of 4 )y y y

Values on exiting automaticArrayInit:

array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

Second call to each function:

Values on entering staticArrayInit:

array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5

Values on exiting staticArrayInit:

array1[ 0 ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10

Values on entering automaticArrayInit:

array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3

Values on exiting automaticArrayInit:

array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

57 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 58: Algor-06 New Array 1

6.5 Passing Arrays to Functionsg y58

Passing arraysTo pass an array argument to a function, specify the name of the array without any brackets

int myArray[ 24 ];F ti ( A 24 )myFunction( myArray, 24 );

Array size usually passed to function Arrays passed call-by-reference Name of array is address of first elementName of array is address of first elementFunction knows where the array is stored

Modifies original memory locationsP i l t Passing array elements

Passed by call-by-valuePass subscripted name (i.e., myArray[ 3 ]) to function

Page 59: Algor-06 New Array 1

6.5 Passing Arrays to Functionsg y59

Function prototypeFunction prototypevoid modifyArray( int b[], int arraySize );

Parameter names optional in prototypep p ypint b[] could be written int []int arraySize could be simply int

Page 60: Algor-06 New Array 1

1 /* Fig. 6.12: fig06_12.c

2 The name of an array is the same as &array[ 0 ] */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

5 / function main begins program execution /

6 int main( void )

7 {

8 char array[ 5 ]; /* define an array of size 5 */

9 10 printf( " array %p\n&array[0] %p\n &array %p\n"

fig06_12.c

10 printf( " array = %p\n&array[0] = %p\n &array = %p\n", 11 array, &array[ 0 ], &array ); 12 13 return 0; /* indicates successful termination */ 14 15 } /* end main */

array = 0012FF78

&array[0] = 0012FF78

&array = 0012FF78

60 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 61: Algor-06 New Array 1

1 /* Fig. 6.13: fig06_13.c

2 Passing arrays and individual array elements to functions */

3 #include <stdio.h>

4 #define SIZE 5

5

Outline

5 6 /* function prototypes */

7 void modifyArray( int b[], int size );

8 void modifyElement( int e );

9 10 /* function main begins program execution */

fig06_13.c

(1 of 3 )Function prototype indicates function will take an array

10 /* function main begins program execution */ 11 int main( void ) 12 { 13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */ 14 int i; /* counter */ 15 16 printf( "Effects of passing entire array by reference:\n\nThe " 17 "values of the original array are:\n" ); 18 19 /* output original array */ 19 / output original array /

20 for ( i = 0; i < SIZE; i++ ) { 21 printf( "%3d", a[ i ] ); 22 } /* end for */ 23 24 i tf( "\ " ) 24 printf( "\n" ); 25 26 /* pass array a to modifyArray by reference */ 27 modifyArray( a, SIZE ); 28

Array a is passed to modifyArrayby passing only its name

61

29 printf( "The values of the modified array are:\n" ); 30

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 62: Algor-06 New Array 1

31 /* output modified array */ 32 for ( i = 0; i < SIZE; i++ ) { 33 printf( "%3d", a[ i ] ); 34 } /* end for */ 35

Outline

35 36 /* output value of a[ 3 ] */ 37 printf( "\n\n\nEffects of passing array element " 38 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); 39 40 modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */

fig06_13.c

(2 of 3 )40 modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */ 41 42 /* output value of a[ 3 ] */ 43 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); 44

Array element is passed to modifyElementby passing a[ 3 ]

45 return 0; /* indicates successful termination */ 46 47 } /* end main */ 48 49 /* in function modifyArray, "b" points to the original array "a" 49 / in function modifyArray, b points to the original array a

50 in memory */ 51 void modifyArray( int b[], int size ) 52 { 53 int j; /* counter */ 5454 55 /* multiply each array element by 2 */ 56 for ( j = 0; j < size; j++ ) { 57 b[ j ] *= 2; 58 } /* end for */

62

59 60 } /* end function modifyArray */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 63: Algor-06 New Array 1

61 62 /* in function modifyElement, "e" is a local copy of array element 63 a[ 3 ] passed from main */ 64 void modifyElement( int e ) 65 {

Outline

65 { 66 /* multiply parameter by 2 */ 67 printf( "Value in modifyElement is %d\n", e *= 2 ); 68 } /* end function modifyElement */

Effects of passing entire array by reference:

fig06_13.c

(3 of 3 )Effects of passing entire array by reference:

The values of the original array are:

0 1 2 3 4

The values of the modified array are:

0 2 4 6 8 0 2 4 6 8

Effects of passing array element by value:

h l f [ ] iThe value of a[3] is 6

Value in modifyElement is 12

The value of a[ 3 ] is 6

63 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 64: Algor-06 New Array 1

1 /* Fig. 6.14: fig06_14.c

2 Demonstrating the const type qualifier with arrays */

3 #include <stdio.h>

4 5 void tryToModifyArray( const int b[] ); /* function prototype */

Outline

5 void tryToModifyArray( const int b[] ); / function prototype /

6 7 /* function main begins program execution */

8 int main( void )

9 {

10 int a[] { 10 20 30 }; /* initialize a */

fig06_14.c

(1 of 2 )t lifi t ll il th t10 int a[] = { 10, 20, 30 }; /* initialize a */

11 12 tryToModifyArray( a ); 13 14 printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] );

const qualifier tells compiler that array cannot be changed

15 16 return 0; /* indicates successful termination */ 17 18 } /* end main */ 1919 20 /* in function tryToModifyArray, array b is const, so it cannot be 21 used to modify the original array a in main. */ 22 void tryToModifyArray( const int b[] ) 23 { 24 b[ 0 ] / 2 /* */ 24 b[ 0 ] /= 2; /* error */ 25 b[ 1 ] /= 2; /* error */ 26 b[ 2 ] /= 2; /* error */ 27 } /* end function tryToModifyArray */

Any attempts to modify the array will result in errors

64 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 65: Algor-06 New Array 1

Compiling...

FIG06_14.C

fig06_14.c(24) : error C2166: l-value specifies const object

fig06_14.c(25) : error C2166: l-value specifies const object

Outline

fig06_14.c(26) : error C2166: l-value specifies const object

fig06_14.c

(2 of 2 )

65 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 66: Algor-06 New Array 1

6.6 Sorting Arraysg y66

Sorting dataImportant computing applicationVirtually every organization must sort some data

Bubble sort (sinking sort) S l th h th Several passes through the array Successive pairs of elements are compared

If increasing order (or identical ), no changeIf decreasing order, elements exchanged

RepeatExample:

original: 3 4 2 6 7pass 1: 3 2 4 6 7pass 2: 2 3 4 6 7 Small elements "bubble" to the top

Page 67: Algor-06 New Array 1

1 /* Fig. 6.15: fig06_15.c

2 This program sorts an array's values into ascending order */

3 #include <stdio.h>

4 #define SIZE 10

5

Outline

5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* initialize a */

10 int a[ SIZE ] { 2 6 4 8 10 12 89 68 45 37 };

fig06_15.c

(1 of 2 )10 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 11 int pass; /* passes counter */ 12 int i; /* comparisons counter */ 13 int hold; /* temporary location used to swap array elements */ 14 15 printf( "Data items in original order\n" ); 16 17 /* output original array */ 18 for ( i = 0; i < SIZE; i++ ) { 19 printf( "%4d", a[ i ] ); 19 printf( %4d , a[ i ] );

20 } /* end for */ 21 22 /* bubble sort */ 23 /* loop to control number of passes */ 24 f ( 1 SIZE ) { 24 for ( pass = 1; pass < SIZE; pass++ ) { 25 26 /* loop to control number of comparisons per pass */ 27 for ( i = 0; i < SIZE - 1; i++ ) { 28

67

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 68: Algor-06 New Array 1

29 /* compare adjacent elements and swap them if first 30 element is greater than second element */ 31 if ( a[ i ] > a[ i + 1 ] ) { 32 hold = a[ i ]; 33 a[ i ] = a[ i + 1 ];

Outline

If any two array elements are out of d th f ti th34 a[ i + 1 ] = hold;

35 } /* end if */ 36 37 } /* end inner for */ 38

fig06_15.c

(2 of 2 )

order, the function swaps them

38 39 } /* end outer for */ 40 41 printf( "\nData items in ascending order\n" ); 42 43 /* t t t d */ 43 /* output sorted array */ 44 for ( i = 0; i < SIZE; i++ ) { 45 printf( "%4d", a[ i ] ); 46 } /* end for */ 47 48 printf( "\n" ); 49 50 return 0; /* indicates successful termination */ 51 }

Data items in original order

2 6 4 8 10 12 89 68 45 37

Data items in ascending order

2 4 6 8 10 12 37 45 68 89

68

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 69: Algor-06 New Array 1

6.7 Case Study: Computing Mean, M di d M d U i AMedian and Mode Using Arrays

69

Mean – averageMean averageMedian – number in middle of sorted list

1 2 3 4 5 1, 2, 3, 4, 5 3 is the median

Mode – number that occurs most oftenMode – number that occurs most often1, 1, 1, 2, 3, 3, 4, 5 1 is the mode1 is the mode

Page 70: Algor-06 New Array 1

1 /* Fig. 6.16: fig06_16.c

2 This program introduces the topic of survey data analysis.

3 It computes the mean, median and mode of the data */

4 #include <stdio.h>

5 #define SIZE 99

Outline

5 #define SIZE 99

6 7 /* function prototypes */

8 void mean( const int answer[] );

9 void median( int answer[] );

10 void mode( int freq[] const int answer[] ) ;

fig06_16.c

(1 of 6 )10 void mode( int freq[], const int answer[] ) ; 11 void bubbleSort( int a[] ); 12 void printArray( const int a[] ); 13 14 /* function main begins program execution */ 15 int main( void ) 16 { 17 int frequency[ 10 ] = { 0 }; /* initialize array frequency */ 18 19 /* initialize array response */ 19 / initialize array response /

20 int response[ SIZE ] = 21 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 22 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 23 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 24 7 8 9 8 9 8 9 7 8 9 24 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 25 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 26 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 27 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 28 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,

70

29 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 30 4, 5, 6, 1, 6, 5, 7, 8, 7 };

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 71: Algor-06 New Array 1

31 32 /* process responses */ 33 mean( response ); 34 median( response ); 35 mode( frequency, response );

Outline

35 mode( frequency, response ); 36 37 return 0; /* indicates successful termination */ 38 39 } /* end main */ 40

fig06_16.c

(2 of 6 )40 41 /* calculate average of all response values */ 42 void mean( const int answer[] ) 43 { 44 int j; /* counter for totaling array elements */ 45 int total = 0; /* variable to hold sum of array elements */ 46 47 printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); 48 49 /* total response values */ 49 / total response values /

50 for ( j = 0; j < SIZE; j++ ) { 51 total += answer[ j ]; 52 } /* end for */ 53 54 i tf( "Th i th l f th d t \ " 54 printf( "The mean is the average value of the data\n" 55 "items. The mean is equal to the total of\n" 56 "all the data items divided by the number\n" 57 "of data items ( %d ). The mean value for\n" 58 "this run is: %d / %d = %.4f\n\n",

71

59 SIZE, total, SIZE, ( double ) total / SIZE ); 60 } /* end function mean */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 72: Algor-06 New Array 1

61 62 /* sort array and determine median element's value */ 63 void median( int answer[] ) 64 { 65 printf( "\n%s\n%s\n%s\n%s",

Outline

65 printf( \n%s\n%s\n%s\n%s ,

66 "********", " Median", "********", 67 "The unsorted array of responses is" ); 68 69 printArray( answer ); /* output unsorted array */ 70

fig06_16.c

(3 of 6 )70 71 bubbleSort( answer ); /* sort array */ 72 73 printf( "\n\nThe sorted array is" ); 74 printArray( answer ); /* output sorted array */

Once the array is sorted, the median will be the value of the middle element

75 76 /* display median element */ 77 printf( "\n\nThe median is element %d of\n" 78 "the sorted %d element array.\n" 79 "For this run the median is %d\n\n", 79 For this run the median is %d\n\n ,

80 SIZE / 2, SIZE, answer[ SIZE / 2 ] ); 81 } /* end function median */ 82 83 /* determine most frequent response */ 84 id d ( i t f [] t i t [] ) 84 void mode( int freq[], const int answer[] ) 85 { 86 int rating; /* counter for accessing elements 1-9 of array freq */ 87 int j; /* counter for summarizing elements 0-98 of array answer */ 88 int h; /* counter for diplaying histograms of elements in array freq */

72

89 int largest = 0; /* represents largest frequency */ 90 int modeValue = 0; /* represents most frequent response */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 73: Algor-06 New Array 1

91 92 printf( "\n%s\n%s\n%s\n", 93 "********", " Mode", "********" ); 94 95 /* initialize frequencies to 0 */

Outline

95 / initialize frequencies to 0 /

96 for ( rating = 1; rating <= 9; rating++ ) { 97 freq[ rating ] = 0; 98 } /* end for */ 99 100 /* summarize frequencies */

fig06_16.c

(4 of 6 )100 /* summarize frequencies */ 101 for ( j = 0; j < SIZE; j++ ) { 102 ++freq[ answer[ j ] ]; 103 } /* end for */ 104 105 /* output headers for result columns */ 106 printf( "%s%11s%19s\n\n%54s\n%54s\n\n", 107 "Response", "Frequency", "Histogram", 108 "1 1 2 2", "5 0 5 0 5" ); 109109 110 /* output results */ 111 for ( rating = 1; rating <= 9; rating++ ) { 112 printf( "%8d%11d ", rating, freq[ rating ] ); 113 114 /* k t k f d l d l t f l */ 114 /* keep track of mode value and largest frequency value */ 115 if ( freq[ rating ] > largest ) { 116 largest = freq[ rating ]; 117 modeValue = rating; 118 } /* end if */

73

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 74: Algor-06 New Array 1

119 120 /* output histogram bar representing frequency value */ 121 for ( h = 1; h <= freq[ rating ]; h++ ) { 122 printf( "*" ); 123 } /* end inner for */

Outline

123 } / end inner for /

124 125 printf( "\n" ); /* being new line of output */ 126 } /* end outer for */ 127 128 /* display the mode value */

fig06_16.c

(5 of 6 )128 /* display the mode value */ 129 printf( "The mode is the most frequent value.\n" 130 "For this run the mode is %d which occurred" 131 " %d times.\n", modeValue, largest ); 132 } /* end function mode */

133 134 /* function that sorts an array with bubble sort algorithm */

135 void bubbleSort( int a[] ) 136 { 137 int pass; /* pass counter */ 137 int pass; / pass counter /

138 int j; /* comparison counter */ 139 int hold; /* temporary location used to swap elements */ 140 141 /* loop to control number of passes */ 142 f ( 1 SIZE ) { 142 for ( pass = 1; pass < SIZE; pass++ ) { 143 144 /* loop to control number of comparisons per pass */ 145 for ( j = 0; j < SIZE - 1; j++ ) { 146

74

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 75: Algor-06 New Array 1

147 /* swap elements if out of order */ 148 if ( a[ j ] > a[ j + 1 ] ) { 149 hold = a[ j ]; 150 a[ j ] = a[ j + 1 ]; 151 a[ j + 1 ] = hold;

Outline

151 a[ j + 1 ] hold;

152 } /* end if */ 153 154 } /* end inner for */ 155 156 } /* end outer for */

fig06_16.c

(6 of 6 )156 } /* end outer for */ 157 158 } /* end function bubbleSort */ 159 160 /* output array contents (20 values per row) */ 161 void printArray( const int a[] ) 162 { 163 int j; /* counter */ 164 165 /* output array contents */ 165 / output array contents /

166 for ( j = 0; j < SIZE; j++ ) { 167 168 if ( j % 20 == 0 ) { /* begin new line every 20 values */ 169 printf( "\n" ); 170 } /* d if */ 170 } /* end if */ 171 172 printf( "%2d", a[ j ] ); 173 } /* end for */ 174

75

175 } /* end function printArray */

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 76: Algor-06 New Array 1

******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number

Outline

all the data items divided by the number of data items ( 99 ). The mean value for this run is: 681 / 99 = 6.8788 ******** Median

(1 of 2 )******** The unsorted array of responses is 6 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8 6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9 6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3 5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8 7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7 The sorted array is 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 (continued on next slide… )

76 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 77: Algor-06 New Array 1

(continued from previous slide…) The median is element 49 of the sorted 99 element array. For this run the median is 7 ********

Outline

Mode ******** Response Frequency Histogram 1 1 2 2 5 0 5 0 5

(2 of 2 ) 5 0 5 0 5 1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 5 8 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value.

For this run the mode is 8 which occurred 27 times. For this run the mode is 8 which occurred 27 times.

77 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 78: Algor-06 New Array 1

6.8 Searching Arraysg y78

Search an array for a key valueSearch an array for a key valueLinear search

Simple Simple Compare each element of array with key valueUseful for small and unsorted arraysUseful for small and unsorted arrays

Page 79: Algor-06 New Array 1

1 /* Fig. 6.18: fig06_18.c

2 Linear search of an array */

3 #include <stdio.h>

4 #define SIZE 100

5

Outline

5 6 /* function prototype */

7 int linearSearch( const int array[], int key, int size );

8 9 /* function main begins program execution */

10 int main( void )

fig06_18.c

(1 of 3 )10 int main( void ) 11 { 12 int a[ SIZE ]; /* create array a */ 13 int x; /* counter for initializing elements 0-99 of array a */ 14 int searchKey; /* value to locate in array a */ 15 int element; /* variable to hold location of searchKey or -1 */ 16 17 /* create data */ 18 for ( x = 0; x < SIZE; x++ ) { 19 a[ x ] = 2 * x; 19 a[ x ] 2 x;

20 } /* end for */ 21

79 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 80: Algor-06 New Array 1

22 printf( "Enter integer search key:\n" ); 23 scanf( "%d", &searchKey ); 24 25 /* attempt to locate searchKey in array a */ 26 element = linearSearch( a, searchKey, SIZE );

Outline

26 element linearSearch( a, searchKey, SIZE );

27 28 /* display results */ 29 if ( element != -1 ) { 30 printf( "Found value in element %d\n", element ); 31 } /* end if */

fig06_18.c

(2 of 3 )31 } /* end if */ 32 else { 33 printf( "Value not found\n" ); 34 } /* end else */ 35 36 return 0; /* indicates successful termination */ 37 38 } /* end main */ 39 40 /* compare key to every element of array until the location is found 40 / compare key to every element of array until the location is found

41 or until the end of array is reached; return subscript of element 42 if key or -1 if key is not found */ 43 int linearSearch( const int array[], int key, int size ) 44 { 45 i t /* t */ 45 int n; /* counter */ 46

80 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 81: Algor-06 New Array 1

47 /* loop through array */ 48 for ( n = 0; n < size; ++n ) { 49 50 if ( array[ n ] == key ) { 51 return n; /* return location of key */

Outline

51 return n; / return location of key /

52 } /* end if */ 53 54 } /* end for */ 55 56 return 1; /* key not found */

fig06_18.c

(3 of 3 )

Linear search algorithm searches through every element in the array until a match is found

56 return -1; /* key not found */ 57 58 } /* end function linearSearch */

Enter integer search key:

36 36

Found value in element 18

Enter integer search key: g y

37

Value not found

81 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 82: Algor-06 New Array 1

6.8 Searching Arraysg y82

Binary search yFor sorted arrays onlyCompares middle element with key

If equal, match foundIf key < middle, looks in first half of arrayIf key > middle looks in last halfIf key > middle, looks in last halfRepeat

Very fast; at most n steps, where 2n > number of elements

30 element array takes at most 5 steps25 > 30 so at most 5 stepsp

Page 83: Algor-06 New Array 1

1 /* Fig. 6.19: fig06_19.c

2 Binary search of an array */

3 #include <stdio.h>

4 #define SIZE 15

5

Outline

5 6 /* function prototypes */

7 int binarySearch( const int b[], int searchKey, int low, int high );

8 void printHeader( void );

9 void printRow( const int b[], int low, int mid, int high );

10

fig06_19.c

(1 of 6 )10 11 /* function main begins program execution */ 12 int main( void ) 13 { 14 int a[ SIZE ]; /* create array a */ 15 int i; /* counter for initializing elements 0-14 of array a */ 16 int key; /* value to locate in array a */ 17 int result; /* variable to hold location of key or -1 */ 18 19 /* create data */ 19 / create data /

20 for ( i = 0; i < SIZE; i++ ) { 21 a[ i ] = 2 * i; 22 } /* end for */ 23 24 i tf( "E t b b t 0 d 28 " ) 24 printf( "Enter a number between 0 and 28: " ); 25 scanf( "%d", &key ); 26 27 printHeader(); 28

83

29 /* search for key in array a */ 30 result = binarySearch( a, key, 0, SIZE - 1 );

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 84: Algor-06 New Array 1

31 32 /* display results */ 33 if ( result != -1 ) { 34 printf( "\n%d found in array element %d\n", key, result ); 35 } /* end if */

Outline

35 } / end if /

36 else { 37 printf( "\n%d not found\n", key ); 38 } /* end else */ 39 40 return 0; /* indicates successful termination */

fig06_19.c

(2 of 6 )40 return 0; /* indicates successful termination */ 41 42 } /* end main */ 43 44 /* function to perform binary search of an array */ 45 int binarySearch( const int b[], int searchKey, int low, int high ) 46 { 47 int middle; /* variable to hold middle element of array */ 48 49 /* loop until low subscript is greater than high subscript */ 49 / loop until low subscript is greater than high subscript /

50 while ( low <= high ) { 51 52 /* determine middle element of subarray being searched */ 53 middle = ( low + high ) / 2; 5454 55 /* display subarray used in this loop iteration */ 56 printRow( b, low, middle, high ); 57

84 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 85: Algor-06 New Array 1

58 /* if searchKey matched middle element, return middle */ 59 if ( searchKey == b[ middle ] ) { 60 return middle; 61 } /* end if */ 62

OutlineIf value is found, return its index

62 63 /* if searchKey less than middle element, set new high */ 64 else if ( searchKey < b[ middle ] ) { 65 high = middle - 1; /* search low end of array */ 66 } /* end else if */ 67

fig06_19.c

(3 of 6 )If value is too high search the left half of array67

68 /* if searchKey greater than middle element, set new low */ 69 else { 70 low = middle + 1; /* search high end of array */ 71 } /* end else */

If value is too high, search the left half of array

If l i l h h i h h lf f72 73 } /* end while */ 74 75 return -1; /* searchKey not found */ 76

If value is too low, search the right half of array

76 77 } /* end function binarySearch */ 78 79 /* Print a header for the output */ 80 void printHeader( void ) 81 { 81 { 82 int i; /* counter */ 83 84 printf( "\nSubscripts:\n" ); 85

85

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 86: Algor-06 New Array 1

86 /* output column head */ 87 for ( i = 0; i < SIZE; i++ ) { 88 printf( "%3d ", i ); 89 } /* end for */ 90

Outline

90 91 printf( "\n" ); /* start new line of output */ 92 93 /* output line of - characters */ 94 for ( i = 1; i <= 4 * SIZE; i++ ) { 95 printf( " " );

fig06_19.c

(4 of 6 )95 printf( "-" ); 96 } /* end for */ 97 98 printf( "\n" ); /* start new line of output */ 99 } /* end function printHeader */ 100 101 /* Print one row of output showing the current 102 part of the array being processed. */ 103 void printRow( const int b[], int low, int mid, int high ) 104 { 104 { 105 int i; /* counter for iterating through array b */ 106

86 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 87: Algor-06 New Array 1

107 /* loop through entire array */ 108 for ( i = 0; i < SIZE; i++ ) { 109 110 /* display spaces if outside current subarray range */ 111 if ( i < low || i > high ) {

Outline

111 if ( i < low || i > high ) { 112 printf( " " ); 113 } /* end if */ 114 else if ( i == mid ) { /* display middle element */ 115 printf( "%3d*", b[ i ] ); /* mark middle value */ 116 } /* end else if */

fig06_19.c

(5 of 6 )116 } /* end else if */ 117 else { /* display other elements in subarray */ 118 printf( "%3d ", b[ i ] ); 119 } /* end else */ 120 121 } /* end for */ 122 123 printf( "\n" ); /* start new line of output */ 124 } /* end function printRow */

Enter a number between 0 and 28: 25

Subscripts:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

------------------------------------------------------------

0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28

16 18 20 22* 24 26 28

24 26* 28

24*

87

25 not found (continued on next slide… )

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 88: Algor-06 New Array 1

(continued from previous slide…) Enter a number between 0 and 28: 8

Subscripts:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Outline

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

------------------------------------------------------------

0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28

0 2 4 6* 8 10 12

8 10* 12

8*

fig06_19.c

(6 of 6 ) 8*

8 found in array element 4

Enter a number between 0 and 28: 6

Subscripts:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

------------------------------------------------------------

0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28

0 2 4 6* 8 10 12

6 found in array element 3

88 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 89: Algor-06 New Array 1

6.9 Multiple-Subscripted Arraysp p y89

Multiple subscripted arrays Tables with rows and columns (m by n array)Like matrices: specify row, then column

InitializationInitializationint b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to zero

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Referencing elementse e e c g e e e sSpecify row, then column

printf( "%d", b[ 0 ][ 1 ] );

Page 90: Algor-06 New Array 1

Fig. 6.20 | Double-subscripted array ith th d f lwith three rows and four columns.

90

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 91: Algor-06 New Array 1

1 /* Fig. 6.21: fig06_21.c

2 Initializing multidimensional arrays */

3 #include <stdio.h>

4 5 void printArray( const int a[][ 3 ] ); /* function prototype */

Outline

5 void printArray( const int a[][ 3 ] ); / function prototype /

6 7 /* function main begins program execution */

8 int main( void )

9 {

10 /* initialize array1 array2 array3 */

fig06_21.c

(1 of 2 )10 /* initialize array1, array2, array3 */ 11 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; 12 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; 13 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; 14

array1 is initialized with both rows full

array2 and array3 are initialized only partially

15 printf( "Values in array1 by row are:\n" ); 16 printArray( array1 ); 17 18 printf( "Values in array2 by row are:\n" ); 19 printArray( array2 ); 19 printArray( array2 ); 20 21 printf( "Values in array3 by row are:\n" ); 22 printArray( array3 ); 23 24 t 0 /* i di t f l t i ti */ 24 return 0; /* indicates successful termination */ 25 26 } /* end main */ 27

91 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 92: Algor-06 New Array 1

28 /* function to output array with two rows and three columns */ 29 void printArray( const int a[][ 3 ] ) 30 { 31 int i; /* row counter */ 32 int j; /* column counter */

Outline

32 int j; / column counter /

33 34 /* loop through rows */ 35 for ( i = 0; i <= 1; i++ ) { 36 37 /* output column values */

fig06_21.c

(2 of 2 )37 /* output column values */ 38 for ( j = 0; j <= 2; j++ ) { 39 printf( "%d ", a[ i ][ j ] ); 40 } /* end inner for */ 41 42 printf( "\n" ); /* start new line of output */ 43 } /* end outer for */ 44 45 } /* end function printArray */

Values in array1 by row are:

1 2 3

4 5 6

Values in array2 by row are:

1 2 3 1 2 3

4 5 0

Values in array3 by row are:

1 2 0

4 0 0

92

Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 93: Algor-06 New Array 1

1 /* Fig. 6.22: fig06_22.c

2 Double-subscripted array example */

3 #include <stdio.h>

4 #define STUDENTS 3

5 #define EXAMS 4

Outline

5 #define EXAMS 4

6 7 /* function prototypes */

8 int minimum( const int grades[][ EXAMS ], int pupils, int tests );

9 int maximum( const int grades[][ EXAMS ], int pupils, int tests );

10 double average( const int setOfGrades[] int tests );

fig06_22.c

(1 of 6 )10 double average( const int setOfGrades[], int tests ); 11 void printArray( const int grades[][ EXAMS ], int pupils, int tests ); 12 13 /* function main begins program execution */ 14 int main( void ) 15 { 16 int student; /* student counter */ 17 18 /* initialize student grades for three students (rows) */ 19 const int studentGrades[ STUDENTS ][ EXAMS ] = 19 const int studentGrades[ STUDENTS ][ EXAMS ]

20 { { 77, 68, 86, 73 }, 21 { 96, 87, 89, 78 }, 22 { 70, 90, 86, 81 } }; 23 24 /* t t t d tG d */

Each row in the array corresponds to a single student’s set of grades

24 /* output array studentGrades */ 25 printf( "The array is:\n" ); 26 printArray( studentGrades, STUDENTS, EXAMS ); 27

93 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 94: Algor-06 New Array 1

28 /* determine smallest and largest grade values */ 29 printf( "\n\nLowest grade: %d\nHighest grade: %d\n", 30 minimum( studentGrades, STUDENTS, EXAMS ), 31 maximum( studentGrades, STUDENTS, EXAMS ) ); 32

Outline

32 33 /* calculate average grade for each student */ 34 for ( student = 0; student < STUDENTS; student++ ) { 35 printf( "The average grade for student %d is %.2f\n", 36 student, average( studentGrades[ student ], EXAMS ) ); 37 } /* end for */

fig06_22.c

(2 of 6 )37 } /* end for */ 38 39 return 0; /* indicates successful termination */ 40 41 } /* end main */

average function is passed a row of the array

42

94 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 95: Algor-06 New Array 1

43 /* Find the minimum grade */ 44 int minimum( const int grades[][ EXAMS ], int pupils, int tests ) 45 { 46 int i; /* student counter */ 47 int j; /* exam counter */

Outline

47 int j; / exam counter /

48 int lowGrade = 100; /* initialize to highest possible grade */ 49 50 /* loop through rows of grades */ 51 for ( i = 0; i < pupils; i++ ) { 52

fig06_22.c

(3 of 6 )52 53 /* loop through columns of grades */ 54 for ( j = 0; j < tests; j++ ) { 55 56 if ( grades[ i ][ j ] < lowGrade ) { 57 lowGrade = grades[ i ][ j ]; 58 } /* end if */ 59 60 } /* end inner for */ 6161 62 } /* end outer for */ 63 64 return lowGrade; /* return minimum grade */ 65 66 } /* d f ti i i */ 66 } /* end function minimum */ 67

95 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 96: Algor-06 New Array 1

68 /* Find the maximum grade */ 69 int maximum( const int grades[][ EXAMS ], int pupils, int tests ) 70 { 71 int i; /* student counter */ 72 int j; /* exam counter */

Outline

72 int j; / exam counter /

73 int highGrade = 0; /* initialize to lowest possible grade */ 74 75 /* loop through rows of grades */ 76 for ( i = 0; i < pupils; i++ ) { 77

fig06_22.c

(4 of 6 )77 78 /* loop through columns of grades */ 79 for ( j = 0; j < tests; j++ ) { 80 81 if ( grades[ i ][ j ] > highGrade ) { 82 highGrade = grades[ i ][ j ]; 83 } /* end if */ 84 85 } /* end inner for */ 8686 87 } /* end outer for */ 88 89 return highGrade; /* return maximum grade */ 90 91 } /* d f ti i */ 91 } /* end function maximum */ 92

96 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 97: Algor-06 New Array 1

93 /* Determine the average grade for a particular student */ 94 double average( const int setOfGrades[], int tests ) 95 { 96 int i; /* exam counter */ 97 int total = 0; /* sum of test grades */

Outline

97 int total 0; / sum of test grades /

98 99 /* total all grades for one student */ 100 for ( i = 0; i < tests; i++ ) { 101 total += setOfGrades[ i ]; 102 } /* end for */

fig06_22.c

(5 of 6 )102 } /* end for */ 103 104 return ( double ) total / tests; /* average */ 105 106 } /* end function average */ 107 108 /* Print the array */ 109 void printArray( const int grades[][ EXAMS ], int pupils, int tests ) 110 { 111 int i; /* student counter */ 111 int i; / student counter /

112 int j; /* exam counter */ 113 114 /* output column heads */ 115 printf( " [0] [1] [2] [3]" ); 116116

97 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 98: Algor-06 New Array 1

117 /* output grades in tabular format */ 118 for ( i = 0; i < pupils; i++ ) { 119 120 /* output label for row */ 121 printf( "\nstudentGrades[%d] ", i );

Outline

121 printf( \nstudentGrades[%d] , i );

122 123 /* output grades for one student */ 124 for ( j = 0; j < tests; j++ ) { 125 printf( "%-5d", grades[ i ][ j ] ); 126 } /* end inner for */

fig06_22.c

(6 of 6 )126 } /* end inner for */ 127 128 } /* end outer for */ 129 130 } /* end function printArray */

The array is:

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

studentGrades[0] 77 68 86 73

studentGrades[1] 96 87 89 78

studentGrades[2] 70 90 86 81

Lowest grade: 68

Highest grade: 96

The average grade for student 0 is 76.00 g g

The average grade for student 1 is 87.50

The average grade for student 2 is 81.75

98 Diambil dari materi Deitel – Deitel, C How to program Pearson

Education Inc.

Page 99: Algor-06 New Array 1

699

C ArraysC Arrays

Page 100: Algor-06 New Array 1

Now go write it before them in a tableNow go, write it before them in a table,and note it in a book.

Isaiah 30:8

To go beyond is as wrong as to fall short.Confucius

Begin at the beginning Begin at the beginning, …and go on till you come to the end: then stop.

Lewis Carroll

100

Page 101: Algor-06 New Array 1

OBJECTIVES101

In this chapter you will learn: p yTo use the array data structure to represent lists and tables of values.To define an array, initialize an array and refer to individual elements of an array.To define symbolic constantsTo define symbolic constants.To pass arrays to functions. To use arrays to store sort and search lists and tables To use arrays to store, sort and search lists and tables of values.To define and manipulate multiple-subscripted arrays.

Page 102: Algor-06 New Array 1

102

6.1 Introduction 6.2 Arrays 6.3 Defining Arrays6 4 A E l6.4 Array Examples6.5 Passing Arrays to Functions6 6 Sorting Arrays6.6 Sorting Arrays6.7 Case Study: Computing Mean, Median and Mode Using Arrays6.8 Searching Arrays6.9 Multiple-Subscripted Arrays

Page 103: Algor-06 New Array 1

6.1 Introduction103

Arrays Arrays Structures of related data itemsStatic entity – same size throughout programStatic entity same size throughout programDynamic data structures discussed in Chapter 12

Page 104: Algor-06 New Array 1

6.2 Arraysy104

ArrayGroup of consecutive memory locations Same name and type

To refer to an element specifyTo refer to an element, specifyArray namePosition number

Format:arrayname[ position number ]

First element at position 0First element at position 0n element array named c:

c[ 0 ], c[ 1 ]...c[ n – 1 ]

Page 105: Algor-06 New Array 1

Fig. 6.1 | 12-element array. g | y105

Page 106: Algor-06 New Array 1

6.2 Arraysy106

Array elements are like normal variablesArray elements are like normal variablesc[ 0 ] = 3;printf( "%d", c[ 0 ] );

Perform operations in subscript. If x equals 3c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 107: Algor-06 New Array 1

Common Programming Error 6.1g g107

It is important to note the difference between the It is important to note the difference between the “seventh element of the array” and “array element seven.” Because array subscripts begin at 0, the y p g ,“seventh element of the array” has a subscript of 6, while “array element seven” has a subscript of 7 and is actually the eighth element of the array. This is a source of “off-by-one” errors.

Page 108: Algor-06 New Array 1

108

Operators Associativity Typep y yp

[] () left to right highest

++ -- !

(type) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

g

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment Fig. 6.2 | Operator precedence. , left to right comma

Page 109: Algor-06 New Array 1

6.3 Defining Arraysg y109

When defining arrays, specifyWhen defining arrays, specifyNameType of arrayType of arrayNumber of elements

arrayType arrayName[ numberOfElements ];

Examples:int c[ 10 ]; float myArray[ 3284 ];

Defining multiple arrays of same typeFormat similar to regular variablesExample:

b[ 100 ] [ 27 ]

Page 110: Algor-06 New Array 1

6.4 Array Examplesy p110

InitializersInitializersint n[ 5 ] = { 1, 2, 3, 4, 5 };

If not enough initializers, rightmost elements become 0g , gint n[ 5 ] = { 0 }

All elements 0

If too many initializers, a syntax error occursC arrays have no bounds checking

f d l dIf size omitted, initializers determine itint n[ ] = { 1, 2, 3, 4, 5 };

5 i iti li th f 5 l t 5 initializers, therefore 5 element array

Page 111: Algor-06 New Array 1

1 /* Fig. 6.3: fig06_03.c

2 initializing an array */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

5 / function main begins program execution /

6 int main( void )

7 {

8 int n[ 10 ]; /* n is an array of 10 integers */

9 int i; /* counter */

10

fig06_03.c

(1 of 2 )10 11 /* initialize elements of array n to 0 */ 12 for ( i = 0; i < 10; i++ ) { 13 n[ i ] = 0; /* set element at location i to 0 */ 14 } /* end for */

for loop initializes each array element separately

15 16 printf( "%s%13s\n", "Element", "Value" ); 17 18 /* output contents of array n in tabular format */ 19 for ( i = 0; i < 10; i++ ) { for loop outputs all array19 for ( i 0; i < 10; i++ ) {

20 printf( "%7d%13d\n", i, n[ i ] ); 21 } /* end for */ 22 23 return 0; /* indicates successful termination */ 24

for loop outputs all array elements

24 25 } /* end main */

111

Page 112: Algor-06 New Array 1

Element Value

0 0

1 0

2 0

Outline

3 0

4 0

5 0

6 0

7 0

fig06_03.c

(2 of 2 )

8 0

9 0

112

Page 113: Algor-06 New Array 1

1 /* Fig. 6.4: fig06_04.c

2 Initializing an array with an initializer list */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

6 int main( void )

7 {

8 /* use initializer list to initialize array n */

9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

10 int i; /* counter */

fig06_04.c

(1 of 2 )

11 12 printf( "%s%13s\n", "Element", "Value" ); 13 14 /* output contents of array in tabular format */ 15 for ( i = 0; i < 10; i++ ) {

initializer list initializes all array elements simultaneously15 for ( i 0; i < 10; i++ ) {

16 printf( "%7d%13d\n", i, n[ i ] ); 17 } /* end for */ 18 19 return 0; /* indicates successful termination */ 20

simultaneously

20 21 } /* end main */

113

Page 114: Algor-06 New Array 1

Element Value

0 32

1 27

2 64

3 18

Outline

3 18

4 95

5 14

6 90

7 70

8 60

fig06_04.c

(2 of 2 ) 8 60

9 37

114

Page 115: Algor-06 New Array 1

Common Programming Error 6.2g g115

Forgetting to initialize the elements of anForgetting to initialize the elements of anarray whose elements should be initialized.

Page 116: Algor-06 New Array 1

Common Programming Error 6.3g g116

Providing more initializers in an arrayProviding more initializers in an arrayinitializer list than there are elementsin the array is a syntax error.y y

Page 117: Algor-06 New Array 1

1 /* Fig. 6.5: fig06_05.c

2 Initialize the elements of array s to the even integers from 2 to 20 */

3 #include <stdio.h>

4 #define SIZE 10 /* maximum size of array */

5

Outline#define directive tells compiler to replace all

instances of the word SIZE with 10 5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* symbolic constant SIZE can be used to specify array size */

10 int s[ SIZE ]; /* array s has SIZE elements */

fig06_05.c

(1 of 2 )

instances of the word SIZE with 10

SIZE i l d ith 10 b th10 int s[ SIZE ]; /* array s has SIZE elements */ 11 int j; /* counter */ 12 13 for ( j = 0; j < SIZE; j++ ) { /* set the values */ 14 s[ j ] = 2 + 2 * j;

SIZE is replaced with 10 by the compiler, so array s has 10 elements

for loop initializes each array 15 } /* end for */ 16 17 printf( "%s%13s\n", "Element", "Value" ); 18 19 /* output contents of array s in tabular format */

p yelement separately

19 / output contents of array s in tabular format /

20 for ( j = 0; j < SIZE; j++ ) { 21 printf( "%7d%13d\n", j, s[ j ] ); 22 } /* end for */ 23 24 t 0 /* i di t f l t i ti */ 24 return 0; /* indicates successful termination */ 25 26 } /* end main */

117

Page 118: Algor-06 New Array 1

Element Value

0 2

1 4

2 6

Outline

3 8

4 10

5 12

6 14

7 16

fig06_05.c

(2 of 2 )

8 18

9 20

118

Page 119: Algor-06 New Array 1

Common Programming Error 6.4g g119

Ending a #define or #include preprocessor Ending a #define or #include preprocessor directive with a semicolon. Remember that preprocessor directives are not C statements. p p

Page 120: Algor-06 New Array 1

Common Programming Error 6.5g g120

Assigning a value to a symbolic constant inAssigning a value to a symbolic constant inan executable statement is a syntax error.A symbolic constant is not a variable. Noyspace is reserved for it by the compiler as with variables that hold values at execution time.

Page 121: Algor-06 New Array 1

Software Engineering Observation 6 16.1

121

Defining the size of each array as a symbolic Defining the size of each array as a symbolic constant makes programs more scalable.

Page 122: Algor-06 New Array 1

Good Programming Practice 6.1g g122

Use only uppercase letters for symbolic constant Use only uppercase letters for symbolic constant names. This makes these constants stand out in a program and reminds you that symbolic constants p g y yare not variables.

Page 123: Algor-06 New Array 1

Good Programming Practice 6.2g g123

In multiword symbolic constant names, use In multiword symbolic constant names, use underscores to separate the words for readability.

Page 124: Algor-06 New Array 1

1 /* Fig. 6.6: fig06_06.c

2 Compute the sum of the elements of the array */

3 #include <stdio.h>

4 #define SIZE 12

5

Outline

5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* use initializer list to initialize array */

10 int a[ SIZE ] { 1 3 5 4 7 2 99 16 45 67 89 45 };

fig06_06.c

10 int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; 11 int i; /* counter */ 12 int total = 0; /* sum of array */ 13 14 /* sum contents of array a */

initializer list initializes all array elements simultaneously15 for ( i = 0; i < SIZE; i++ ) {

16 total += a[ i ]; 17 } /* end for */ 18 19 printf( "Total of array element values is %d\n", total );

simultaneouslyfor loop adds each element of

the array to variable total19 printf( Total of array element values is %d\n , total );

20 21 return 0; /* indicates successful termination */ 22 23 } /* end main */

Total of array element values is 383

124

Page 125: Algor-06 New Array 1

1 /* Fig. 6.7: fig06_07.c

2 Student poll program */

3 #include <stdio.h>

4 #define RESPONSE_SIZE 40 /* define array sizes */

5 #define FREQUENCY SIZE 11

Outline#define directives

create symbolic 5 #define FREQUENCY_SIZE 11

6 7 /* function main begins program execution */

8 int main( void )

9 {

10 int answer; /* counter to loop through 40 responses */

fig06_07.c

(1 of 2 )

create symbolic constants

10 int answer; /* counter to loop through 40 responses */ 11 int rating; /* counter to loop through frequencies 1-10 */ 12 13 /* initialize frequency counters to 0 */ 14 int frequency[ FREQUENCY_SIZE ] = { 0 };

frequency array is d fi d ith 1115

16 /* place the survey responses in the responses array */ 17 int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 18 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };

defined with 11 elements responses array is

defined with 40 19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; 20 21 /* for each answer, select value of an element of array responses 22 and use that value as subscript in array frequency to

23 determine element to increment */

24 f ( 0 RESPONSE SIZE ) {

elements and its elements are initialized

24 for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) { 25 ++frequency[ responses [ answer ] ]; 26 } /* end for */ 27

subscript of frequency array is given by value in responsesarray

125

y

Page 126: Algor-06 New Array 1

28 /* display results */ 29 printf( "%s%17s\n", "Rating", "Frequency" ); 30 31 /* output the frequencies in a tabular format */ 32 for ( rating = 1; rating < FREQUENCY SIZE; rating++ ) {

Outline

32 for ( rating 1; rating < FREQUENCY_SIZE; rating++ ) {

33 printf( "%6d%17d\n", rating, frequency[ rating ] ); 34 } /* end for */ 35 36 return 0; /* indicates successful termination */ 37

fig06_07.c

(2 of 2 )37 38 } /* end main */

Rating Frequency

1 2

2 2 2 2

3 2

4 2

5 5

6 11

7 5

8 7

9 1

10 3

126

Page 127: Algor-06 New Array 1

Good Programming Practice 6.3g g127

Strive for program clarity. Sometimes it may be Strive for program clarity. Sometimes it may be worthwhile to trade off the most efficient use of memory or processor time in favor of writing y p gclearer programs.

Page 128: Algor-06 New Array 1

Performance Tip 6.1p128

Sometimes performance considerationsSometimes performance considerationsfar outweigh clarity considerations.

Page 129: Algor-06 New Array 1

Common Programming Error 6.6g g129

Referring to an element outside the array bounds.Referring to an element outside the array bounds.

Page 130: Algor-06 New Array 1

Error-Prevention Tip 6.1p130

When looping through an array, the array subscript When looping through an array, the array subscript should never go below 0 and should always be less than the total number of elements in the array (size y (– 1). Make sure the loop-terminating condition prevents accessing elements outside this range.

Page 131: Algor-06 New Array 1

Error-Prevention Tip 6.2p131

Programs should validate the correctness of all input Programs should validate the correctness of all input values to prevent erroneous information from affecting a program’s calculations.g p g

Page 132: Algor-06 New Array 1

1 /* Fig. 6.8: fig06_08.c

2 Histogram printing program */

3 #include <stdio.h>

4 #define SIZE 10

5

Outline

5 6 /* function main begins program execution */

7 int main( void )

8 {

9 /* use initializer list to initialize array n */

10 int n[ SIZE ] { 19 3 15 7 11 9 13 5 17 1 };

fig06_08.c

(1 of 2 )10 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 11 int i; /* outer for counter for array elements */ 12 int j; /* inner for counter counts *s in each histogram bar */ 13 14 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); 15 16 /* for each element of array n, output a bar of the histogram */ 17 for ( i = 0; i < SIZE; i++ ) { 18 printf( "%7d%13d ", i, n[ i ]) ; 1919 20 for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */ 21 printf( "%c", '*' ); 22 } /* end inner for */

23 24 i tf( "\ " ) /* d hi t b */

nested for loop prints n[ i ] asterisks on the ith line

24 printf( "\n" ); /* end a histogram bar */ 25 } /* end outer for */ 26 27 return 0; /* indicates successful termination */ 28

132

29 } /* end main */

Page 133: Algor-06 New Array 1

Element Value Histogram

0 19 *******************

1 3 ***

2 15 ***************

Outline

3 7 *******

4 11 ***********

5 9 *********

6 13 *************

7 5 *****

fig06_08.c

(2 of 2 )

8 17 *****************

9 1 *

133

Page 134: Algor-06 New Array 1

1 /* Fig. 6.9: fig06_09.c

2 Roll a six-sided die 6000 times */

3 #include <stdio.h>

4 #include <stdlib.h>

5 #include <time.h>

Outline

5 #include <time.h>

6 #define SIZE 7

7 8 /* function main begins program execution */

9 int main( void )

10 {

fig06_09.c

(1 of 2 )10 { 11 int face; /* random die value 1 - 6 */ 12 int roll; /* roll counter 1-6000 */ 13 int frequency[ SIZE ] = { 0 }; /* clear counts */ 14 15 srand( time( NULL ) ); /* seed random-number generator */ 16 17 /* roll die 6000 times */ 18 for ( roll = 1; roll <= 6000; roll++ ) { 19 face = 1 + rand() % 6; 19 face 1 + rand() % 6;

20 ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */ 21 } /* end for */

for loop uses one array to trackfor loop uses one array to track number of times each number is rolled instead of using 6 variables and a switch

134

statement

Page 135: Algor-06 New Array 1

22 23 printf( "%s%17s\n", "Face", "Frequency" ); 24 25 /* output frequency elements 1-6 in tabular format */ 26 for ( face = 1; face < SIZE; face++ ) {

Outline

26 for ( face 1; face < SIZE; face++ ) {

27 printf( "%4d%17d\n", face, frequency[ face ] ); 28 } /* end for */ 29 30 return 0; /* indicates successful termination */ 31

fig06_09.c

(2 of 2 )31 32 } /* end main */

Face Frequency

1 1029

2 951 2 951

3 987

4 1033

5 1010

6 990

135

Page 136: Algor-06 New Array 1

6.4 Array Examplesy p136

Character arraysString “first” is really a static array of charactersCharacter arrays can be initialized using string literals

char string1[] = "first";Null character '\0' terminates stringsstring1 actually has 6 elements

It is equivalent to

h t i 1[] = { 'f' 'i' ' ' ' ' 't' '\0' }char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };Can access individual characters

string1[ 3 ] is character ‘s’A i dd f & d d f f Array name is address of array, so & not needed for scanf

scanf( "%s", string2 );Reads characters until whitespace encounteredBe careful not to write past end of array as it is possible to do soBe careful not to write past end of array, as it is possible to do so

Page 137: Algor-06 New Array 1

Common Programming Error 6.7g g137

Not providing scanf with a character array large Not providing scanf with a character array large enough to store a string typed at the keyboard can result in destruction of data in a program and other p gruntime errors. This can also make a system susceptible to worm and virus attacks.

Page 138: Algor-06 New Array 1

1 /* Fig. 6.10: fig06_10.c

2 Treating character arrays as strings */

3 #include <stdio.h>

4 5 /* function main begins program execution */

Outline

5 / function main begins program execution /

6 int main( void )

7 {

8 char string1[ 20 ]; /* reserves 20 characters */

9 char string2[] = "string literal"; /* reserves 15 characters */

10 int i; /* counter */

fig06_10.c

(1 of 2 )10 int i; /* counter */ 11 12 /* read string from user into array string1 */ 13 printf("Enter a string: "); 14 scanf( "%s", string1 ); /* input ended by whitespace character */

string2 array is defined with one element for each character, so 15 elements including null character /0

15 16 /* output strings */ 17 printf( "string1 is: %s\nstring2 is: %s\n" 18 "string1 with spaces between characters is:\n", 19 string1, string2 );

/0

19 string1, string2 ); 20 21 /* output characters until null character is reached */ 22 for ( i = 0; string1[ i ] != '\0'; i++ ) { 23 printf( "%c ", string1[ i ] ); 24 } /* d f */

for loop prints characters of string1 array with spaces in24 } /* end for */

25 26 printf( "\n" ); 27 28 return 0; /* indicates successful termination */

string1 array with spaces in between

138

29 30 } /* end main */

Page 139: Algor-06 New Array 1

Enter a string: Hello there

string1 is: Hello

string2 is: string literal

string1 with spaces between characters is:

Outline

H e l l o

fig06_10.c

(2 of 2 )

139

Page 140: Algor-06 New Array 1

Performance Tip 6.2p140

In functions that contain automatic arrays where the In functions that contain automatic arrays where the function is in and out of scope frequently, make the array static so it is not created each time the yfunction is called.

Page 141: Algor-06 New Array 1

1 /* Fig. 6.11: fig06_11.c

2 Static arrays are initialized to zero */

3 #include <stdio.h>

4 5 void staticArrayInit( void ); /* function prototype */

Outline

5 void staticArrayInit( void ); / function prototype /

6 void automaticArrayInit( void ); /* function prototype */

7 8 /* function main begins program execution */

9 int main( void )

10 {

fig06_11.c

(1 of 4 )10 { 11 printf( "First call to each function:\n" ); 12 staticArrayInit(); 13 automaticArrayInit(); 14 15 printf( "\n\nSecond call to each function:\n" ); 16 staticArrayInit(); 17 automaticArrayInit(); 18 19 return 0; /* indicates successful termination */ 19 return 0; / indicates successful termination /

20 21 } /* end main */ 22

141

Page 142: Algor-06 New Array 1

23 /* function to demonstrate a static local array */ 24 void staticArrayInit( void ) 25 { 26 /* initializes elements to 0 first time function is called */ 27 static int array1[ 3 ];

Outline

t ti i t d l27 static int array1[ 3 ]; 28 int i; /* counter */ 29 30 printf( "\nValues on entering staticArrayInit:\n" ); 31 32 /* output contents of array1 */

fig06_11.c

(2 of 4 )

static array is created only once, when staticArrayInit is first called

32 /* output contents of array1 */ 33 for ( i = 0; i <= 2; i++ ) { 34 printf( "array1[ %d ] = %d ", i, array1[ i ] ); 35 } /* end for */ 36 37 printf( "\nValues on exiting staticArrayInit:\n" ); 38 39 /* modify and output contents of array1 */ 40 for ( i = 0; i <= 2; i++ ) { 41 printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 ); 41 printf( array1[ %d ] %d , i, array1[ i ] + 5 );

42 } /* end for */ 43 44 } /* end function staticArrayInit */

142

Page 143: Algor-06 New Array 1

45 46 /* function to demonstrate an automatic local array */ 47 void automaticArrayInit( void ) 48 { 49 /* initializes elements each time function is called */

Outline

49 / initializes elements each time function is called /

50 int array2[ 3 ] = { 1, 2, 3 }; 51 int i; /* counter */ 52 53 printf( "\n\nValues on entering automaticArrayInit:\n" ); 54

fig06_11.c

(3 of 4 )

automatic array is recreated every time automaticArrayInit is called

54 55 /* output contents of array2 */ 56 for ( i = 0; i <= 2; i++ ) { 57 printf("array2[ %d ] = %d ", i, array2[ i ] ); 58 } /* end for */ 59 60 printf( "\nValues on exiting automaticArrayInit:\n" ); 61 62 /* modify and output contents of array2 */ 63 for ( i = 0; i <= 2; i++ ) { 63 for ( i 0; i < 2; i++ ) {

64 printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 ); 65 } /* end for */ 66 67 } /* end function automaticArrayInit */

143

Page 144: Algor-06 New Array 1

First call to each function:

Values on entering staticArrayInit:

array1[ 0 ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0

Outline

Values on exiting staticArrayInit:

array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5

Values on entering automaticArrayInit:

array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3

fig06_11.c

(4 of 4 )y y y

Values on exiting automaticArrayInit:

array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

Second call to each function:

Values on entering staticArrayInit:

array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5

Values on exiting staticArrayInit:

array1[ 0 ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10

Values on entering automaticArrayInit:

array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3

Values on exiting automaticArrayInit:

array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

144

Page 145: Algor-06 New Array 1

Common Programming Error 6.8g g145

Assuming that elements of a local staticAssuming that elements of a local staticarray are initialized to zero every time the function in which the array is defined is called.y