User Menu

Login



Share with

One Dimensional Array PDF Print E-mail

Array

array

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.

Arrays come in two flavors: one dimensional and dimensional arrays.

Declaring an Array

Just like any variable ,an array has to be declared before being used. Yet the difference this time is that you need to tell the compiler what kind of array you are defining. This is because, once more, the compiler wants to know how much space your array is going to occupy in the computer memory. This is because when you declare an array of items, the compiler puts each one of the items in an appropriate location. 
Like any other variable, the syntax of declaring an array is:

DataType ArrayName[size]

The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its name. The name is then followed by square brackets that specify the size of the array.

Here are examples of declaring arrays:

int a[4];

float f[100];

double d[100];

int a[4]; declares a group or array of 4 values, each one being an integer.

arraymap

float f[100]; declares an array of 100 floating-point values.

double d[100]; declares an array of double-precision numbers. There are 100 of these items in the group.


float f[100]; declares an array of 100 floating-point values.

double d[100]; declares an array of double-precision numbers. There are 100 of these items in the group.

Initializing an Array

Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a one-dimensional array, the syntax used is:

DataType ArrayName[size] = { element1, element2, …, elementn};

Here are examples of declaring an initializing arrays:

int num[5] = {1,2,3,4,5};

If you have decided to initialize the array while you are declaring it, you can omit the size. Therefore, array can be declared as follows:

int num[] = {1,2,3,4,5};

Processing the Elements of an Array

After initializing an array, its elements are counted from left to right. Each element of the array, also called a member of the array, has a specific and constant position. The position of an item is also called its index. The first member of the array, the most left, has an index of 0. The second member of the array has an index of 1. Since each array has a number of items which can be specified as n, the last member of the array has an index of n-1

Based on this system of indexing, to locate a member of an array, use its index in the group. Imagine you declare and initialize an array as follows:

double weight[] = {20.2,24.5,34.7};

To locate the value of the 3rd member of the array, you would type weight[2]. In the same way, the 1st member of the array can be located with weight[0].

Once you can locate a member of the array, you can display its value. Here is an example:

#include <iostream.h>

int main()
{
 double weight[] = {20.2,24.5,34.7};

 cout << "2nd member = " << weight[1] << endl;
 cout << "3rd member = " << weight[2] << endl;
 return 0;
}

This would produce:

2nd member = 24.5
3rd member = 34.7

The Size of an Array

When declaring an array, we saw that you must specify the number of items that the array is made of. Here is an example:

float price[5];

Depending on how you want to deal with your array, you may sometimes need to increase or decrease its dimension. To do this, you would need to locate the declaration of the array and change its dimension. If the program is long and the array is declared in some unusual place, this could take some time. The alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example:

#include <iostream.h>

int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};

    cout << "weight 1: " << weight[0] << endl;
    cout << "weight 2: " << weight[1] << endl;
    cout << "weight 3: " << weight[2] << endl;
    cout << "weight 4: " << weight[3] << endl;
    cout << "weight 5: " << weight[4] << endl;

return 0;
}
We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array. Imagine you declare a large array, possibly made of 50 or 100 members, you wouldn't start counting the number of members. C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use is:

sizeof(NameofArray)

If we declare an array as follows:

int number[] = {1,2,3,4,5};

Instead of counting the number of members of this array  we can use the sizeof operator as follows:
int NumberOfElements = sizeof(Number)/sizeof(int);

Accessing Array Members

int items[5];

Each member of the array can be located using its index, as we have seen so far. In the same way, you can request the value of any member of the array using its index. In the following example, we declare an array of 5 integers and then we request the values of the 2nd and the 4th members:

#include <iostream.h>

int main()

{
    const int count = 5;

    int items[count];

    cout << "Enter the values of two items\n";
    cout << "Item 1: ";
    cin >> items[0];
    cout << "item 4: ";
    cin >> items[3];
    cout << "\nYou have Entered following values";
    cout << "\nItem 1: " << items[0] ;
    cout << "\nItem 4: " << items[3] ;
    return 0;
}

Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66

Operations on Arrays

You can add the values of two members of the array(Number[2]+Number[0]), you can subtract the value of one of the members from another member(member[1]-Number[4]). In the same way, you can perform multiplication, division, or remainder operations on members of an array.

Sum of all the Elements of an Array

#include <iostream.h>

#define N 3

int main()

{
    int a1[N];

    int sum=0;

    int i;

    cout<<"Enter Elements of  Array";

    for(i=0;i<N;i++)

        cin>>a1[i];

     // Now we will find Sum

    for(i=0;i<N;i++)

          sum=sum+a1[i];

    cout<<endl<<"Sum of all The elements is "<<sum;

return 0;

}
Product of all the Elements of an Array

#include <iostream.h>

#define N 3

int main()

{
    int a1[N];

    int pro=1;

    int i;

    cout<<"Enter Elements of  Array";

    for(i=0;i<N;i++)

     cin>>a1[i];

     // Now we will find Product

    for(i=0;i<N;i++)

          pro=pro*a1[i];

    cout<<endl<<"Product of all The elements is "<<pro;

return 0;

}

Average of all the Elements of an Array

#include <iostream.h>

#define N 3

int main()

{
    int a1[N];

    int sum=0;float avg=0.0;

    int i;

    cout<<"Enter Elements of  Array";

    for(i=0;i<N;i++)

        cin>>a1[i];

     // Now we will find Average

    for(i=0;i<N;i++)

          sum=sum+a1[i];

    avg=(float)sum/N;

    cout<<endl<<"Average of all The elements is "<<avg;

return 0;

}

Maximum Element of an Array

#include <iostream.h>

#define N 3

int main()

{
    int a1[N];

    int max=0;

    int i;

    cout<<"Enter Elements of  Array";

    for(i=0;i<N;i++)

        cin>>a1[i];

     // Now we will find Max element

    for(i=0;i<N;i++)

          if(max<a1[i])

           max=a1[i];

    cout<<endl<<"Max elements is "<<max;

    cin>>i;

return 0;

}
Minimum Element of an Array

#include <iostream.h>
#define N 3
int main()
{
    int a1[N];
    int min=9999;
    int i;
    cout<<"Enter Elements of  Array";
    for(i=0;i<N;i++)
        cin>>a1[i];
     // Now we will find Min element
    for(i=0;i<N;i++)
          if(min>a1[i])
           min=a1[i];;
    cout<<endl<<"Max elements is "<<min;
 
return 0;
}

 

Linear Search

Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you can try to know if one of the members holds a particular value you are looking for. Here is an example:

#include <iostream.h>

int main()

{
    // Declare the members of the array

    int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};

    int find;

    int i, m = 8;

    cout << "Enter a number to search: ";

    cin >> find;

    for (i = 0;i<m; ++i)

      if(numbers[i]==find)

            cout << find << "Found" << endl;

// Find whether the number typed is a member of the array

    if (i == m)

        cout << find << " Not Found"<< endl;

    return 0;

}

This would produce:

Enter a number to search: 44

44 Found

Counting vowels,consonants, digits, white space and total number of characters in a String

#include<iostream.h>
int main(){
    char line[150];
    int i,v,c,ch,d,s;
    v=c=ch=d=s=0;
    cout<<"Enter a line of string:\n";
    gets(line);
    for(i=0;line[i]!='\0';++i)
        if(line[i]=='a'||line[i]=='e'||line[i]=='i'
           ||line[i]=='o'||line[i]=='u')
            ++v;
     else if(line[i]>='a'&&line[i]<='z')
            ++c;
     else if(line[i]>='0'&&c<='9')
            ++d;
     else if (line[i]==' ')
            ++s;
    cout<<"Total vowels: "<<v;
    cout<<"\nTotal consonants: "<<c;
    cout<<"\nTotal digits: "<<d;
    cout<<"\nTotal white spaces: "<<s;
    cout<<"\nTotal characters: "<<i;
    return 0;
}

C++ program to reverse string without using strrev library function 

#include<iostream.h>
#include<string.h>
void Reverse(char str[]);
int main(){
    char str[100];
    cout<<"Enter a string to reverse: ";
    gets(str);
    Reverse(str);
    cout<<"String after reversing: ";
    puts(str);
 return 0;
}
void Reverse(char str[]){
    int i,j;
    char temp[100];
    for(i=strlen(str),j=0;i!=0;--i,++j){
        temp[j]=str[i];
    }
    temp[j]='\0';
    strcpy(str,temp);
}

scroll back to top