CS计算机代考程序代写 c/c++ compiler algorithm Lecture 5: Static Arrays (1D/2D)

Lecture 5: Static Arrays (1D/2D)

Computer Programming

Example 1

2

! Input the marks for 10 students
! Store the marks in variables
! Compute the average marks
! Print the marks of the students and the average

100 30 44 66 50 60 80 75 80 100

The mark of the students are: 100, 30,

44, 66, 50, 60, 80, 75, 80, 100

Average mark=68

The program

3

/*define variables for storing 10 students’ mark*/

int mark1, mark2, mark3, mark4, mark5,

mark6, mark7, mark8, mark9, mark10, average;

/*input marks of student*/

cin >> mark1 >> mark2 >> mark3 >> mark4 >>

mark5 >> mark6 >> mark7 >> mark8 >> mark9 >> mark10;

/*print the marks*/

cout << "The mark of the students are: " << mark1<<", " << mark2 <<", " << mark3 <<", " << mark4 <<", " << mark5 <<", " << mark6 <<", " << mark7 <<", " << mark8 <<", " << mark9 <<", " << mark10 << endl; average=(mark1+mark2+mark3+mark4+mark5 +mark6+mark7+mark8+mark9+mark10)/10; cout << "Average mark"<< average << endl; Is it easy to extend the program to handle more students? What is an Array? 4 ! Sequence of data items that are of the same type ! Stored contiguously in physical memory ! Can be accessed by integer index (constant number or variable) IMPORTANT! First item is having index [0], but NOT [1] ! 5int x; x=5; int a[6]; a [0] a [1] a [2] a [3] a [4] a [5] 5 7 2 a[0]=5; a[1]=7; a[2]=2; Array definition 5 There are ten elements in this array mark[0], mark[1], ……, mark[9] The ith array element is accesses as mark[i-1]. (Not mark[i]!) The range of the index i ranges from 0 to array_size-1 The location mark[10] is invalid. Array index out of bound! (compiler will not tell you) int mark[10]; Data type of the array element Size of the array Name of the array mark[10] Array definition ! The size of the array must be know when declared: Ok: int mark[10]; ! Many compilers do NOT support variable size: Problematic: cin>>size; int mark[ size ];
(So.. Let’s consider the worse case and make sure that you declare enough!…)

! The only exception is constant variable:
Ok: const int size=5; int mark[ size ];

! The size could be omitted if the initial values are provided:
Ok: int fiveValues[] = {10,20,30,40,50};

Ask compiler to count for you!
The implicit size here is 5

Storing values to array elements

7

! Suppose the mark for the first student is 30. We can use
the notation

mark[0] = 30;

! Example: Reading the marks of the second student
cin >> mark[1];

! Example: Reading the marks for 10 student
for (i=0;i<10;i++) cin >> mark[i];

Index can be constant (e.g. 1, 2, 3)

Index can also be a variable (e.g. x, y)
or even an expression (e.g. x+y*3-1)

Advantage of Array:
-Can use Loops for repeated reading/writing
-Can use Loops for operations like Sum/Average/Search/find Max

Retrieving the values of an array element

8

! Example: Print the mark of the second student

cout << mark[1]; ! Example: Sum the mark of all the students: sum = 0; //IMPORTANT! for (i=0;i<10;i++) { cout << mark[i]; sum = sum + mark[i]; } Summary of Array Declaration and Access 9 char x[5]; double x[20]; float x[10]; int x[20]; ArrayType Variable Variable Access Array Access int int x; x=1; x[0]=1 float float x; x=3.4; x[0]=3.4; x[1]=1.2; double double x; x=0.7; x[0]=0.7; x[3]=3.4; char char x; x='a'; x[0]='c'; X[1]='s'; Note: Use single quotation mark to access individual character in array ! Example 1 (Average of 10 elements with Array) 10 /*define variables for storing10 students' mark*/ int marks[10], i; double sum=0, average; /*input marks of student*/ for (i=0;i<10;i++) cin >> mark[i];

/*print the marks*/

cout << "The mark of the students are:"; for (i=0;i<10;i++) { cout << mark[i] << " "; sum=sum + mark[i]; } /*compute and print the average*/ average=sum/10; cout << "Average mark= " << average << endl; Note: Don't write for (i=1;i<=10;) since arrays start with 0 not 1 ! Use double if you want average with decimal places… Just like normal int variable, can declare together with comma Example 2: counting / statistics 11 ! Input a sequence of digits {0, 1, 2, …, 9}, which is terminated by -1 ! Count the frequency of occurrence of each digit ! Use an integer array count of 10 elements ! count[i] stores the frequency of occurrence of digit i 9 The program: buggy version 12 #include
using namespace std;

void main(){
int count[10]; //frequency of occurrence of digits
int digit; //input digit.
int i; //loop counter

//read the digits
do {

cin >> digit;
if (digit>=0 && digit<=9) count[digit]++; } while(digit != -1); //stop if the input number is -1 //print the frequency for (i=0; i<10;i++){ cout << "Frequency of " << i << " is " << count[i] << endl; } } The actual output (incorrect!) 13 3 4 1 3 1 3 -1 Frequency of 0 is 2089878893 Frequency of 1 is 2088886165 Frequency of 2 is 1376256 Frequency of 3 is 3 Frequency of 4 is 1394145 Frequency of 5 is 1245072 Frequency of 6 is 4203110 Frequency of 7 is 1394144 Frequency of 8 is 0 Frequency of 9 is 1310720 The exact values in your system may differ. but obviously the numbers are not making sense If your program generates different output in PASS and Local PC, it could be caused by this problem… It's a good practice to initialize arrays 14 ! Otherwise, the values of the elements in the array is unpredictable. ! A common way to initialize an array is to set all the elements to zero for (i=0; i<10; i++) count[i]=0; ! For information: Arrays declared in global scope are initialized with zeroes when the program start! Array initializer 15 int mark [10]={100, 90}; ! Define an array of 10 elements, set the 1st element to 100 and the 2nd element to 90. ! If we list fewer values than the array size (10). The remaining elements are set to 0 by default ! To initialize all elements to 0: int mark[10]={0}; ! IMPORTANT: This notation is ONLY allowed during initialization! int X[3] = {1,2,3}; CORRECT int X[3]; X = {1,2,3}; WRONG! Cannot write = {…} here ! The program: buggy version 16 #include
using namespace std;

void main(){
int count[10]; //frequency of occurrence of digits
int digit; //input digit.
int i; //loop counter

//read the digits
do {

cin >> digit;
if (digit>=0 && digit<=9) count[digit]++; } while(digit != -1); //stop if the input number is -1 //print the frequency for (i=0; i<10;i++){ cout << "Frequency of " << i << " is " << count[i] << endl; } } Correct program 17 #include
using namespace std;
void main(){

int count[10];
int digit;
int i;

//initialization
for (i=0;i<10;i++){ count[i]=0; } //read the digits do { cin >> digit;
if (digit>=0 && digit<=9) count[digit]++; } while(digit != -1); //stop if the input number is -1 //print the frequency for (i=0; i<10;i++){ cout << "Frequency of " << i << " is " << count[i] << endl; } } Side Notes: By changing the if() statement a little bit, you may use it to count other data: e.g. Count only Uppercase: if (ch>=’A’ && ch<='Z') count[ ch – 'A' ]++; i.e. Ask the compiler to count for you… Note: you MUST provide initial values if there's no size Array Initialization Summary 18 Example 3: Comparing 2 arrays 19 ! We have two integers arrays, each with 5 elements int array1[5]={10, 5, 3, 5, 1}; int array2[5]; ! The user input the values of array2 ! Compare whether all the elements in array1 and array2 are the same Array equality 20 ! Note that you have to compare array element 1 by 1. ! The following code is WRONG! if (array1 == array2) cout << "The arrays are equal "; else cout << "The arrays are not equal "; ! Similarly, you cannot compare strings (i.e. char array) directly if (name == "Alan") … //WRONG! if ("Alan" == "Alan") … //WRONG! ! Then, how to check for whether the two arrays are equal? ! Use (for) loop to check each entry one by one ! The Program 21 #include

using namespace std;

void main(){

int array1[5]={10, 5, 3, 5, 1};

int array2[5];

int i;

bool arrayEqual=true;

cout << "Input 5 numbers\n"; for (i=0;i<5;i++) cin >> array2[i];

for (i=0; i<5 && arrayEqual; i++){ if (array1[i]!=array2[i]){ arrayEqual=false; } } if (arrayEqual) cout << "The arrays are equal"; else cout << "The arrays are not equal"; } Input 5 numbers 10 5 3 5 1 The arrays are equal Input 5 numbers 10 4 3 5 2 The arrays are not equal Example 4: Searching 22 ! Read 10 numbers from the user and store them in an array ! User input another number x. ! The program checks if x is an element of the array ! If yes, output the index of the first occurrence of the element ! If no (i.e. not found), output -1 Searching for x=15 (Case 1) 23 Same value at i=2 break out of the loop Suppose N=6 2 4 15 0 15 -7 i=1 a[i]!=x i=0 a[i]!=x i=2 a[i]==x Searching for x=8 (Case 2) 24 Output -1 2 4 15 0 15 -7 i=0 a[[i] !=x i=1 a[[i] !=x i=2 a[[i] !=x i=3 a[[i] !=x i=4 a[[i] !=x i=5 a[[i] !=x The program 25 #include

using namespace std;

const int N=10

void main()

{

int a[N], i, x, pos;

for (i=0; i> a[i];

cout << "Input your target: "; cin >>x;

for (i=0, pos=-1; i0; k–) {

if (a[k]j
k–

a[k]< a[k-1] swap a[k] and a[k-1] T F Bubbling #include

using namespace std;

const int n=10;

void main() {

int a[n], j, k, tmp;

cout <<"Input" << n <<" numbers: "; for (j=0; j> a[j];

// j = pass no. = length of sorted region

for (j=0; jj; k–) // bubbling

if (a[k]> table[i][j]; //[row][column]

! The above statement will read an integer into ith row and
jth column of the array. (not ith column and jth row!)

! Higher dimensions (3D, 4D…etc) are also possible:
(However, in this course, we’ll focus mainly up to 2D..)

int Cube[100][100][100];

Example: Print the 9×9 Multiplication Table
void main() {

int row,col,Table[10][10]; //Note: not [9][9]. Note: Index 0 not used !

//Generate Table
for (row=1;row<10;row++) { for (col=1;col<10;col++) { Table[row][col]=row*col; } } //Output for (row=1;row<10;row++) { for (col=1;col<10;col++) { cout< after each CELL

}
cout< at the end of each ROW

}
}

Summary

35

! Array is a sequence of variables of the same data type
! Array elements are indexed and can be accessed by the

use of subscripts (integer). e.g. array_name[4]

! The first item is [0], and the last one is [n-1] (not 1 to n!)
! Array elements are stored contiguously in memory space
! Sample use: Storing collection of numbers, statistics…etc.

! Array Declaration, Initialization, Searching and Sorting

! Array cannot be copied or compared directly. Must copy or
compare the elements one-by-one using loop.

! Array can be Multi-dimensional, i.e. 1D , 2D