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

Slides:



Advertisements
Similar presentations
Strings.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Chapter 10.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 9: Arrays and Strings
Arrays Chapter 8 page /24/07CS150 Introduction to Computer Science 1 Arrays (8.1)  One variable that can store a group of values of the same.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 5 Arrays and Strings C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
CS102 Introduction to Computer Programming Chapter 7 Arrays.
1 Arrays Chapter 13 Especially read 13.1 – 13.2 Text introduces vectors, which we will not cover, in 13.3.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Chapter 8 Arrays and Strings
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
GE 211 Programming in C++ Array &Matrix Dr. Ahmed Telba.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
Starting Out with C++, 3 rd Edition Array problem solving in C++ Dr Ahmed Telba.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 7 – Arrays.
Arrays Arrays exist in almost every computer language.
Arrays Kingdom of Saudi Arabia
Arrays Arrays A few types Structures of related data items
C++ Programming Lecture 20 Strings
CS-161 Computer Programming Lecture 15 & 16: Arrays II
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Dr. Khizar Hayat Associate Prof. of Computer Science
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Starting Out with C++, 3 rd Edition Slide 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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: [Enter] Here is the gross pay for each employee: Employee #1: $63.75 Employee #2: $ Employee #3: $ Employee #4: $ Employee #5: $510.00

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

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

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 << ": ";

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

Starting Out with C++, 3 rd Edition 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];

Starting Out with C++, 3 rd Edition 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;

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

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

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

Starting Out with C++, 3 rd Edition 54 Program Output

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

Starting Out with C++, 3 rd Edition 56 Program Output

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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; // 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; // int a4[SIZE] = {41, 42}; // Leading elements initialized, the rests to 0 for (int i = 0; i < SIZE; ++i) cout << a4[i] << " "; cout << endl; // 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; // int a6[SIZE] = {}; // All elements to 0 too for (int i = 0; i < SIZE; ++i) cout << a6[i] << " "; cout << endl; // }

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;

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;

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

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

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

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.

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.

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

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

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

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.

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