Showing posts with label ARRAY. Show all posts
Showing posts with label ARRAY. Show all posts

C++ Dynamic Memory Allocation of Arrays

We have already discussed Dynamic Memory Allocation in C style through malloc, calloc and realloc : C++ Program to illustrate memory allocation with malloc, calloc and realloc .

The static memory allocation of array leads to inefficient use of memory. Moreover, it is statically bounded and can not be allocated on demand at runtime. Some programs require memory to be allocated based on user input. This leads to the need of dynamic memory allocation for arrays.

MEMORY ALLOCATION

In C++, Dynamic Memory Allocation takes place with the help of two operators i.e. new and delete. The general syntax for memory allocation goes as:

pointer = new datatype [ number_of_elements ] 

The above expression is used to allocate a block of elements of type datatype. The number_of_elements is an integer value which denotes the number of elements of the array. A pointer to the beginning of new memory block is returned.

For instance,

int *list;
list = new int [5];

In the above scenario, the system will dynamically allocate memory for 5 integer type elements and return a pointer to the beginning of this block to list.


Once the memory is allocated, list will behave similarly as a static array of 5 integer elements. The elements can be accessed as list[0], list[1], ... list[4].

The dynamic memory allocation takes place from the system heap memory. As we know that the system memory is limited and may exhaust, thus the request for dynamic memory allocation may fail. 

One way to identify whether memory allocation is successful or not is through the use of a special object nothrow defined in the <new> header. 


list = new (nothrow) int [5];

By using nothrow, if the memory allocation fails, a null pointer is returned to the pointer and the program continues its execution.

For instance,

int *list;
list = new (nothrow) int [5];

if( list == nullptr )
{
     // MEASURES IF ALLOCATION FAILS
}

// REST OF CODE

MEMORY DEALLOCATION

After the use of memory, the allocated memory can be freed so that is can be used for further requests of dynamic memory. For this purpose, delete operator is used whose syntax is as follows:

delete [] pointer; 

C++ Program to find pairs in an array with given sum [DEVCPP/GCC]

We intend to find pairs in an array having the sum of its elements equal to the provided number.
For instance, if an array consists of elements {0,2,6,4,8,10} and the provided number is 8, then we must find pairs having sum of its elements as 8 i.e. {0,8} and {2,6}.

PROGRAM

// Program to find pairs in an array having sum equal to a given number

#include <iostream>

using namespace std;

void findPairs(int a[], int n, int sum)
{
      int count=0;

      for(int i=0 ; i<n ; i++)
      {
             for(int j=i+1 ; j<n ; j++)
             {
                     if(a[i]+a[j]==sum)
                     {
                              count++;
                              cout<<"\nPAIR FOUND AT INDICES "<<i<<","<<j;
                     }
             }
       }

       cout<<"\n\nTOTAL PAIRS HAVING SUM AS "<<sum<<" ARE "<<count;
}

int main()
{
       int a[5],sum;

       cout<<"ENTER ARRAY OF ELEMENTS: ";

       for(int i=0 ; i<5 ; i++)
       {
                cin>>a[i];
       }

        cout<<"\nENTER SUM: ";
        cin>>sum;

        findPairs(a,5,sum);
}

OUTPUT

C++ Program to find pairs in an array with given sum

C++ Program to remove duplicate elements from an array [DEVCPP/GCC]

PROGRAM

// Program to remove duplicate elements from an array

#include <iostream>

using namespace std;

int main()
{
        int i,j,k,len=0;

        cout<<"ENTER THE NUMBER OF ELEMENTS: ";
        cin>>len;

        int num[len];

        cout<<"\nENTER ELEMENTS: ";

        for(i=0 ; i<len ; i++)
        {
                   cin>>num[i];
         }

        for(i=0 ; i<len ; i++)
        {
                for(j=i+1 ; j<len ; j++)
                {
                        if(num[i]==num[j])
                        {
                                 for(k=j ; k<len ; k++)
                                 {
                                            num[k]=num[k+1];
                                  }

                                  len--;
                                  j--;
                       }
                }
          }

          cout<<"\nDISTINCT ELEMENTS: ";

          for(i=0 ; i<len ; i++)
          {
                  cout<<num[i]<<" ";
           }

            return 0;
}

OUTPUT

C++ Program to remove duplicate elements from an array with output


C++ Program to add the distinct elements of an array [DEVCPP/GCC]


PROGRAM

//Program to add the distinct elements of an array

# include <iostream>
using namespace std;

int main()
{
int arr[5],i,j,sum=0;
     bool flag;

cout<<"ENTER THE ELEMENTS OF AN ARRAY:\n";
for(i=0;i<5;i++)     // Input an array
{
cin>>arr[i];
}

for(i=0;i<5;i++)
{
flag=true;
for(j=0;j<i;j++)
{
if(arr[i]==arr[j]) //check for uniqueness
{
flag=false;
break;
}
}
if(flag)
{
sum=sum+arr[i]; //summation of distinct elements
}
}

cout<<"SUM IS:"<<sum;
return 0;
}

OUTPUT

C++ Program to add the distinct elements of an array with output

C++ Program to find the second highest element in a given array [DEVCPP/GCC]

INT_MIN

As the name suggests, it refers to the minimum value of integer datatype.

PROGRAM

//Program to find the second highest element in a given array

#include <iostream>

using namespace std;

int main()
{
        int num [10],i,max,SecondMax;
        max=SecondMax=INT_MIN;

// Calculating the highest element of the array
        for(i=0 ; i<10 ; i++)
        {
                cout<<"ENTER "<< i<<" ELEMENT: ";
                cin>>num [i];

                if(num [i]>max)
                {
                        max=num [i];
                }
        }
 
        // Calculating the second highest element
        for(i=0;i<10;i++)
        {
                if(num [i]==max)
                {
                        continue;
                }
                else if(num [i]>SecondMax)
                {
                        SecondMax=num [i];
                 }
        }

        cout<<"\nMAXIMUM ELEMENT IS "<<max;
        cout<<"\nSECOND MAXIMUM ELEMENT IS "<<SecondMax;

        return 0;
}

OUTPUT

C++ Program to find the second highest element in a given array with output


C++ Program to calculate frequency of a character in a given string [DEVCPP/GCC]

FREQUENCY

Frequency of a character in a given string implies no of occurences of that particular character in the given string.

For example:

String:        Techcpp
Character:  c
Frequency: 2


STEPS

1. Initialize count with 0.

2. Input an string and the character whose frequency is to be calculated within the entered string.

3. Initialize index variable i with 0

4. Increment the count if the condition 'ch equals to a[i]' is satisfied.

5. Increment i untill a[i]!='\0'. 

PROGRAM

//Program to calculate the frequency of a character

# include <iostream>

using namespace std;

int main()
{
char a[20],ch;
int i,j,count=0;

cout<<"ENTER THE STRING:\n";
cin.getline(a,20);

cout<<"ENTER THE CHARACTER WHOSE FREQUENCY IS TO BE CALCULATED:\n";
cin>>ch;

for(i=0;a[i]!='\0';i++)
{
if(ch==a[i])
count++;
}

cout<<count;
return 0;
}

OUTPUT

C++ Program to calculate frequency of a character in a given string with output

C++ Program to split an array into two arrays [DEVCPP/GCC]


PROBLEM

We have to split an array into two arrays in an efficient way as described in the image below.


STEPS

1. Input the elements of an array C (which is to be biparted).

2. Initialize the index variable i and j with 0.

3. Assign the value at jth index of array C to ith index of array A and the value at (j+1)th index of array C to ith index of array B.

4. Increment i by 1 and j by 2.

5. Repeat step 3-4 until j<(size of the composite array), Here 8.

PROGRAM

//Program to split an array into two arrays (in an efficient way)

# include<iostream>

using namespace std;

int main()
{

int a[4],b[4],c[8],i,j;
cout<<"ENTER THE ELEMENTS OF COMPOSITE ARRAY:\n";
 
for(i=0; i<8 ;i++)            //Loop for input
{
cout<<"c["<<i<<"]=";
cin>>c[i];
}
cout<<endl;

for(i=0,j=0 ; j<8 ; i++,j+=2)
{
a[i]=c[j];
b[i]=c[j+1];
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY1:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"b["<<i<<"]=";
cout<<b[i]<<endl;
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY2:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<endl;
}

return 0;
}

OUTPUT

C++ Program to split an array into two arrays with output

C++ Program to merge two arrays [DEVCPP/GCC]


//Program to merge two arrays (in an efficient way)

# include<iostream>

using namespace std;

int main()
{
int a[4],b[4],c[8],i,j;

cout<<"ENTER THE ELEMENTS OF ARRAY1:\n";
 
          for(i=0 ; i<4 ; i++)             //Loop to input array a
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
 
cout<<"\nENTER THE ELEMENTS OF ARRAY2:\n";

for(i=0 ; i<4 ; i++)              //Loop to input array b
{
cout<<"b["<<i<<"]=";
cin>>b[i];
}

           for(i=0 , j=0 ; i<4 ; i++ , j=j+2)  //Loop for merging
{
c[j]=a[i];
c[j+1]=b[i];
}

cout<<"\nMERGED ARRAY:\n";

for(i=0 ; i<8 ; i++)
{
cout<<"c["<<i<<"]="<<c[i]<<endl;
}

return 0;
}

C++ Program to merge two arrays with output

C++ Program to reverse a single dimensional array without using another array [DEVCPP/GCC]

PROGRAM

//Program to reverse a single dimensional array without using another array

# include <iostream>

using namespace std;

int main()
{
int a[5],i,sum=0;
 
           cout<<"INPUT THE ARRAY ELEMENTS:\n";
for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}

cout<<"REVERSED ARRAY:\n";
for(i=0;i<2;i++)
{
a[i]=a[i]+a[4-i];
a[4-i]=a[i]-a[4-i];
a[i]=a[i]-a[4-i];
}
 
             for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}

return 0;
}

OUTPUT

C++ Program to reverse a single dimensional array without using another array with output

C++ Program to reverse a single dimensional array using another array [DEVCPP/GCC]

PROGRAM

//Program to reverse a single dimensional array using another array.

# include <iostream>

using namespace std;

int main()
{
int a[5],b[5],i,sum=0;

cout<<"INPUT THE ARRAY ELEMENTS:\n";
for(i=0;i<5;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}

cout<<"\nREVERSED ARRAY:\n";
for(i=0;i<5;i++)
{
b[i]=a[4-i];
cout<<"b["<<i<<"]="<<b[i]<<endl;
}
 
            return 0;
}

OUTPUT

C++ Program to reverse a single dimensional array using another array with output

FIND US ON FACEBOOK!