Professional Documents
Culture Documents
Fundamentals of Computer
Programming
Arrays (CLO3)
Lecture 06
By
Ms. Rukaiya
What is Array?
• Array
– group of consecutive memory locations
– Same name and data type.
• A simple variable is a single memory location with
unique name and a type.
• The memory locations in the array are known as
elements of array.
• The total number of elements in the array is called
length of array.
• The elements of an array are accessed with
reference to its position in array, that is called
index or subscript.
2003 Prentice Hall, Inc. All rights reserved.
3
Array
name
int c[12]
Declaring Arrays
Array Initialization
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
– If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
– Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore n is a 5 element array
11
12 int main()
13 {
14 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
15
16 cout << "Element" << "Value" << endl;
17
18 for ( int i = 0; i < 10; i++ )
19 cout << i << n[ i ] << endl;
20
21 return 0;
22 }
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37 2003 Prentice Hall, Inc.
All rights reserved.
1 // Fig. 4.7: fig04_07.cpp
2 // A const object must be initialized Outline
3
4 int main()
5 {
6 const int x; // Error: x must be initialized
7
8 x = 7; // Error: cannot modify a const variable
9
10 return 0;
11 }
Fig04_07.cpp:
Error E2304 Fig04_07.cpp 6: Constant variable 'x' must be
initialized in function main()
Error E2024 Fig04_07.cpp 8: Cannot modify a const object in
function main()
*** 2 errors in Compile ***
Types of Array
• One dimensional
• Two dimensional
• Multi-dimensional
0 1 2 3 4
int marks
0 1 2 3 4
int marks 70 54 82 96 49
• Individual element
Array_name[index];
• Using loop
int marks[5];
for (int i=0;i<=4;i++)
cout << marks[i] < “\n”;
int main()
{
int age[4];
for(int j=0;j<4;j++){
cout<<“Enter an age”;
cin >> age[j];}
for(j=0;j<4;j++)
cout <<“ you entered” << age[j] <<endl;
return 0;
}
}
2003 Prentice Hall, Inc. All rights reserved.
14
Example
#define SIZE 10; /* symbolic constant SIZE can be used to specify array size */
int main( ){
int s[SIZE];
int j; /* counter */
Practice problems
Practice problems
1. Write a program C++ program to create an array with reverse
elements of one dimensional array
2. Write a program C++ program to find largest element in a one
dimensional array
3. Suppose X. Y, Z are arrays of integers of size M, N, and M + N
respectively. The numbers in array X and Y appear in descending
order. Write a C++ program to produce third array Z by merging
arrays X and Y in descending order
4. Print following triangle using one dimensional array