Chapter 7 - Introduction To Arrays
Chapter 7 - Introduction To Arrays
CHAPTER 7:
Introduction to Arrays
2 ARRAYS
[LEARNING OUTCOMES]
At the end this class, students should able:
What is array?
Array declaration
Array initialization
Accessing individual elements of an array
Character Arrays
Passing array to FUNCTION
3 WHAT IS ARRAY?
• Example:
int num[5];
element_type array_name[number_of_elements];
• You can initialize an array when you declare it (just like with
variables):
• Example:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};
PARTIAL INITIALIZATION OF ARRAYS DURING
DECLARATION
13
• The statement:
• The statement:
cout << "Enter " << SIZE << " gpas: ";
Based on the program above, illustrate how gpa look like in a memory.
19 EXERCISE 01 - ANSWER
• Assign 7 to the first element and -25 to the last element in array A
A[0] = 7;
A[N-1] = -25; // better than A[49] = -25
22 ARRAYS - EXERCISE 03
Answer:
Answer:
for(i = 1; i < N; i += 2)
cin >> A[i];
24 ARRAYS - EXERCISE 05
Answer:
• #include <iostream.h>
void main()
printArray(numbers, 5);
}
28 PASSING SIZE ALONG WITH
ARRAY
• Normally when you pass an array to a function,
you should also pass its size in another argument.
So the function knows how many elements are in
the array.
• Otherwise, you will have to hard code this into
the function or declare it in a global variable.
Neither is flexible or robust.
29 Two-Dimensional Arrays
int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
};
int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};
32 Printing a 2D Arrays i C++
#include<iostream>
using namespace std;
main( )
{
int arr[4][2] = {
{ 10, 11 },
{ 20, 21 },
{ 30, 31 },
{ 40, 41 }
};
int i,j;
cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}
….as user input
#include<iostream>
33 using namespace std;
main( )
{
int s[2][2];
int i, j;
cout<<"\n2D Array Input:\n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\
ns["<<i<<"]["<<j<<"]= ";
cin>>s[i][j];
}
}