Array in C++


Structured Data Type


Array

Array is a collection of similar type of data that shares a common name.
In C++, all arrays consist of contiguous memory location.
                  
Array can have data items of simple types like int or float, or even of user defined types like structures and objects.

The element member in [] are called subscripts or indices. The subscript or index of an element designates its position in array’s ordering.
Ex.  
Array in C++

Array in C++


Advantage

1.      It is used to represent multiple data items of same type by using only single name.

2.    It can be used to implement other data structure like linked lists, stacks, queues, trees, graphs etc.


Types of array

1.      One-dimensional array
2.    Multi-dimensional array

1.One-dimensional array

The simplest form of an array is a single dimensional array. The array has a name and its elements are referred to by their subscripts or indices.

C++ array index numbering starts with 0.

Declaration /initialization
      type array-name[size];

 Ex. int marks [50];
 int marks= {85, 90, 72, 82};

Q. Program to read the marks of 50 students and store them in an array.

#include<iostream.h>
void main()
{
 const int size=50;
 float marks[size];
 for (int i=0; i<size; i++)
{
 cout<<”Enter the marks of student”<<i+1<<”\n”;
 cin>>marks[i];
 }
cout<<”\n”;
for(i=0; i<size; i++)
{
 cout<<”Marks [“<<i<<”] =”<<Marks[i] <<”\n”;
}
}


Manipulation of array elements


Program to read price of 20 items in an array and then display sum of all the prices, product of all the prices and average of them.


#include<iostream.h>
int main()
{
 double Price [20],sum, avg, prod;
 sum=avg=0;
 prod=1;
 for(int i=0;i<20; ++i)
 {
 cout<<”Enter price for item”<<i+1<<”:”;
 cin>>Price[i];
 sum+=Price[i];
 prod*=Price[i];
 }
avg=sum/20;
cout<<”Sum of all prices=”<<sum<<endl;
cout<<”Product of all prices=”<<prod<<endl;
cout<<”Average of all prices=” <<avg<<endl;
return 0;
}


Linear Search

Sometimes we need to search for an element in an array. This can be done by comparing the search-item with each and every element of the array.

Ex.
#include<iostream.h>
int main()
{
 int A[20],size, i, flag=0, num, pos;
 cout<<”\n Enter the number of elements in the array:”;
 cin>>size;
 cout<<”\n Enter the elements of array:”;
 for (i=0;i<size; i++)
{
 cin>>A[i];
 }
cout<<”Enter the element to be searched for:”;
cin>>num;
for(i=0;i<size;i++)
{
 if(A[i]==num)
 {
flag=1;
pos=i;
break;
}
if(flag==0)
   cout<<”\n Element not found”;
else
  cout<<”\n Element found at position”<<(pos+1);
return;
}


String as an array

C++ does not have a string data type rather it implements string as single-dimension character array. A string is defined as a character array that is terminated by a null character ‘\0’.

Declaration

    char strg[11];


Program to find number of vowels in a given line of text.

#include<iostream.h>
#include<stdio.h>
int main()
{
 char line[80];
 int vow=0;
 cout<<”Enter the line:”<<endl;
 gets(line);
 for(int i=0; line[i]!=’\0’;++i)
 {
   switch(line[i])
  {
case a:
case A:
case e:
case E:
case i:
case I:
case o:
case O:
case u:
case U: ++vow;
}
}
cout<<”the total number of vowels in the given line is”<<vow<<endl;
return 0;
}

Output:
Enter the line:
God is Great
The total number of vowels in the given line is 4

 Program to find the maximum value in an array.

#include<iostream.h>
void main()
{
int arr[25],size, i, max;
cout<<”\n Enter the no. of elements in an array”;
cin>>size;
cout<<”Enter the element of array”;
for(i=0; i<size; i++)
{
cin>>arr[i];
}
max=arr[0];
for(i=0; i<size; i++)
{
 if(arr[i]>max)
{
max=arr[i];
}
}
cout<<”Maximum value is:”<<max;
}

Program to reverse words of a string individually if you enter: I read C++, it should display I daer ++C.

#include<iostream.h>
#include<stdio.h>
#include<string.h>
void main()
{
int i, k=0;
char str[80], word[80];
cout<<”Enter any string:”<<endl;
gets(str);
strcat(str, “ ”);
for(i=0; str[i]!=’\0’;i++)
{
if(str[i]!=’ ’)
{
word[k]=str[i];
k=k+1;
}
else
{
while(k>0)
{
cout<<word[--k];
}
cout<<str[i];
}
}
}

Output: Enter any string: I read c++
I daer ++c

 Program to convert a string to proper case.

#include<iostream.h>
#include<stdio.h>
#include<ctype.h>
int main()
{
char str[80];
int i;
cout<<”\n Enter any string”;
gets(str);
str[0]=toupper(str[0]);
for(i=0; str[i]!=’\0’;i++)
{
if(str[i]==’ ‘)
{
str[i+1]=toupper(str[i+1]);
}
}
cout<<”\n Updated string is:”<<str;
return 0;
}

Output:
Enter any string: mira rehaan augustine
Updated string is: Mira Rehaan Augustine 

 Program to reversing a string.

#include<iostream.h>
#include<stdio.h>
#include<string.h>
void main()
{
char str[80];
cout<<”Enter sring”;
gets(str);
cout<<strrev(str);
}

 Program to find the vowels, consonants, digits and white space character.

#include<iostream.h>
#include<stdio.h>
void main()
{
char s[80];
int i, v=0, c=0, d=0, s=0;
cout<<”Enter the line of string:”<<endl;
gets(s);
for(i=0; s[i]!=’\0’; i++)
{
if(s[i]==’a’|| s[i]==’e’ ||s[i]==’i’ ||s[i]==’o’ ||s[i]==’u’)
++v;
else if((s[i]>=’a’ && s[i]<=’z’)||(s[i]>=’A’ && s[i]<=’z’))
++c;
else if(s[i]>=’0’&& s[i]<=’9’)
++d;
else if  (s[i]== ‘ ‘)
++s;
}
cout<<”\n Vowels :” << v << ”Consonants:” << c << ”Digits” << d ; cout<<”Space” <<s;
}

Output :
Enter the line of string:
This program is easy to understand
Vowels:10 Consonants:20 Digits:0  Space : 5


Two dimensional Array

A two dimensional array is an array in which each elements is itself an array. A[m][n] array has mxn elements.
Ex. A [7][9]
Is calculated as 7x9=63
Declaration of 2-D array
     Type array-name [rows] [columns];

Inputting array elements

To read or process 2-D array, you need to use nested loop. One loop to process row and another for column.

int A[2][3];
int i, j;
for (i=0;i<2;i++)
{
 for (j=0;j<3;j++)
   {
   cout<<”enter the elements”;
   cin>>A[i][j];
}
}
Array in C++


Accessing array elements

for (i=0;i<2;i++)
   for (j=0;j<3;j++)
          cout<<A[i][j];


Array Initialization

The arrays are initialized in the same way as the other variables are.
The general form of initialization is shown below-
type array-name [size1]…….. [sizeN]={value-list};

Ex.
int day_of_month[12]={31,28,31,30,31,30,31,31,30,31,30,31};
char string[10]=”Program”;
Or
char string[10]={‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘\0’};
int cube[3][2]={ 1,1
                            2,8
                            3,27
                         };
Or
int cube[3][2]={1,1, 2,8, 3,27}                


Manipulation of Array Elements


·     To sum of row elements of an array.

#include<iostream.h>
#include<conio.h>
void main()
{
int a[5][6], i, j, sum=0;
cout<<”\n Enter the elements of array”;
for(i=0; i<5; i++)
{
for(j=0; j<6; j++)
{
cin>>a[i][j];
}
}
for (i=0; i<5; i++)
{
for (j=0; j<6; j++)
{
sum=sum+ a[i][j];
}
cout<<“\n The sum of row:”<< i+1<< “is”<<sum;
}
}

To sum of diagonal elements of 2D-array.

#include<iostream.h>
#include<conio.h>
void main()
{
int array[8][8], i, j, sum=0;
for(i=0; i<8; i++)
{
cout<<”\n Enter the elements of array”;
for(j=0; j<8; j++)
{
cin>>array[i][j];
}
}
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
{
if(i==j)
{
sum=sum+ array[i][j];
}
}
}
cout<<“\n The sum of elements are:”<<sum;
}

To find the maximum element of 2D-array.

#include<iostream.h>
#include<conio.h>
void main()
{
int a[8][8], i, j, max;
for(i=0; i<8; i++)
{
cout<<”\n Enter the elements of array”;
for(j=0; j<8; j++)
{
cin>>a[i][j];
}
}
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
{
if(a[i][j]>max)
{
max= a[i][j];
}
}
cout<<“\n Max element in 2D array is:”<<max;
}



This post is about Array in C++. In the next post we will discuss the topic Structure.
























Post a Comment

0 Comments