About Me

Introduction to Array


An array is a fixed-size sequenced collection of elements of the same data type. It is simply a grouping of like-type data.

For example, an array to contain 5 integer values of type int called billy could be represented like this:


Where each blank panel represents an element of the array, that in this case, are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.


We can use arrays to represent not only simple lists of values but also tables of data in two, three or more dimensions. In this section, introduce the concept of an array and discuss how to use it to create and apply the following types of array.

1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array


One-Dimensional Array

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or one-dimensional array.

Syntax of One-Dimensional Array

Therefore, in order to declare an array called billy as the one shown in the above diagram, it is as simple as:

type  name [elements];


Declaration and Defining an Array

int billy [5];

NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value.

Initialization an Array

In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:

int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }:

int billy [] = { 16, 2, 77, 40, 12071 };

After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.





Accessing individual elements of an Array

In any point of a program in which an array is visible, we can access the value of any of its elements individually as

name[index]

Following the previous examples in which billy had 5 elements and each of those elements was of type int, the name which we can use to refer to each element is the following:

For example, to store the value 75 in the third element of billy, we could write the following statement:
and, for example, to pass the value of the third element of billy to a variable called a, we could write:

a = billy[2];

// WAP using Array 


using namespace std;

int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}



C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.

#include <iostream>
using namespace std;

int main()
{
    int numbers[5], sum = 0;
    cout << "Enter 5 numbers: ";
   
    //  Storing 5 number entered by user in an array
    //  Finding the sum of numbers entered
    for (int i = 0; i < 5; ++i)
    {
        cin >> numbers[i];
        sum += numbers[i];
    }
   
    cout << "Sum = " << sum << endl; 
   
    return 0;
}
Output
Enter 5 numbers: 3
4
5
4
2
Sum = 18


Character Arrays and Strings

A string is a sequence of characters that is treated as a single data item. A string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows −

char greeting[] = "Hello";

Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −


#include <iostream>

using namespace std;

int main () {

   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Greeting message: ";
   cout << greeting << endl;

   return 0;
}

Output:  Hello





Sr.No
Function & Purpose
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.

#include <iostream>
#include <cstring>
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;
}


OUTPUT:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10








Two Dimensional Array 

It is a collection of data elements of same data type arranged in rows and columns (that is, in two dimensions).

Syntax:

Type arrayName[numberOfRows][numberOfColumn];


Declaration of Two-Dimensional Array

int Sales[3][5];




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}};


Referring to Array Elements
To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:

name[rowIndex][columnIndex]

Examples:
cout<<A[1][2];      //print an array element
A[1][2]=13;         // assign value to an array element

cin>>A[1][2];       //input element



// WAP using Two Dimensional Arrays


#include "iostream"
#include "stdafx.h"
using namespace std;
 //Swap function declaration

int main()
{


int add[2][3],i,j,total=0;

for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
cout << "add[" << i << "][" << j << "] : ";
         cin >> add[i][j];
}
}
cout << "You have entered the matrix :- " << endl;
   for ( i = 0; i < 2; i++ )
   {
      for ( j = 0; j < 3; j++ )
  {
         cout << add[i][j] << " ";
      }

      cout << endl;
   }

system("pause");
   return 0;


}

Post a Comment

0 Comments