Array of Variables Vikram Kulkarni MBA - Systems
Arrays of Variables In this chapter we will: Introduce the array as a structure for storing large amounts of data Discuss common array operations Introduce algorithms for searching and sorting arrays
Array Array is a collection of
variables of same data type and common name.
Array Types 1. One Dimensional Array 2. Two Dimensional Array
3. Multi Dimensional Arrays
3D, 4D and so on…
Example of Multi-Dimensional Array
Declaration of Array It is the same as Variable
Declaration The only difference is the number of array elements need Int count[10]; name[25];in the [ ] to beChar specified Int marks[10][5];
For two dimensional arrays
Array Initialization Arrays can be initialized by giving a list
of their elements If your list contains n elements the subscripts will range from 0 to n – 1 You do not need to allocate the array Int A[5] =after {1,2,3,4,5}; explicitly it is initialized. Float S[3] = {1.4,2.6, 8.3}; Char city[20] = “mumbai”; Int d[2][3] = {{23,30}, {14,76}, {5,21}}; Int arr[] = {5,6,7,0,10,34};
Array Subscripts Subscripts are used to access specific
array values. Subscripts starts with 0 and goes up to (n-1). Int c[7]; counts[0] counts[1] counts[6] counts[7]
// first variable in counts // second variable in counts // last variable in counts // error – trying to access // variable outside counts
c0 c1 c2 c3 c4 c5 c6
Sample Program #include
Void main () { Int a[5],i; //single dimension array for (i=0;i<5;i++) { cout << “enter any number /n”; cin>>a[i]; } cout << “numbers you entered was”; for (i=0;i<5;i++) { cout << a[i]<<“/n”; } }
Sample Program #include void main() { int A[3][4]; int i; int j; for(i=0;i<3;i++) { for(j=0;j<4;j++) { cout<<“Enter a number: “; cin>>A[i][j]; }} cout<<“\n Array Contents\n”; for(i=0;i<4;i++) { for(j=0;j<4;j++) cout<
Array Operations – Copying #include Void main () { Int a[5],b[5],i; for (i=0;i<5;i++) { cout << “enter any number /n”; cin>>a[i]; } b=a; //Copying array cout << “numbers you entered was”; for (i=0;i<5;i++) { cout << b[i]<<“/n”; } }
Excersies - 1 Declare the array of 7 elements. Accept the array elements. Reverse the elements. Show the array.
Excersies – 2 Write a program to Input student name (max. 20 char) Input mark for 4 subjects. Calculate total marks. Display results as, <student name> <m1> <m2> <m3> <m4>