Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.

Similar presentations


Presentation on theme: "Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays."— Presentation transcript:

1 Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

2 Starting Out with C++, 3 rd Edition 2 7.1 Arrays Hold Multiple values Unlike regular variables, arrays can hold multiple values.

3 Starting Out with C++, 3 rd Edition 3 Figure 7-1 int count Enough memory for 1 int 12345 float price Enough memory for 1 float 56.981 char letter Enough memory for 1 char A

4 Starting Out with C++, 3 rd Edition 4 Figure 7-2

5 Starting Out with C++, 3 rd Edition 5 Partial Array Initialization When an array is being initialized, C++ does not require a value for every element. int numbers[7] = {1, 2, 4, 8};

6 Starting Out with C++, 3 rd Edition 6 Table 7-1

7 Starting Out with C++, 3 rd Edition 7 Program 7-1 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element int array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees: "; cin >> hours[0]; cin >> hours[1]; cin >> hours[2]; cin >> hours[3];

8 Starting Out with C++, 3 rd Edition 8 Program continues cin >> hours[4]; cin >> hours[5]; cout << "The hours you entered are:"; cout << " " << hours[0]; cout << " " << hours[1]; cout << " " << hours[2]; cout << " " << hours[3]; cout << " " << hours[4]; cout << " " << hours[5] << endl; }

9 Starting Out with C++, 3 rd Edition 9 Figure 7-7

10 Starting Out with C++, 3 rd Edition 10 Program 7-2 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element short array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees: "; for (int count = 0; count < 6; count++) cin >> hours[count]; cout << "The hours you entered are:"; for (count = 0; count < 6; count++) cout << " " << hours[count]; cout << endl; }

11 Starting Out with C++, 3 rd Edition 11 Program 7-3 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element short array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees.\n"; for (int count = 1; count <= 6; count++) { cout << "Employee " << count << ": "; cin >> hours[count - 1]; } cout << "The hours you entered are\n";

12 Starting Out with C++, 3 rd Edition 12 Program continues for (count = 1; count <= 6; count++) { cout << "Employee " << count << ": "; cout << hours[count - 1] << endl; }

13 Starting Out with C++, 3 rd Edition 13 Figure 7-8

14 Starting Out with C++, 3 rd Edition 14 7.4 Array Initialization Arrays may be initialized when they are declared.

15 Starting Out with C++, 3 rd Edition 15 Program 7-5 // This program displays the number of days in each month. // It uses a 12-element int array. #include void main(void) { int days[12]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July

16 Starting Out with C++, 3 rd Edition 16 / This program displays the number of days in each month. // It uses a 12-element int array. #include main() {int days[12]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July days[7] = 31; // August days[8] = 30; // September days[9] = 31; // October days[10] = 30; // November days[11] = 31; // December for (int count = 0; count < 12; count++) { cout << "Month " << (count + 1) << " has "; cout << days[count] << " days.\n"; } system("pause"); }

17 Starting Out with C++, 3 rd Edition 17 Program 7-6 // This program displays the number of days in each month. // It uses a 12-element int array. #include main() { int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int count = 0; count < 12; count++) { cout << "MMonth " << (count + 1) << " has "; cout << days[count] << " days.\n"; } system("pause"); }

18 Starting Out with C++, 3 rd Edition 18 Program 7-7 // This program uses an array of ten characters to store the // first ten letters of the alphabet. The ASCII codes of the // characters are displayed. #include main() { char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; cout << "Character" << "\t" << "ASCII Code\n"; cout << "--------" << "\t" << "----------\n"; for (int count = 0; count < 10; count++) { cout << letters[count] << "\t\t"; cout << int(letters[count]) << endl; } system("pause"); }

19 Starting Out with C++, 3 rd Edition 19 Program 7-8 // This program has a partially initialized array. #include void main(void) { int numbers[7] = {1, 2, 4, 8}; // Initialize the // first 4 elements. cout << "Here are the contents of the array:\n"; for (int index = 0; index < 7; index++) cout << numbers[index] << endl; }

20 Starting Out with C++, 3 rd Edition Slide 7- 20 Default Values If too few values are listed in an initialization statement –The listed values are used to initialize the first of the indexed variables –The remaining indexed variables are initialized to a zero of the base type –Example: int a[10] = {5, 5}; initializes a[0] and a[1] to 5 and a[2] through a[9] to 0

21 Starting Out with C++, 3 rd Edition #include using namespace std; int main () { int a[20]; int i; for (i=0;i<20;++i) { a[i]=i+1; cout<<"a[i]="<<a[i]<<endl;} system("pause"); return 0; }

22 Starting Out with C++, 3 rd Edition #include using namespace std; int main (){ int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl<<x[I]<<"\t"<<y[I]; } system("pause"); return 0; }

23 Starting Out with C++, 3 rd Edition #include main () { int a[6]={40,60,50,70,80,90}; int I; for(I=0;I<6;I++) cout<<a[I]<<endl; //cout<<a[I]<<"\t"; system("pause"); return 0; }

24 Starting Out with C++, 3 rd Edition //initializing an array #include main() { int n[10]; int i; for(int i=0;i<10;i++) // initialize array n[i] = 0; cout << "Element”" << setw(13) << " value" << endl; // setw(13) 13 space for (i=0; i<10;i++) // print array // needs iomanip.h cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

25 Starting Out with C++, 3 rd Edition initialize elements of array n to 0 #include using namespace std; #include using std::setw; int main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } system("pause"); return 0; }

26 Starting Out with C++, 3 rd Edition initializing an array with a declaration #include main() { int Element,value,i; int n[10]={32,27,64,18,95,14,90,70,60,37}; cout << "Element”" << setw(13) << "“ value" << endl; for(i=0;i<10;i++) // print array cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

27 Starting Out with C++, 3 rd Edition compute the sum of the elements of the array // compute the sum of the elements of the array #include main() { const int arraysize =12; int a[arraysize] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int total=0; for(int i=0;i<arraysize ;i++) total+= a[i]; cout <<" total of array element valuesis " << total << endl; system("pause"); return 0; }

28 Starting Out with C++, 3 rd Edition // 2 array x,y=x*x #include main() { int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl <<x[I]<< " "<<y[I]; } system("pause"); return 0; }

29 Starting Out with C++, 3 rd Edition //multiply by *2 #include main() { //rscr(); int i; int a[5]={5,8,1,9,2}; for(i=0;i<=4;i++) {cout<<a[i]*2<<endl;} system("pause"); }

30 Starting Out with C++, 3 rd Edition #include main() { int i,n; int a[5]; cout<<"pls ent size arr: "<<setw(4); cin>>n; cout<<endl; for(i=1;i<=n;i++) {cout<<"enter number : "<<i<<" "<<setw(4); cin>>a[i]; cout<<i<<"*2="<<setw(4)<<a[i]*2<<endl;} system("pause"); }

31 Starting Out with C++, 3 rd Edition Pointer #include main() { int arr[3]; arr[0]=4; arr[1]=5; arr[2]=6; int *p; p=&arr[0]; cout<<"p= "<<*(p+1)<<endl; system("pause"); }

32 Starting Out with C++, 3 rd Edition 32 Implicit Array Sizing It is possible to declare an array without specifying its size, as long as you provide an initialization list. float ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

33 Starting Out with C++, 3 rd Edition Strings char string1[ ]="first"; Equal == char string1[ ]={'f','i','r','s','t','\o'}

34 Starting Out with C++, 3 rd Edition 34 Initializing With Strings When initializing a character array with a string, simply enclose the string in quotation marks: char name[] = “Warren”;

35 Starting Out with C++, 3 rd Edition 35 Figure 7-11

36 Starting Out with C++, 3 rd Edition Strcpy(string copy) #include main () { char x[]="Happy Hegrey year for All Muslem"; char y[25]; cout<<" The stringin array x is : "<< x << endl; cout<<" The stringin array y is: "<< strcpy(y,x) << endl; system("pause"); return 0; }

37 Starting Out with C++, 3 rd Edition #include main () { char s1[20]="computer"; char s2[ ]="science" ; cout<<"s1= " <<s1 << endl << "s2= " << s2 <<endl; cout<< "strcat(s1,s2) = " << strcat (s1, s2) << endl; system("pause"); return 0; }

38 Starting Out with C++, 3 rd Edition using strcmp( string copy ) // using strcmp #include int main () { char *s1 = "Saudia"; char *s2 = "Riyadh"; char *s3 = "Dirayah"; cout << "s1= " << s1<< endl<< "s2= " <<s2<<endl << "s3= " << s3<< endl<< endl<< "strcmp(s1, s2)= " << strcmp(s1, s2) <<endl<< "strcmp(s1, s3)= " << strcmp(s1, s3) <<endl<< "strcmp(s3, s1)= " << strcmp(s3, s1) <<endl<< endl; system("pause"); return 0; }

39 Starting Out with C++, 3 rd Edition 39 Program 7-9 // This program displays the contents of two char arrays. #include main() { char name1[] = "Holly"; char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'}; cout << name1 << endl; cout << name2 << endl; system("pause"); }

40 Starting Out with C++, 3 rd Edition 40 Program Output Holly Warren

41 Starting Out with C++, 3 rd Edition 41 7.5 Processing Array Contents Individual array elements are processed like any other type of variable.

42 Starting Out with C++, 3 rd Edition 42 Program 7-10 // This program stores, in an array, the hours worked by 5 // employees who all make the same hourly wage. #include main() { int hours[5]; float payRate; cout << "Enter the hours worked by 5 employees who all\n"; cout << "earn the same hourly rate.\n"; for (int index = 0; index < 5; index++) { cout << "Employee #" << (index + 1) << ": "; cin >> hours[index]; //system("pause"); } system("pause"); }

43 Starting Out with C++, 3 rd Edition 43 Program continues cout << "Enter the hourly pay rate for all the employees: "; cin >> payRate; cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < 5; index++) { float grossPay = hours[index] * payRate; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; }

44 Starting Out with C++, 3 rd Edition 44 Program Output with Example Input Enter the hours worked by 5 employees who all earn the same hourly rate. Employee #1: 5 [Enter] Employee #2: 10 [Enter] Employee #3: 15 [Enter] Employee #4: 20 [Enter] Employee #5: 40 [Enter] Enter the hourly pay rate for all the employees: 12.75 [Enter] Here is the gross pay for each employee: Employee #1: $63.75 Employee #2: $127.50 Employee #3: $191.25 Employee #4: $255.00 Employee #5: $510.00

45 Starting Out with C++, 3 rd Edition 45 Program 7-11 // This program stores, in an array, the hours worked by 5 // employees who all make the same hourly wage. It then // displays the gross pay, including any overtime. #include // Constant for defining the array size void main(void) { int hours[5]; float payRate; cout << "Enter the hours worked by 5 employees who all\n"; cout << "earn the same hourly rate.\n"; for (int index = 0; index < 5; index++) { cout << "Employee #" << (index + 1) << ": "; cin >> hours[index]; }

46 Starting Out with C++, 3 rd Edition 46 7.6 Focus on Software Engineering: Parallel Arrays By using he same subscript, you can build relationships between data stored in two or more arrays.

47 Starting Out with C++, 3 rd Edition 47 Program 7-12 // This program stores, in two arrays, the hours worked by 5 // employees, and their hourly pay rates. #include // Constant for defining the array size const int numEmps = 5; void main(void) { int hours[numEmps]; float payRate[numEmps]; cout << "Enter the hours worked by “ << numEmps << “ employees and their\n"; cout << "hourly rates.\n"; for (int index = 0; index < numEmps; index++) { cout << "hours worked by employee #" << (index + 1); cout << ": ";

48 Starting Out with C++, 3 rd Edition 48 Program continues cin >> hours[index]; cout << "Hourly pay rate for employee #"; cout << (index + 1) << ": "; cin >> payRate[index]; } cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < numEmps; index++) { float grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; }

49 Starting Out with C++, 3 rd Edition 49 7.7 Thou Shalt Not Assign You cannot use the assignment operator to copy one array’s contents to another. for (int count=0; count < 4; count++) newVal[count] = oldVal[count];

50 Starting Out with C++, 3 rd Edition 50 7.8 Printing the Contents of an Array To display the contents of an array, you must use a loop to display the contents of each element. int array[5] = { 10, 20, 30, 40, 50 }; for (int count = 0; count < 5; count++) cout << array[count] << endl;

51 Starting Out with C++, 3 rd Edition 51 7.9 Arrays As Function Arguments To pass an array as an argument to a function, pass the name of the array.

52 Starting Out with C++, 3 rd Edition 52 Program 7-13 // This program demonstrates that an array element is passed // to a function like any other variable. #include int ShowValue(int);// Function prototype main() { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; for (int Cycle = 0; Cycle < 8; Cycle++) ShowValue(collection[Cycle]); } int ShowValue(int Num) { cout << Num << " "; system("pause");}

53 Starting Out with C++, 3 rd Edition 53 Program 7-14 // This program demonstrates an array being passed to a function. #include void showValues(int []);// Function prototype void main(void) { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; showValues(collection); // Passing address of array collection } //*********************************************** // Definition of function showValues. * // This function accepts an array of 8 integers * // as its argument. The contents of the array * // is displayed. * //*********************************************** void showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; }

54 Starting Out with C++, 3 rd Edition 54 Program Output 5 10 15 20 25 30 35 40

55 Starting Out with C++, 3 rd Edition 55 Program 7-15 // This program demonstrates an array being passed to a function. #include void showValues(int []);// Function prototype void main(void) { int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16}; showValues(set1); cout << endl; showValues(set2); } //*********************************************** // Definition of function showValues. * // This function accepts an array of 8 integers * // as its argument. The contents of the array * // is displayed. * //*********************************************** void showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; }

56 Starting Out with C++, 3 rd Edition 56 Program Output 5 10 15 20 25 30 35 40 2 4 6 8 10 12 14 16

57 Starting Out with C++, 3 rd Edition Pointer #include main() { int arr[3]; arr[0]=4; arr[1]=5; arr[2]=6; int *p; p=&arr[0]; cout<<"p= "<<*(p+1)<<endl; system("pause"); }

58 Starting Out with C++, 3 rd Edition 58 7.10 Two-dimensional Arrays A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.

59 Starting Out with C++, 3 rd Edition Two-Dimensional Array Elements: #include using namespace std; int main () { // an array with 5 rows and 2 columns. int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; // output each array element's value for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 2; j++ ) { cout << "a[" << i << "][" << j << "]: "; cout << a[i][j]<< endl; } system("pause"); return 0; }

60 Starting Out with C++, 3 rd Edition 60 Passing Two-dimensional Arrays to Functions When a two-dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns.

61 Starting Out with C++, 3 rd Edition initialize elements of array n to 0 #include using namespace std; #include using std::setw; int main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } system("pause"); return 0; }

62 Starting Out with C++, 3 rd Edition Two-Dimensional Array Elements: #include using namespace std; int main () { // an array with 5 rows and 2 columns. int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; // output each array element's value for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 2; j++ ) { cout << "a[" << i << "][" << j << "]: "; cout << a[i][j]<< endl; } system("pause"); return 0; }

63 Starting Out with C++, 3 rd Edition String in array #include using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: "; cout << greeting << endl; system("pause"); return 0; }

64 Starting Out with C++, 3 rd Edition string copy #include #include // using namespace std; int main () { char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ; // copy str1 into str3 strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl; // concatenates str1 and str2 strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl; // total lenghth of str1 after concatenation len = strlen(str1); cout << "strlen(str1) : " << len << endl; system("pause"); return 0; }

65 Starting Out with C++, 3 rd Edition Address of variable #include using namespace std; int main () { int var1; char var2[10]; cout << "Address of var1 variable: "; cout << &var1 << endl; cout << "Address of var2 variable: "; cout << &var2 << endl; system("pause"); return 0; }

66 Starting Out with C++, 3 rd Edition Getting ASCII Code in C++ How do I get the ASCII code for a char type variable? And How do I convert ASCII code back to a character? #include using namespace std; int main(){ char ascii; int numeric; cout << "Give character: "; cin >> ascii; cout << "Its ascii value is: " << (int) ascii << endl; cout << "Give a number to convert to ascii: "; cin >> numeric; cout << "The ascii value of " << numeric << " is " << (char) numeric; return 0; }

67 Starting Out with C++, 3 rd Edition Declaring an array int marks[5]; called marks with 5 elements double numbers[10]; // Declare an double array of 10 elements const int SIZE = 9; float temps[SIZE]; // Use const int as array length // Some compilers support an variable as array length, e.g., int size; cout << "Enter the length of the array: "; cin >> size; float values[size];

68 Starting Out with C++, 3 rd Edition //Inter array and some calculation #include #include // setw(4) main() { int i,n; int a[5]; cout<<"pls ent size arr: "<<setw(4); cin>>n; cout<<endl; for(i=1;i<=n;i++) {cout<<"enter number : "<<i<<" "<<setw(4); cin>>a[i]; cout<<i<<"*2="<<setw(4)<<a[i]*2<<endl;} system("pause");}

69 Starting Out with C++, 3 rd Edition */ minumum number in array #include main() { int min,i,a[5]; min=a[1]; cout<<"pls enter item arr a[5]:"<<endl; for(i=1;i<=5;i++) {cin>>a[i];} for(i=1;i<=5;i++) if(min>a[i]) min=a[i]; cout<<"min item in arr a[5]: = "<<min<<endl; system("pause"); }

70 Starting Out with C++, 3 rd Edition //Min and max #include main() { int max,min,z,i,j,a[5]; min=a[1]; max=a[1]; cout<<"pls enter item arr a[5]:"<<endl; for(i=1;i<=5;i++) {cin>>a[i];} for(i=1;i<=5;i++) if(min>a[i]) min=a[i]; cout<<"min item in arr a[5]: = "<<min<<endl; for(i=1;i<=5;i++) if(max<a[i]) max=a[i]; cout<<"max item in arr a[5]: ="<<max<<endl; system("pause"); }

71 Starting Out with C++, 3 rd Edition */two dimenal array #include main() { int i,j,q,m=0; int a[8][8]; cout<<"pls enter item array : "<<endl; for(i=0;i<3;i++) { for(j=0;j<3;j++) cin>>a[i][j];} cout<<"---------------"<<endl; for(i=0;i<3;i++) { for(j=0;j<3;j++) {cout<<a[i][j]<<" ";} cout<<endl;} cout<<endl; for(i=0;i<3;i++) {for(j=1;j<3;j++) m=m+a[i][j]; } cout<<"sum array = "<<m; system("pause"); }

72 Starting Out with C++, 3 rd Edition #include main() { int i,n; int a[5],b[5],c[5]; cout<<"pls ent size arr 1: "<<setw(4); cin>>n;cout<<endl; for(i=1;i<=5;i++) {cout<<"enter items of a[i] number:"<<i<<" "<<setw(4); cin>>a[i];} cout<<"pls ent size arr 2: "<<setw(4); cin>>n;cout<<endl; for(i=1;i<=n;i++) {cout<<"enter items of b[i] number:"<<i<<" "<<setw(4); cin>>b[i];} cout<<endl; cout<<"a[i] = [ "; for(i=1;i<=n;i++) {cout<<a[i]<<" ";} cout<<" ]"; cout<<endl<<endl<<"b[i] = [ "; for(i=1;i<=n;i++) { cout<<b[i]<<" ";} cout<<" ]"<<endl<<endl; for(i=1;i<=n;i++) c[i]=a[i]+b[i]; cout<<endl<<"c[i] = a[i] + b[i] = [ "; for(i=1;i<=n;i++) { cout<<c[i]<<" ";} cout<<" ]"; system("pause"); }

73 Starting Out with C++, 3 rd Edition // Declare and initialize an int array of 3 elements int numbers[3] = {11, 33, 44}; // If length is omitted, the compiler counts the elements int numbers[] = {11, 33, 44}; // Number of elements in the initialization shall be equal to or less than length int numbers[5] = {11, 33, 44}; // Remaining elements are zero. Confusing! Don't do this int numbers[2] = {11, 33, 44}; // ERROR: too many initializers // Use {0} or {} to initialize all elements to 0 int numbers[5] = {0}; // First element to 0, the rest also to zero int numbers[5] = {}; // All element to 0 too

74 Starting Out with C++, 3 rd Edition #include main() { int i; int a[5]={5,8,1,9,2}; for(i=0;i<=4;i++) {cout<<a[i]*2<<endl;} system("pause"); }

75 Starting Out with C++, 3 rd Edition Array math used #include main() { int i; int a[5]={5,8,1,9,2};// changed to double for(i=0;i<=4;i++) {cout<<a[i]/2<<endl;} system("pause"); }

76 Starting Out with C++, 3 rd Edition //Sum & Average of Array #include using namespace std; int main() { int marks[] = {74, 43, 58, 60, 90, 64, 70}; int sum=0; int ava=0; for (int j = 0; j < 7; ++j) { sum += marks[j]; ava=sum/5;} cout << "sum is "<< sum << "avaregeis" <<endl<< ava<<endl; system("pause"); return 0;}

77 Starting Out with C++, 3 rd Edition /* Test local array initialization (TestArrayInit.cpp) */ #include using namespace std; int main() { int const SIZE = 5; int a1[SIZE]; // Uninitialized for (int i = 0; i < SIZE; ++i) cout << a1[i] << " "; cout << endl; // ? ? ? ? ? int a2[SIZE] = {21, 22, 23, 24, 25}; // All elements initialized for (int i = 0; i < SIZE; ++i) cout << a2[i] << " "; cout << endl; // 21 22 23 24 25 int a3[] = {31, 32, 33, 34, 35}; // Size deduced from init values int a3Size = sizeof(a3)/sizeof(int); cout << "Size is " << a3Size << endl; // 5 for (int i = 0; i < a3Size; ++i) cout << a3[i] << " "; cout << endl; // 31 32 33 34 35 int a4[SIZE] = {41, 42}; // Leading elements initialized, the rests to 0 for (int i = 0; i < SIZE; ++i) cout << a4[i] << " "; cout << endl; // 41 42 0 0 0 int a5[SIZE] = {0}; // First elements to 0, the rests to 0 too for (int i = 0; i < SIZE; ++i) cout << a5[i] << " "; cout << endl; // 0 0 0 0 0 int a6[SIZE] = {}; // All elements to 0 too for (int i = 0; i < SIZE; ++i) cout << a6[i] << " "; cout << endl; // 0 0 0 0 0 }

78 Starting Out with C++, 3 rd Edition // Declare & allocate a 5-element int array int marks[5]; // Assign values to the elements marks[0] = 95; marks[1] = 85; marks[2] = 77; marks[3] = 69; marks[4] = 66; cout << marks[0] << endl; cout << marks[3] + marks[4] << endl;

79 Starting Out with C++, 3 rd Edition //Find the mean and standard deviation of numbers kept in an array (MeanStdArray.cpp). #include #define SIZE 7 using namespace std; int main() { int marks[] = {74, 43, 58, 60, 90, 64, 70}; int sum = 0; int sumSq = 0; double mean, stdDev; for (int i = 0; i < SIZE; ++i) { sum += marks[i]; sumSq += marks[i]*marks[i]; } mean = (double)sum/SIZE; cout << fixed << "Mean is " << setprecision(2) << mean << endl; stdDev = sqrt((double)sumSq/SIZE - mean*mean); cout << fixed << "Std dev is " << setprecision(2) << stdDev << endl; return 0;

80 Starting Out with C++, 3 rd Edition // mean & Standard Div & Sum #include #define SIZE 7 using namespace std; int main() { int marks[] = {74, 43, 58, 60, 90, 64, 70}; int sum = 0; int sumSq = 0; double mean, stdDev; for (int i = 0; i < SIZE; ++i) { sum += marks[i]; sumSq += marks[i]*marks[i]; } mean = (double)sum/SIZE; cout << fixed << "Mean is " << setprecision(2) << mean << endl; stdDev = sqrt((double)sumSq/SIZE - mean*mean); cout << fixed << "Std dev is " << setprecision(2) << stdDev << sum<<endl; cout<< sum<<endl; system("pause"); return 0;}

81 Starting Out with C++, 3 rd Edition Multi-Dimensional Array

82 Starting Out with C++, 3 rd Edition /* Test Multi-dimensional Array (Test2DArray.cpp) */ #include using namespace std; void printArray(const int[][3], int); int main() { int myArray[][3] = {{8, 2, 4}, {7, 5, 2}}; // 2x3 initialized // Only the first index can be omitted and implied printArray(myArray, 2); return 0; } // Print the contents of rows-by-3 array (columns is fixed) void printArray(const int array[][3], int rows) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < 3; ++j) { cout << array[i][j] << " "; } cout << endl; } system("pause"); }

83 Starting Out with C++, 3 rd Edition Array of Characters - C-String In C, a string is a char array terminated by a NULL character '\0' (ASCII code of Hex 0). C++ provides a new string class under header. The original string in C is known as C-String (or C- style String or Character String). You could allocate a C-string via: char message[256]; // Declare a char array // Can hold a C-String of up to 255 characters terminated by '\0' char str1[] = "Hello"; // Declare and initialize with a "string literal". // The length of array is number of characters + 1 (for '\0'). char str1char[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Same as above char str2[256] = "Hello"; // Length of array is 256, keeping a smaller string.

84 Starting Out with C++, 3 rd Edition Example You can use cin and cout to handle C-strings. cin << reads a string delimited by whitespace; cin.getline(var, size) reads a string of into var till newline of length up to size-1, discarding the newline (replaced by '\0'). The size typically corresponds to the length of the C-string array. cin.get(var, size) reads a string till newline, but leaves the newline in the input buffer. cin.get(), without argument, reads the next character.

85 Starting Out with C++, 3 rd Edition /* Test C-string (TestCString.cpp) */ #include using namespace std; int main() { char msg[256]; // Hold a string of up to 255 characters (terminated by '\0') cout << "Enter a message (with space)" << endl; cin.getline(msg, 256); // Read up to 255 characters into msg cout << msg << endl; // Access via null-terminated character array for (int i = 0; msg[i] != '\0'; ++i) { cout << msg[i]; } cout << endl; cout << "Enter a word (without space)" << endl; cin >> msg; cout << msg << endl; // Access via null-terminated character array for (int i = 0; msg[i] != '\0'; ++i) { cout << msg[i]; } cout << endl; system("pause"); return 0;}

86 Starting Out with C++, 3 rd Edition 86 7.11 Arrays of Strings A two-dimensional array of characters can be used as an array of C-strings.

87 Starting Out with C++, 3 rd Edition 87 Program 7-20 // This program displays the number of days in each month. // It uses a two-dimensional character array to hold the // names of the months and an int array to hold the number // of days. #include void main(void) { char months[12][10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September”, "October", "November","December"}; int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int count = 0; count < 12; count++) { cout << months[count] << " has "; cout << days[count] << " days.\n"; } }

88 Starting Out with C++, 3 rd Edition 88 Program 7-20 (continued) Program Output January has 31 days. February has 28 days. March has 31 days. April has 30 days. May has 31 days. June has 30 days. July has 31 days. August has 31 days. September has 30 days. October has 31 days. November has 30 days. December has 31 days.

89 Starting Out with C++, 3 rd Edition 89 Three Dimensional Arrays and Beyond C++ allows you to create arrays with virtually any number of dimensions. Here is an example of a three-dimensional array declaration: float seat[3][5][8];


Download ppt "Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays."

Similar presentations


Ads by Google