Built in functions in array -part2

 This post contains two built in functions std::accumulate() and std::find().

3. std::accumulate():

              This function is used to find the sum of all the elements in the array.

C++ Program:

#include <iostream>

#include <numeric>

using namespace std;

int main() {

int i,a[10],sum=0,n;

cout<<"Enter the n value:"<<endl;

    cin>>n;

    cout<<"Enter the array elements:"<<endl;

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

    {

    cin>>a[i];

    }

    cout<<"The original array is:"<<endl;

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

    {

    cout<<a[i]<<endl;

    }

    sum = std::accumulate(a, a + n, 0);

    cout<<"the sum of all the elements are:"<<sum<<endl;

    return 0;

}

Output:

Enter the n value:

5

Enter the array elements:

12

34

6

27

89

The original array is:

12

34

6

27

89

the sum of all the elements are:168

4. std::find()

              This built in function is used to find an element in the array.

C++ Program:

#include <iostream>

#include <numeric>

#include <algorithm>

using namespace std;

int main() {

int i,a[10],sum=0,n,x;

cout<<"Enter the n value:"<<endl;

    cin>>n;

    cout<<"Enter the array elements:"<<endl;

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

    {

    cin>>a[i];

    }

    cout<<"Enter the data to search:"<<endl;

    cin>>x;

    cout<<"The original array is:"<<endl;

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

    {

    cout<<a[i]<<endl;

    }

   auto it = std::find(a, a + n,x);

   if (x>0)

   {

       cout<<" The element is found"<<endl;

   }

   else {

         cout<<" The element is not found"<<endl;

   }

   return 0;

}

Output:

Enter the n value:

5

Enter the array elements:

12

45

23

67

4

Enter the data to search:

23

The original array is:

12

45

23

67

4

 The element is found

These are the built in functions in array operations. Remaining functions are explained in next post. Hope, the above code is useful to you. Keep coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.