SlideShare a Scribd company logo
1 of 21
Jeanine Ingber
Arrays
Jeanine Ingber
Arrays
 An array is an indexed data structure
 An array stores a collection of variables
 All variables stored in an array are of the same
data type
 An individual variable within an array is called an
element of the array
 An element of an array is accessed using the array
name and an index
 The name of the array is the address of the first
element. The index is the offset
Jeanine Ingber
Declaring an array
 data type array_name[size];
– allocates memory for size variables
– index of first element is 0
– index of last element is size-1
– size must be a constant
Jeanine Ingber
Declaring an array- Example
 Example: int list[10];
– allocates memory for 10 integer variables
– index of first element is 0
– index of last element is 9
– C++ does not perform any bounds checking on arrays
list[0]
list[1]
list[9]
Jeanine Ingber
Initializing Arrays
 Arrays can be initialized at the time they are
declared.
Examples:
double taxrate[3] ={0.15, 0.25, 0.3};
char word[] = “hello”; //word has size 6
char list[5] = {‘h’,’e’,’l’,’l’,’o’};
//list of characters, not a string
double vector[100] = {0.0}; //assigns zero to all 100 elements
Jeanine Ingber
Assigning values to an array
•for loops are often used to assign values to an array
•Example:
int list[10];
for(int I=0; I<10; I++)
list[I] = I;
•Example
int count;
cin >> count;
for(int I=0; I<count; I++)
cin >> list[I];
Jeanine Ingber
Arrays As Arguments to
Functions
 Individual elements of an array can be
passed as regular arguments. They can be
pass by reference or pass by value.
 Example
void donothing(int&, int, int);//prototype
int main()
{
int array[5] = {1,2,3,4,5};
donothing(array[0], array[2], array[4]);
.
.
Jeanine Ingber
Passing Entire Arrays as
Arguments to Functions
 Arrays are always pass by reference
 The array name is the address of the first element
 Arrays arguments that are not to be altered by the function
should use the modifier const in the prototype and the
function header
 The maximum size of the array must be specified at the
time the array is declared. The actual number of array
elements that have values assigned will vary, so the actual
size of the array is often passed as an argument to the
function
Jeanine Ingber
Example
int maxval(const int array[], int actual_size); //prototype
const int MAXSIZE=100;
int main()
{
ifstream fin(“input”);
int numbers[MAXSIZE], temp, count=0, maximum;
fin >> temp;
while(!fin.eof() && count < MAXSIZE) //input data from file
{
numbers[count] = temp;
count++; //count number of entries
fin >> temp;
}
maximum = maxval(numbers, count);
cout << “The array has “ << count << “ values.nThe largest value is “
<< maximum << endl;
return 0;
}//end main
Jeanine Ingber
Function Definition for maxval
int maxval(const int array[], int actual_size)
{
int temp;
temp = array[0]; //initialize temp to first value in array
for(int I=1; I<actual_size; I++)
{
if(array[I] > temp)
temp = array[I];
}
return temp;
}//end maxval
Jeanine Ingber
Quiz
Jeanine Ingber
Modifying arrays in functions -
Selection Sort
void selection_sort(int array[], int actual_size); //prototypes
int find_max_pos(const int array[], int size, int top);
void swap(int& v1, int& v2);
void get_data(istream& fin, int array[], int& count);
void print_data(const int[], int);
const int MAXSIZE=100;
int main()
{
int array[MAXSIZE], count;
get_data(cin,array, count);
cout << “the input data is “;
print_data(array, count);
selection_sort(array, count);
cout << “the sorted data is “;
print_data(array, count);
return 0;
}//end main
Jeanine Ingber
Function Definition -
Selection Sort
void selection_sort(int array[], int size)
{
int max_pos;
for(int i=0; i<size-1; i++)
{
max_pos = find_max_pos(array, size, i);
swap(array[i], array[max_pos];
}
}//end selection_sort
Jeanine Ingber
Function Definition for find_max_pos and
swap
int find_max_pos(const int array[], int actual_size, int top)
{
int temp;
temp = top; //initialize temp to index of first value in array
for(int I=top+1; I<actual_size; I++)
{
if(array[I] > array[temp])
temp = I;
}
return temp;
}//end maxval
void swap(int& n1, int& n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
Jeanine Ingber
Selection Sort Illustrated
Jeanine Ingber
Two Dimensional Arrays
 C++ supports multi-dimensional array
– data type array_name[row_size][column_size]
– int matrix[3][4];
row[0]
row[1]
row[2]
in memory
row1 row2 row3
Jeanine Ingber
Accessing Array Elements
 int matrix[3][4];
– matrix has 12 integer elements
– matrix[0][0] element in first row, first column
– matrix[2][3] element in last row, last column
– matrix is the address of the first element
– matrix[1] is the address of the second row
Jeanine Ingber
2-Dimensional Arrays
 As arguments to functions
– column size must be declared in prototype and
header
Jeanine Ingber
Programming Example
#include<iostream>
using namespace std;
const int ROWS=10, COLS=10;
//prototypes
void Fill_Up(double[][COLS], int&, int&);
void Display(double[][COLS], int, int);
void Form_Transpose(double[][COLS], int, int, double[][COLS]);
int main()
{
double A[ROWS][COLS], A_Transpose[ROWS][COLS];
int row_count, col_count;
Fill_Up(A, row_count, col_count);
cout << "Matrix A (" << row_count << "rows, " << col_count << "columns)n";
Display(A, row_count, col_count);
Form_Transpose(A, row_count, col_count, A_Transpose);
cout << "Matrix A_Transpose (" << col_count << "rows, ”
<< row_count << "columns)n";
Display(A_Transpose, col_count, row_count);
return 0;
}//end main
Jeanine Ingber
Example
if(row_count == col_count)
{
cout << "Sum of elements along the main diagonal of A is "
<< Sum_Diag(A, row_count);
cout << "Sum of elements above the main diagonal of A is "
<< Sum_Above_Diag(A, row_count);
}//end if
return0;
}
#include<iostream>
using namespace std;
const int ROWS=10, COLS=10;
//prototypes
void Fill_Up(double[][COLS], int&, int&);
double Sum_Diag(const double[][COLS], int);
double Sum_Above_Diag( const double[][COLS], int);
int main()
{
double A[ROWS][COLS];
int row_count, col_count;
Fill_Up(A, row_count, col_count);
Jeanine Ingber
Quiz

More Related Content

Similar to Week6.ppt

Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptxMrMaster11
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.pptcoding9
 
Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...ssuser6478a8
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
Array assignment
Array assignmentArray assignment
Array assignmentAhmad Kamal
 
Chapter12 array-single-dimension
Chapter12 array-single-dimensionChapter12 array-single-dimension
Chapter12 array-single-dimensionDeepak Singh
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdffonecomp
 
Data structure array
Data structure  arrayData structure  array
Data structure arrayMajidHamidAli
 
Programming fundamentals week 12.pptx
Programming fundamentals week 12.pptxProgramming fundamentals week 12.pptx
Programming fundamentals week 12.pptxdfsdg3
 

Similar to Week6.ppt (20)

C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Lecture 2.8 Arrays.pdf
Lecture 2.8 Arrays.pdfLecture 2.8 Arrays.pdf
Lecture 2.8 Arrays.pdf
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
2 arrays
2   arrays2   arrays
2 arrays
 
Array assignment
Array assignmentArray assignment
Array assignment
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
Chapter12 array-single-dimension
Chapter12 array-single-dimensionChapter12 array-single-dimension
Chapter12 array-single-dimension
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdf
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
intorduction to Arrays in java
intorduction to Arrays in javaintorduction to Arrays in java
intorduction to Arrays in java
 
Programming fundamentals week 12.pptx
Programming fundamentals week 12.pptxProgramming fundamentals week 12.pptx
Programming fundamentals week 12.pptx
 
Arrays
ArraysArrays
Arrays
 

More from JosManuel782430

More from JosManuel782430 (17)

sedra42021_appc.ppt
sedra42021_appc.pptsedra42021_appc.ppt
sedra42021_appc.ppt
 
IP1C - SCRATCH.pptx
IP1C - SCRATCH.pptxIP1C - SCRATCH.pptx
IP1C - SCRATCH.pptx
 
Caldeiras e vapor.pptx
Caldeiras e vapor.pptxCaldeiras e vapor.pptx
Caldeiras e vapor.pptx
 
01-Aco_Carbono_Ligas.ppt
01-Aco_Carbono_Ligas.ppt01-Aco_Carbono_Ligas.ppt
01-Aco_Carbono_Ligas.ppt
 
-Polynésie.ppt
-Polynésie.ppt-Polynésie.ppt
-Polynésie.ppt
 
Torneamento.pdf
Torneamento.pdfTorneamento.pdf
Torneamento.pdf
 
4-Hierarquia Digital.pptx
4-Hierarquia Digital.pptx4-Hierarquia Digital.pptx
4-Hierarquia Digital.pptx
 
4º Linguagem Algorítmica.pptx
4º Linguagem Algorítmica.pptx4º Linguagem Algorítmica.pptx
4º Linguagem Algorítmica.pptx
 
Autómatos Programáveis (1).pptx
Autómatos Programáveis (1).pptxAutómatos Programáveis (1).pptx
Autómatos Programáveis (1).pptx
 
1 IntroSOppt1.ppt
1 IntroSOppt1.ppt1 IntroSOppt1.ppt
1 IntroSOppt1.ppt
 
Week7.ppt
Week7.pptWeek7.ppt
Week7.ppt
 
X-25.ppt
X-25.pptX-25.ppt
X-25.ppt
 
70_modal_verbs.pptx
70_modal_verbs.pptx70_modal_verbs.pptx
70_modal_verbs.pptx
 
07-Polímeros.ppt
07-Polímeros.ppt07-Polímeros.ppt
07-Polímeros.ppt
 
Microcontroladores e Arduino.pptx
Microcontroladores e Arduino.pptxMicrocontroladores e Arduino.pptx
Microcontroladores e Arduino.pptx
 
sw9_past_perfect.pptx
sw9_past_perfect.pptxsw9_past_perfect.pptx
sw9_past_perfect.pptx
 
qualidade_e_fiabilidade.ppt
qualidade_e_fiabilidade.pptqualidade_e_fiabilidade.ppt
qualidade_e_fiabilidade.ppt
 

Recently uploaded

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Recently uploaded (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Week6.ppt

  • 2. Jeanine Ingber Arrays  An array is an indexed data structure  An array stores a collection of variables  All variables stored in an array are of the same data type  An individual variable within an array is called an element of the array  An element of an array is accessed using the array name and an index  The name of the array is the address of the first element. The index is the offset
  • 3. Jeanine Ingber Declaring an array  data type array_name[size]; – allocates memory for size variables – index of first element is 0 – index of last element is size-1 – size must be a constant
  • 4. Jeanine Ingber Declaring an array- Example  Example: int list[10]; – allocates memory for 10 integer variables – index of first element is 0 – index of last element is 9 – C++ does not perform any bounds checking on arrays list[0] list[1] list[9]
  • 5. Jeanine Ingber Initializing Arrays  Arrays can be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; char word[] = “hello”; //word has size 6 char list[5] = {‘h’,’e’,’l’,’l’,’o’}; //list of characters, not a string double vector[100] = {0.0}; //assigns zero to all 100 elements
  • 6. Jeanine Ingber Assigning values to an array •for loops are often used to assign values to an array •Example: int list[10]; for(int I=0; I<10; I++) list[I] = I; •Example int count; cin >> count; for(int I=0; I<count; I++) cin >> list[I];
  • 7. Jeanine Ingber Arrays As Arguments to Functions  Individual elements of an array can be passed as regular arguments. They can be pass by reference or pass by value.  Example void donothing(int&, int, int);//prototype int main() { int array[5] = {1,2,3,4,5}; donothing(array[0], array[2], array[4]); . .
  • 8. Jeanine Ingber Passing Entire Arrays as Arguments to Functions  Arrays are always pass by reference  The array name is the address of the first element  Arrays arguments that are not to be altered by the function should use the modifier const in the prototype and the function header  The maximum size of the array must be specified at the time the array is declared. The actual number of array elements that have values assigned will vary, so the actual size of the array is often passed as an argument to the function
  • 9. Jeanine Ingber Example int maxval(const int array[], int actual_size); //prototype const int MAXSIZE=100; int main() { ifstream fin(“input”); int numbers[MAXSIZE], temp, count=0, maximum; fin >> temp; while(!fin.eof() && count < MAXSIZE) //input data from file { numbers[count] = temp; count++; //count number of entries fin >> temp; } maximum = maxval(numbers, count); cout << “The array has “ << count << “ values.nThe largest value is “ << maximum << endl; return 0; }//end main
  • 10. Jeanine Ingber Function Definition for maxval int maxval(const int array[], int actual_size) { int temp; temp = array[0]; //initialize temp to first value in array for(int I=1; I<actual_size; I++) { if(array[I] > temp) temp = array[I]; } return temp; }//end maxval
  • 12. Jeanine Ingber Modifying arrays in functions - Selection Sort void selection_sort(int array[], int actual_size); //prototypes int find_max_pos(const int array[], int size, int top); void swap(int& v1, int& v2); void get_data(istream& fin, int array[], int& count); void print_data(const int[], int); const int MAXSIZE=100; int main() { int array[MAXSIZE], count; get_data(cin,array, count); cout << “the input data is “; print_data(array, count); selection_sort(array, count); cout << “the sorted data is “; print_data(array, count); return 0; }//end main
  • 13. Jeanine Ingber Function Definition - Selection Sort void selection_sort(int array[], int size) { int max_pos; for(int i=0; i<size-1; i++) { max_pos = find_max_pos(array, size, i); swap(array[i], array[max_pos]; } }//end selection_sort
  • 14. Jeanine Ingber Function Definition for find_max_pos and swap int find_max_pos(const int array[], int actual_size, int top) { int temp; temp = top; //initialize temp to index of first value in array for(int I=top+1; I<actual_size; I++) { if(array[I] > array[temp]) temp = I; } return temp; }//end maxval void swap(int& n1, int& n2) { int temp; temp = n1; n1 = n2; n2 = temp; }
  • 16. Jeanine Ingber Two Dimensional Arrays  C++ supports multi-dimensional array – data type array_name[row_size][column_size] – int matrix[3][4]; row[0] row[1] row[2] in memory row1 row2 row3
  • 17. Jeanine Ingber Accessing Array Elements  int matrix[3][4]; – matrix has 12 integer elements – matrix[0][0] element in first row, first column – matrix[2][3] element in last row, last column – matrix is the address of the first element – matrix[1] is the address of the second row
  • 18. Jeanine Ingber 2-Dimensional Arrays  As arguments to functions – column size must be declared in prototype and header
  • 19. Jeanine Ingber Programming Example #include<iostream> using namespace std; const int ROWS=10, COLS=10; //prototypes void Fill_Up(double[][COLS], int&, int&); void Display(double[][COLS], int, int); void Form_Transpose(double[][COLS], int, int, double[][COLS]); int main() { double A[ROWS][COLS], A_Transpose[ROWS][COLS]; int row_count, col_count; Fill_Up(A, row_count, col_count); cout << "Matrix A (" << row_count << "rows, " << col_count << "columns)n"; Display(A, row_count, col_count); Form_Transpose(A, row_count, col_count, A_Transpose); cout << "Matrix A_Transpose (" << col_count << "rows, ” << row_count << "columns)n"; Display(A_Transpose, col_count, row_count); return 0; }//end main
  • 20. Jeanine Ingber Example if(row_count == col_count) { cout << "Sum of elements along the main diagonal of A is " << Sum_Diag(A, row_count); cout << "Sum of elements above the main diagonal of A is " << Sum_Above_Diag(A, row_count); }//end if return0; } #include<iostream> using namespace std; const int ROWS=10, COLS=10; //prototypes void Fill_Up(double[][COLS], int&, int&); double Sum_Diag(const double[][COLS], int); double Sum_Above_Diag( const double[][COLS], int); int main() { double A[ROWS][COLS]; int row_count, col_count; Fill_Up(A, row_count, col_count);