Starting Out with C++, 3 rd Edition Array problem solving in C++ Dr Ahmed Telba.

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
Advertisements

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.
 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
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Introduction to Programming with C++ Fourth Edition
C++ for Engineers and Scientists Third Edition
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.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
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.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
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.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
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.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
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.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
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.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays –C++, arrays.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 19: Container classes; strings.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
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.
Computer Programming BCT 1113
Module 2 Arrays and strings – example programs.
Standard Version of Starting Out with C++, 4th Edition
Arrays Arrays A few types Structures of related data items
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
Presentation transcript:

Starting Out with C++, 3 rd Edition Array problem solving in C++ Dr Ahmed Telba

Starting Out with C++, 3 rd Edition 2 Arrays 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 Table 7-1

Starting Out with C++, 3 rd Edition Accessing Array elements The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements.

Starting Out with C++, 3 rd Edition 7 // 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 using namespace std; int main() { short hours[6]; cout << "Enter the hours worked by six employees: "; cin >> hours[0]; cin >> hours[1]; cin >> hours[2]; cin >> hours[3]; 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 8

9 Program // 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 using namespace std; int main() { 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 10 Program // 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 using namespace std; int main() { int 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"; for (int count = 1; count <= 6; count++) { cout << "Employee " << count << ": "; cout << hours[count - 1] << endl; } }

Starting Out with C++, 3 rd Edition 11 // This program displays the number of days in each month. // It uses a 12-element int array. #include using namespace std; int 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"; }

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

Starting Out with C++, 3 rd Edition #include #include // for set wedith using namespace std; int main( ) { int n[10]; for (int i=0; i<10;i++) // initialize array n[i] = 0; cout << "“Element”" << setw(13) << " value" << endl; for (int i=0; i<10;i++) // print array cout << setw(7) <<i<<setw(13) <<n[i]<<endl; return 0; }

Starting Out with C++, 3 rd Edition Declaring & Printing Array #include #include // for set width using namespace std; int main( ) { int n[10] = {32,27,64,18,95,14,90,70,60,37}; cout << "“Element" << setw(13) << " value"<< endl; for ( int i=0 ; i< 10; i++)// for print cout << setw(7) <<i<<setw(13) <<n[i]<<endl; return 0; }

Starting Out with C++, 3 rd Edition Sum of element in array #include #include // for set wedith using namespace std; int 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 values is " << total << endl; return 0; } Chapter 8 slide 15

Starting Out with C++, 3 rd Edition 16 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 using namespace std; int 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; }

Starting Out with C++, 3 rd Edition 17 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 18 Program 7-8 // This program has a partially initialized array. #include using namespace std; int main() { 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 19 Implicit (hidden) 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 20 Initializing With Strings When initializing a character array with a string, simply enclose the string in quotation marks: char name[] = “Warren”; // null terminator ‘/0’

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

Starting Out with C++, 3 rd Edition 22 Program 7-9 // This program displays the contents of two char arrays. #include using namespace std; int main() { char name1[] = "Holly"; char name2[] = {'A', 'H', 'M', 'E', 'D', 'T', '\0'}; cout << name1 << endl; cout << name2 << endl; }

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 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 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 27 Program 7-13 // This program demonstrates that an array element is passed // to a function like any other variable. #include using namespace std; int ShowValue(int);// Function prototype int 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 << " "; }

Starting Out with C++, 3 rd Edition 28 Program 7-14 // This program demonstrates an array being passed to a function. #include using namespace std; int showValues(int []);// Function prototype main() { 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. * //*********************************************** int showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; }

Starting Out with C++, 3 rd Edition Function in Array #include using namespace std; void print(int A[], int length) { for (int n=0; n<length; n++) cout << A[n] << " "; cout << "\n"; } int main () { int arr[] = {5, 10, 15}; print(arr,3); // can be changed for element to be print return 0; } 29

Starting Out with C++, 3 rd Edition 30 Basic Operation On One Dimensional Array Function to traverse the array A void display(int A[], int n) { cout<<"The elements of the array are:\n"; for(int i=0;i<n;i++) cout<<A[i]; }

Starting Out with C++, 3 rd Edition #include using namespace std; int main() { int matrix [2][3]; // For taking integer inputs in a matrix // for (int m1=0 ; m1<2 ; m1++) { for (int m2=0 ; m2<3 ; m2++) { cout<<"Enter Integer :"; cin>>matrix [m1][m2]; } cout<<endl; // For displaying elements of a matrix on a screen // for (int m1=0 ; m1<2 ; m1++) { for (int m2=0 ; m2<3 ; m2++) { cout<<"Your Entered Integer are :"; cout<<matrix [m1][m2]; cout<<endl; } } } 31

Starting Out with C++, 3 rd Edition Function to Read elements of the array A void Input(int A[], int n) { cout<<"Enter the elements:"; for(int i=0;i<n;i++) cin>>A[i]; } Function to Search for an element from A by Linear Search void lsearch(int A[], int n, int data) { int i; for(i=0; i<n; i++) { if(A[i]==data) { cout<<"Data Found at : "<<i; return; } } cout<<"Data Not Found in the array"<<endl; } 32

Starting Out with C++, 3 rd Edition Function to Sort the array A by Bubble Sort void BSort(int A[], int n) { int I,J,Temp; for(I=0;I<n-1;I++) //sorting { for(J=0;J<(n-1-I);J++) if(A[J]>A[J+1]) { Temp=A[J]; //swapping A[J]=A[J+1]; A[J+1]=Temp; } 33

Starting Out with C++, 3 rd Edition Array addition #include // Array addition using namespace std; int main() { int a[4]={2,4,6,8},i,b[4]={1,3,5,6},c[4]; for(i=0;i<=3;i++) {c[i]=a[i]+b[i]; cout<<c[i]<<" ";} } 34

Starting Out with C++, 3 rd Edition #include // sum & Average of array using namespace std; int main() { int a[5]={50,60,70,80,90}; int i,sum=0; for(i=0;i<=4;i++) sum=sum+a[i]; float av=sum/5; cout<< "The sum is: "<<sum<<endl; cout<<"The Average is: "<<av; } 35

Starting Out with C++, 3 rd Edition #include // sort array min to max using namespace std; int main() { int a[7],i,j,t; for(i=0;i<7;i++) {cout<<"Enter a["<<i<<"]= "; cin>>a[i];} for(i=0;i<7;i++) {for( j=0; j<7; j++) if(a[i] a[j])*/ {t=a[i]; a[i]=a[j]; a[j]=t;}} for(i=0;i<7;i++) cout<<a[i]<<" "; } 36

Starting Out with C++, 3 rd Edition #include // odd number in array using namespace std; int main() { int a[10],c[10]; int n1=0,i; for(i=0;i<10;i++){ cout<<"a["<<i<<"]="; cin>>a[i];} for(i=0;i<10;i++) if(a[i]%2!=0){ n1++; c[n1]=a[i];} for(i=1;i<=n1;i++) cout<<c[i]<<"\t"; } 37

Starting Out with C++, 3 rd Edition #include // odd and even using namespace std; int main() { int a[10],i,j,z; for(i=1; i<=10;i++) {cout<<"Enter a["<<i<<"]="; cin>>a[i]; } for(i=0; i<=9;i++) for(j=i+1; j<=9;j++) if(a[i]%2!=0) {z=a[i]; a[i]=a[j]; a[j]=z; } for(i=1; i<=10;i++) cout<<a[i]<<" "; } 38

Starting Out with C++, 3 rd Edition 39 Program 7-15 #include // odd and even using namespace std; int main() { int a[2][2],i,j; for(i=0;i<=1;i++) for(j=0;j<=1;j++) {cout<<"Enter a[<<i<<"]["<<j<<"]= "; cin>>a[i][j];} for(i=0;i<=1;i++) {cout<<endl; for(j=0;j<=1;j++) cout<<a[i][j]; } }

Starting Out with C++, 3 rd Edition لحصول على القطر if(i==j) #include // odd and even using namespace std; int main() { int a[3][3]={{5,6,2},{8,7,4},{1,3,9}}; int i,j; for(i=0;i<3;i++) for(j=0;j<3;j++) if(i==j) cout<<a[i][j]<<" "; } 40

Starting Out with C++, 3 rd Edition #include // sum of diameter using namespace std; int main() { int a[3][3]={{5,6,2},{8,7,4},{1,3,9}}; int i,j,sum=0; for(i=0;i<3;i++) for(j=0;j<3;j++) {if(i==j) sum+=a[i][j];} cout<<sum; } 41

Starting Out with C++, 3 rd Edition #include // diameter inverste using namespace std; int main() { int a[3][3]={{5,6,2},{8,7,4},{1,3,9}};// int i,j,n=3; // // for(i=0;i<3;i++) for(j=0;j<3;j++) if(i+j==n-1)//or if(i+j==2) cout<<a[i][j]<<" "; } 42

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 A dynamic 2D array is basically an array of pointers to arrays. You should initialize it using a loop: int** ary = new int*[sizeY]; for(int i = 0; i < sizeY; ++i) ary[i] = new int[sizeX]; The above, for sizeX = 5 and sizeY = 4, would produce the following:Two-dimensional Arrays 44

Starting Out with C++, 3 rd Edition Multidimensional Array Initialisation You can initialise a multidimensional array in more than one way. Consider this examples to initialise two dimensional array. int test[2][3] = {2, 4, -5, 9, 0, 9}; Better way to initialise this array with same array elements as above. int test[2][3] = { {2, 4, 5}, {9, 0 0}}; 45

Starting Out with C++, 3 rd Edition Initialization of three dimensional array int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23, 2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9}; Better way to initialize this array with same elements as above. int test[2][3][4] = { { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } }; 46

Starting Out with C++, 3 rd Edition Better way to initialize this array with same elements as above. int test[2][3][4] = { { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } }; 47

Starting Out with C++, 3 rd Edition Example #include using namespace std; int main() { int test[3][2] = { {2, -5}, {4, 0}, {9, 1} }; for(int i = 0; i < 3; ++i) { for(int j = 0; j < 2; ++j) { cout<< "test["<< i << "][" << j << "] = " << test[i][j]<<endl; } return 0; } 48

Starting Out with C++, 3 rd Edition #include // three dimension array using namespace std; int main() { int test[2][3][2]; // this array can store 12 elements cout<<"Enter 12 values: \n"; for(int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for(int k = 0; k < 2; ++k ) { cin>>test[i][j][k]; } cout<<"\nDisplaying Value stored:"<<endl; /* Displaying the values with proper index. */ for(int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for(int k = 0; k < 2; ++k ) { cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j][k]<<endl; } return 0; } 49

Starting Out with C++, 3 rd Edition C++ Program to Add Two Matrix Using Multi-dimensional Arrays #include using namespace std; int main(){ int r,c,a[100][100],b[100][100],sum[100][100],i,j; cout << "Enter number of rows (between 1 and 100): "; cin >> r; cout << "Enter number of columns (between 1 and 100): "; cin >> c; cout << endl << "Enter elements of 1st matrix: " << endl; /* Storing elements of first matrix entered by user. */ for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << "Enter element a" << i+1 << j+1 << " : "; cin >> a[i][j]; } /* Storing elements of second matrix entered by user. */ cout << endl << "Enter elements of 2nd matrix: " << endl; for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << "Enter element b" << i+1 << j+1 << " : "; cin >> b[i][j]; } /*Adding Two matrices */ for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j]; /* Displaying the resultant sum matrix. */ cout << endl << "Sum of two matrix is: " << endl; for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << sum[i][j] << " "; if(j==c-1) cout << endl; } return 0; } 50

Starting Out with C++, 3 rd Edition //C++ Program to Find Largest Element of an Array #include using namespace std; int main(){ int i,n; float arr[100]; cout << "Enter total number of elements: "; cin >> n; cout << endl; while (n>100 || n<=0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } for(i=0;i<n;++i) /* Stores number entered by user. */ { cout << "Enter Number " << i+1 << " : "; cin >> arr[i]; } for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */ { if(arr[0] if you want to find smallest element*/ arr[0]=arr[i]; } cout << "Largest element = " << arr[0]; return 0; } 51

Starting Out with C++, 3 rd Edition #include //Source Code to Find Transpose of a Matrix Colom change to row and row change Colom using namespace std; int main() { int a[10][10], trans[10][10], r, c, i, j; cout << "Enter rows and columns of matrix: "; cin >> r >> c; /* Storing element of matrix entered by user in array a[][]. */ cout << endl << "Enter elements of matrix: " << endl; for(i=0; i<r; ++i) for(j=0; j<c; ++j) { cout << "Enter elements a" << i+1 << j+1 << ": "; cin >> a[i][j]; } /* Displaying the matrix a[][] */ cout << endl << "Entered Matrix: " << endl; for(i=0; i<r; ++i) for(j=0; j<c; ++j) { cout << " " << a[i][j]; if(j==c-1) cout << endl << endl; } /* Finding transpose of matrix a[][] and storing it in array trans[][]. */ for(i=0; i<r; ++i) for(j=0; j<c; ++j) { trans[j][i]=a[i][j]; } /* Displaying the transpose,i.e, Displaying array trans[][]. */ cout << endl << "Transpose of Matrix: " << endl; for(i=0; i<c; ++i) for(j=0; j<r; ++j) { cout << " " << trans[i][j]; if(j==r-1) cout << endl << endl; } return 0; } 52

Starting Out with C++, 3 rd Edition #include // matrix addation using namespace std; int main() { int a[10][10]; int b[10][10]; int x,y,i,j; cout<<"\nEnter the number of rows and columns :::\n\n"; cin>>x>>y; cout<<"\n\nEnter elements for Matrix A :::\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cin>>a[i][j]; } cout<<"\n"; } cout<<"\n\nEnter elements for Matrix B :::\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cin>>b[i][j]; } cout<<"\n"; } cout<<"\n\nMatrix A :\n\n"; for(i=0;i<x;i++) { } 53

Starting Out with C++, 3 rd Edition //Counted matrix add for(j=0;j<y;j++) { cout<<"\t"<<a[i][j]; } cout<<"\n\n"; } cout<<"\n\nMatrix B :\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cout<<"\t"<<b[i][j]; } cout<<"\n\n"; } cout<<"\n\nAddition of Matrix A and Matrix B :\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cout<<"\t"<<a[i][j]+b[i][j]; } cout<<"\n\n"; } 54

Starting Out with C++, 3 rd Edition #include using namespace std; int main() { int i1=9,i2=10,i3=11,i4=12,i5=13; double ava=i1+i2+i3+i4+i5; ava=ava/5; cout << "avarage= "<< ava<<endl; return 0; }

Starting Out with C++, 3 rd Edition #include // cin num& print it using namespace std; int main() { int a[10],i; for(i=0;i<=9;i++) cin>>a[i]; for(i=0;i<=9;i++) cout<<a[i]<<" "; }

Starting Out with C++, 3 rd Edition #include // change firstA[0] to third{2] using namespace std; int main() { int A[4],M=0,i; for(i=0;i<=3;i++) cin>>A[i]; { M=A[0]; A[0]=A[2]; A[2]=M;} for(i=0;i<=3;i++) cout<<A[i]<<" ";}

Starting Out with C++, 3 rd Edition #include // find minimum & maximum of array using namespace std; int main() { int a[10]; for(int i=0;i<=9;i++) cin>>a[i]; int max=a[0]; int min=a[0]; for(int i=0;i<=9;i++) { if(max<a[i]) max=a[i]; if(min>a[i]) min=a[i];} cout<<"Max="<<max<<"\n"; cout<<"Min="<<min<<"\n";}

Starting Out with C++, 3 rd Edition #include // sum of array element & avarage #include using namespace std; int main() { int A[2][2]; int sum=0,i,j,ava; cout<<"Please enter the elements ofarray\n"; for(i=0;i<=1;i++) for(j=0;j<=1;j++) cin>>A[i][j]; for(i=0;i<=1;i++) for(j=0;j<=1;j++) sum+=A[i][j]; ava=sum/4; cout<< "avarage=\n"<<ava<< endl; cout<<"sum = "<<sum;}

Starting Out with C++, 3 rd Edition #include // change Coolum by row using namespace std; int main() { int array[3][3],z,i,j; for(i=0;i<=2;i++) for(j=0;j<=2;j++) cin>>array[i][j]; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) z=array[0][i]; array[0][i]=array[i][1]; array[i][1]=z;} cout<<" \n"; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) cout<<array[i][j]<<" "; cout<<endl;}}

Starting Out with C++, 3 rd Edition #include // matrix 3 by 3 change in row using namespace std; int main() { int p[3][3],m,i,j; for(i=0;i<=2;i++) for(j=0;j<=2;j++) cin>>p[i][j]; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) m=p[i][0]; p[i][0]=p[i][1]; p[i][1]=m;} cout<<" \n"; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) cout<<p[i][j]<<" "; cout<<endl;}}

Starting Out with C++, 3 rd Edition #include // adding two array using namespace std; int main() { int a[4]={2,4,6,8},i,b[4]={1,3,5,6},c[4]; for(i=0;i<=3;i++) {c[i]=a[i]+b[i]; //cout<<a[i]<<"\t"; //cout<<b[i]<<" "; cout<<c[i]<<" "; }

Starting Out with C++, 3 rd Edition #include // look for number in array and yes or NO using namespace std; int main() { int a[7]={1,3,5,4,6,7,8}; int i,m=0,n; cout<<"Enter the number :"; cin>>n; for(i=0;i<=6;i++) {if(n==a[i]) {m=1; break;} else m=0;} if(m==1) cout<< "The number is found. "; else cout<< "The number is not found. "; }

Starting Out with C++, 3 rd Edition #include // enter array then sort from min to max using namespace std; int main() { int a[7],i,j,t; for(i=0;i<7;i++) {cout<<"Enter a["<<i<<"]= "; cin>>a[i];} for(i=0;i<7;i++) {for( j=0; j<7; j++) if(a[i]<a[j]) {t=a[i]; a[i]=a[j]; a[j]=t;}} for(i=0;i<7;i++) cout<<a[i]<<" "; }

Starting Out with C++, 3 rd Edition #include // enter array then delete one number using namespace std; int main() { int a[6],x,i,j,d=5,k; for(i=0; i<=5;i++) {cout<<"enter a["<<i<<"]="; cin>>a[i]; } cout<<"enter number for delete it: "; cin>>x; k=0; for(i=0; i<=5;i++) if(x==a[i]) {k=k+1; for(j=i; j<=5;j++) a[j]=a[j+1]; d=d-1;} if(k==0) cout<<"not found"<<endl; for(i=0;i<=d;i++) cout<<a[i]<<" "; }

Starting Out with C++, 3 rd Edition #include //Reverse the array element using namespace std; int main() { int a[10],i; for(i=0;i<=9;i++) cin>>a[i]; for(i=9;i>=0;i--) cout<<a[i]<<" "; }

Starting Out with C++, 3 rd Edition 67

Starting Out with C++, 3 rd Edition #include // sort odd & even in array using namespace std; int main() { int a[10],i,j,z; for(i=1; i<=10;i++) {cout<<"Enter a["<<i<<"]="; cin>>a[i]; } for(i=0; i<=9;i++) for(j=i+1; j<=9;j++) if(a[i]%2!=0) {z=a[i]; a[i]=a[j]; a[j]=z; } for(i=1; i<=10;i++) cout<<a[i]<<" "; }

Starting Out with C++, 3 rd Edition #include //enter two Dim matrix & print it using namespace std; int main() { int a[2][2],i,j; for(i=0;i<=1;i++) for(j=0;j<=1;j++) { cout<<"Enter a["<<i<<"]["<<j<<"]= "; cin>>a[i][j];} for(i=0;i<=1;i++) {cout<<endl; for(j=0;j<=1;j++) cout<<a[i][j] <<"\t";} }

Starting Out with C++, 3 rd Edition #include // minimum number in matrix #include using namespace std; int main() { int A[2][2]={5,6,2,8}; int i,j,min=A[0][0]; for(i=0;i<=1;i++) for(j=0;j<=1;j++) {cout<<"Enter A["<<i<<"]["<<j<<"]= "; //cin>>A[i][j]; } for(i=0;i<=1;i++) {for(j=0;j<=1;j++) if(A[i][j]<min) min=A[i][j];} cout<<"\n min = " <<min;} }

Starting Out with C++, 3 rd Edition #include //diameter of matrix using namespace std; int main() { int a[3][3]={{5,6,2},{8,7,4},{1,3,9}}; int i,j; for(i=0;i<3;i++) for(j=0;j<3;j++) if(i==j) cout<<a[i][j]<<" "; }

Starting Out with C++, 3 rd Edition 72 Program 7-18 // This program demonstrates a two-dimensional array. #include void main(void) { float sales[3][4]; // 2D array, 3 rows and 4 columns. float totalSales = 0;// To hold the total sales. int dir, qtr;// Loop counters.

Starting Out with C++, 3 rd Edition 73 Program continues cout << "This program will calculate the total sales of\n"; cout << "all the company's divisions.\n"; cout << "Enter the following sales information:\n\n"; // Nested loops to fill the array with quarterly // sales figures for each division. for (div = 0; div < 3; div++) { for (qtr = 0; qtr < 4; qtr++) { cout << "Division " << (div + 1); cout << ", Quarter " << (qtr + 1) << ": $"; cin >> sales[div][qtr]; } cout << endl; // Print blank line. }

Starting Out with C++, 3 rd Edition 74 Program continues // Nested loops to add all the elements. for (div = 0; div < 3; div++) for (qtr = 0; qtr < 4; qtr++) totalSales += sales[div][qtr]; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The total sales for the company are: $"; cout << totalSales << endl; }

Starting Out with C++, 3 rd Edition 75 Program Output with Example Input This program will calculate the total sales of all the company's divisions. Enter the following sales information: Division 1, Quarter 1: $ [Enter] Division 1, Quarter 2: $ [Enter] Division 1, Quarter 3: $ [Enter] Division 1, Quarter 4: $ [Enter] Division 2, Quarter 1: $ [Enter] Division 2, Quarter 2: $ [Enter] Division 2, Quarter 3: $ [Enter] Division 2, Quarter 4: $ [Enter]

Starting Out with C++, 3 rd Edition C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional integer array: int threedim[5][10][4]; Two-Dimensional Arrays: The simplest form of the multidimensional array is the two-dimensional array. A two- dimensional array is, in essence, a list of one-dimensional arrays. To declare a two- dimensional integer array of size x,y, you would write something as follows: type arrayName [ x ][ y ];Where type can be any valid C++ data type and arrayName will be a valid C++ identifier. A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below: 76

Starting Out with C++, 3 rd Edition 77 Initializing Two-Dimensional Arrays: Multi dimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns. int a[3][4] = { {0, 1, 2, 3}, /* initializers for row indexed by 0 */ {4, 5, 6, 7}, /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; Two Dimensional Array It is a collection of data elements of same data type arranged in rows and columns (that is, in two dimensions). Declaration of Two-Dimensional Array Type arrayName[numberOfRows][numberOfColumn]; For example, int Sales[3][5];

Starting Out with C++, 3 rd Edition Initialization of Two-Dimensional Array An two-dimensional array can be initialized along with declaration. For two-dimensional array initialization, elements of each row are enclosed within curly braces and separated by commas. All rows are enclosed within curly braces. int A[4][3] = {{22, 23, 10}, {15, 25, 13}, {20, 74, 67}, {11, 18, 14}}; 78

Starting Out with C++, 3 rd Edition Example 2 D array #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; } return 0; } 79

Starting Out with C++, 3 rd Edition #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; } return 0; } 80

Starting Out with C++, 3 rd Edition 81 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 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 String function S.N.Function & Purpose 1strcpy(s1, s2); Copies string s2 into string s1. 2strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3strlen(s1); Returns the length of string s1. 4strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1 s2. 5strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. 6strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. 83

Starting Out with C++, 3 rd Edition #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; return 0; } 84

Starting Out with C++, 3 rd Edition Stract #include using namespace std; int main () { string str1 = "Hello"; string str2 = "World"; string str3; int len ; // copy str1 into str3 str3 = str1; cout << "str3 : " << str3 << endl; // concatenates str1 and str2 str3 = str1 + str2; cout << "str1 + str2 : " << str3 << endl; // total lenghth of str3 after concatenation len = str3.size(); cout << "str3.size() : " << len << endl; return 0; } 85

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

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 that you may use in your programs. These data types and algorithms are programmer- defined. They are not part of the C++ language, but were created in addition to the built-in data types.

Starting Out with C++, 3 rd Edition Introduction to the STL vector The data types that are defined in the STL are commonly called containers, because they store and organize data. There are two types of containers in the STL: sequence containers and associative containers. The vector data type is a sequence container.

Starting Out with C++, 3 rd Edition Introduction to the STL vector A vector is like an array in the following ways: –A vector holds a sequence of values, or elements. –A vector stores its elements in contiguous memory locations. –You can use the array subscript operator [] to read the individual elements in the vector

Starting Out with C++, 3 rd Edition Introduction to the STL vector However, a vector offers several advantages over arrays. Here are just a few: –You do not have to declare the number of elements that the vector will have. –If you add a value to a vector that is already full, the vector will automatically increase its size to accommodate the new value. –vector s can report the number of elements they contain.

Starting Out with C++, 3 rd Edition 93 Declaring a vector To use vectors in your program, you must first #include the vector header file with the following statement: #include Note: There is no.h at the end of the file name.

Starting Out with C++, 3 rd Edition 94 Declaring a vector The next step is to include the following statement after your #include statements: using namespace std; The STL uses namespaces to organize the names of its data types and algorithms.

Starting Out with C++, 3 rd Edition 95 Declaring a vector Now you are ready to declare an actual vector object. Here is an example: vector numbers; The statement above declares numbers as a vector of int s.

Starting Out with C++, 3 rd Edition 96 Declaring a vector You can declare a starting size, if you prefer. Here is an example: vector numbers(10); The statement above declares numbers as a vector of 10 int s.

Starting Out with C++, 3 rd Edition 97 Other examples of vector Declarations Declaration FormatDescription vector amounts; Declares amounts as an empty vector of float s. vector scores(15); Declares scores as a vector of 15 int s. vector letters(25, 'A'); Declares letters as a vector of 25 characters. Each element is initialized with 'A'. vector values2(values1); Declares values2 as a vector of double s. All the elements of values1, which also a vector of doubles, are copied to value2.

Starting Out with C++, 3 rd Edition 98 Storing and Retrieving Values in a vector To store a value in an element that already exists in a vector, you may use the array subscript operator [].

Starting Out with C++, 3 rd Edition 99 Program 7-23 // This program stores, in two vectors, the hours worked by 5 // employees, and their hourly pay rates. #include #include // Needed to declare vectors using namespace std; void main(void) { vector hours(5); // Declare a vector of 5 integers vector payRate(5); // Declare a vector of 5 floats cout > hours[index]; cout > payRate[index]; }

Starting Out with C++, 3 rd Edition 100 Program 7-23 (continued) 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[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } }

Starting Out with C++, 3 rd Edition 101 Program 7-23 (continued) Program Output with Example Input Shown in Bold Enter the hours worked by 5 employees and their hourly rates. Hours worked by employee #1: 10 [Enter] Hourly pay rate for employee #1: 9.75 [Enter] Hours worked by employee #2: 15 [Enter] Hourly pay rate for employee #2: 8.62 [Enter] Hours worked by employee #3: 20 [Enter] Hourly pay rate for employee #3: [Enter] Hours worked by employee #4: 40 [Enter] Hourly pay rate for employee #4: [Enter] Hours worked by employee #5: 40 [Enter] Hourly pay rate for employee #5: [Enter] Here is the gross pay for each employee: Employee #1: $97.50 Employee #2: $ Employee #3: $ Employee #4: $ Employee #5: $626.00

Starting Out with C++, 3 rd Edition 102 Using the push_back Member Function You cannot use the [] operator to access a vector element that does not exist. To store a value in a vector that does not have a starting size, or is already full, use the push_back member function. Here is an example: numbers.push_back(25);

Starting Out with C++, 3 rd Edition 103 Program 7-24 // This program stores, in two vectors, the hours worked by a specified // number of employees, and their hourly pay rates. #include #include // Needed to declare vectors using namespace std; void main(void) { vector hours; // hours is an empty vector vector payRate; // payRate is an empty vector int numEmployees; // The number of employees cout > numEmployees; cout << "Enter the hours worked by " << numEmployees; cout << " employees and their hourly rates.\n";

Starting Out with C++, 3 rd Edition 104 Program 7-24 (continued) for (int index = 0; index > tempHours; hours.push_back(tempHours); // Add an element to hours cout > tempRate; payRate.push_back(tempRate); // Add an element to payRate } cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < numEmployees; index++) { float grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } }

Starting Out with C++, 3 rd Edition 105 Program 7-24 (continued) Program Output with Example Input Shown in Bold How many employees do you have? 3 [Enter] Enter the hours worked by 3 employees and their hourly rates. Hours worked by employee #1: 40 [Enter] Hourly pay rate for employee #1: [Enter] Hours worked by employee #2: 25 [Enter] Hourly pay rate for employee #2: [Enter] Hours worked by employee #3: 45 [Enter] Hourly pay rate for employee #3: [Enter] Here is the gross pay for each employee: Employee #1: $ Employee #2: $ Employee #3: $

Starting Out with C++, 3 rd Edition 106 Determining the Size of a vector Unlike arrays, vectors can report the number of elements they contain. This is accomplished with the size member function. Here is an example of a statement that uses the size member function: numValues = set.size(); In the statement above, assume that numValues is an int, and set is a vector. After the statement executes, numValues will contain the number of elements in the vector set.

Starting Out with C++, 3 rd Edition 107 Determining the Size of a vector Example: void showValues(vector vect) { for (int count = 0; count < vect.size(); count++) cout << vect[count] << endl; }

Starting Out with C++, 3 rd Edition 108 Program 7-25 // This program demonstrates the vector size // member function. #include #include using namespace std; // Function prototype void showValues(vector ); void main(void) { vector values; for (int count = 0; count < 7; count++) values.push_back(count * 2); showValues(values); }

Starting Out with C++, 3 rd Edition 109 Program 7-25 (continued) //************************************************** // Definition of function showValues. * // This function accepts an int vector as its * // argument. The value of each of the vector's * // elements is displayed. * //************************************************** void showValues(vector vect) { for (int count = 0; count < vect.size(); count++) cout << vect[count] << endl; }

Starting Out with C++, 3 rd Edition 110 Program 7-25 (continued) Program Output

Starting Out with C++, 3 rd Edition 111 Removing Elements from a vector Use the pop_back member function to remove the last element from a vector. collection.pop_back(); The statement above removes the last element from the collection vector.

Starting Out with C++, 3 rd Edition 112 Program 7-26 // This program demosntrates the vector size member function. #include #include using namespace std; void main(void) { vector values; // Store values in the vector values.push_back(1); values.push_back(2); values.push_back(3); cout << "The size of values is " << values.size() << endl; // Remove a value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl;

Starting Out with C++, 3 rd Edition 113 Program 7-26 (continued) // Now remove another value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl; // Remove the last value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl; } Program Output The size of values is 3 Popping a value from the vector... The size of values is now 2 Popping a value from the vector... The size of values is now 1 Popping a value from the vector... The size of values is now 0

Starting Out with C++, 3 rd Edition 114 Clearing a vector To completely clear the contents of a vector, use the clear member function. Here is an example: numbers.clear(); After the statement above executes, the numbers vector will be cleared of all its elements.

Starting Out with C++, 3 rd Edition 115 Program 7-27 // This program demosntrates the vector size member function. #include #include using namespace std; void main(void) { vector values(100); cout << "The values vector has “ << values.size() << " elements.\n"; cout << "I will call the clear member function...\n"; values.clear(); cout << "Now, the values vector has “ << values.size() << " elements.\n"; }

Starting Out with C++, 3 rd Edition 116 Program 7-27 (continued) Program Output The values vector has 100 elements. I will call the clear member function... Now, the values vector has 0 elements.

Starting Out with C++, 3 rd Edition 117 Detecting an Empty vector To determine if a vector is empty, use the empty member function. The function returns true if the vector is empty, and false if the vector has elements stored in it. Here is an example of its use: if (set.empty()) cout << "No values in set.\n";

Starting Out with C++, 3 rd Edition 118 Program 7-28 // This program demosntrates the vector's empty member function. #include #include using namespace std; // Function prototype float avgVector(vector ); void main(void) { vector values; int numValues; float average; cout > numValues;

Starting Out with C++, 3 rd Edition 119 Program 7-28 (continued) for (int count = 0; count > tempValue; values.push_back(tempValue); } average = avgVector(values); cout << "Average: " << average << endl; } //************************************************************* // Definition of function avgVector. * // This function accepts an int vector as its argument. If * // the vector contains values, the function returns the * // average of those values. Otherwise, an error message is * // displayed and the function returns 0.0. * //*************************************************************

Starting Out with C++, 3 rd Edition 120 Program 7-28 (continued) float avgVector(vector vect) { int total = 0;// accumulator float avg;// average if (vect.empty())// Determine if the vector is empty { cout << "No values to average.\n"; avg = 0.0; } else { for (int count = 0; count < vect.size(); count++) total += vect[count]; avg = total / vect.size(); } return avg; }

Starting Out with C++, 3 rd Edition 121 Program 7-28 (continued) Program Output with Example Input Shown in Bold How many values do you wish to average? Enter a value: 12 Enter a value: 18 Enter a value: 3 Enter a value: 7 Enter a value: 9 Average: 9 Program Output with Example Input Shown in Bold How many values do you wish to average? 0 No values to average. Average: 0

Starting Out with C++, 3 rd Edition 122 Summary of vector Member Functions Member FunctionDescription at(element) Returns the value of the element located at element in the vector. Example: x = vect.at(5); The statement above assigns the value of the 5 th element of vect to x. capacity() Returns the maximum number of elements that may be stored in the vector without additional memory being allocated. (This is not the same value as returned by the size member function). Example: x = vect.capacity(); The statement above assigns the capacity of vect to x.

Starting Out with C++, 3 rd Edition 123 Summary of vector Member Functions clear() Clears a vector of all its elements. Example: vect.clear(); The statement above removes all the elements from vect. empty() Returns true if the vector is empty. Otherwise, it returns false. Example: if (vect.empty()) cout << "The vector is empty."; The statement above displays the message if vect is empty. pop_back() Removes the last element from the vector. Example: vect.pop_back(); The statement above removes the last element of vect, thus reducing its size by 1.

Starting Out with C++, 3 rd Edition 124 Summary of vector Member Functions push_back(value) Stores a value in the last element of the vector. If the vector is full or empty, a new element is created. Example: vect.push_back(7); The statement above stores 7 in the last element of vect. reverse() Reverses the order of the elements in the vector (the last element becomes the first element, and the first element becomes the last element.) Example: vect.reverse(); The statement above reverses the order of the element in vect. resize(elements, value) Resizes a vector by elements elements. Each of the new elements is initialized with the value in value. Example: vect.resize(5, 1); The statement above increases the size of vect by 5 elements. The 5 new elements are initialized to the value 1.

Starting Out with C++, 3 rd Edition 125 Summary of vector Member Functions swap(vector2) Swaps the contents of the vector with the contents of vector2. Example: vect1.swap(vect2); The statement above swaps the contents of vect1 and vect2.