C++ code to find largest element in an array.














































C++ code to find largest element in an array.






Description:


This program is to
find largest element of an array.


Algorithm-


1.Make a class
Demo.


2.Take input of
array through class functions in array arr[].


3.Display the
array.


4.Let max=first
element of array


5.for(i less than
elements in array)


a. if(max<arr[i])


set max=arr[i]


6.Print max
element.






Advantages-


1.Code has dynamic
memory allocation of array.


2.Template is used
for array elements.


3.Class
object(Object oriented programming) is implemented.


4.Memory and time
optimized.






Code:






//Headers
#include<iostream>
using namespace std;

template <class T> //template T
class Demo //creating class demo
{

T *arr,max; //declaring *arr and max of type T (private members)
int n;

public:
int i;

Demo() //constructor
{
arr=NULL; //initializing elements and pointer
max=0;
n=0;
}
int validate(int n) //validation function
{
while(n<=0) //till user enters number n greater than 0
{
cout<<"\nPlease enter valid number of elements::";;
cin>>n;
}
}
void input() //function for taking inputs
{
cout<<"\nEnter number of elements::";
cin>>n; //number of elements
n=validate(n); //calling function for validation

arr=new T[n]; //dynamic memeory allocation of an array 'arr'

cout<<"\n\nEnter elements of an array::";
for(i=0;i<n;i++)
{
cout<<"\nElemenet "<<i<<"::";
cin>>arr[i]; //taking array elements as input
}
}

void display() //function to display array
{
cout<<"\nEntered array is::";
for(i=0;i<n;i++)
{ cout<<" "<<arr[i]; }
}
void calc_max() //function to calculate max elemenet in given array
{
max=arr[0]; //det max to first elemenet
for(i=0;i<n;i++)
{
if(max<arr[i]) //compare every element if less then set max to new greater element
max=arr[i];
}
cout<<"\n\nLargest element in array is::"<<max; //print max element
}

~Demo() //Destructor
{
delete[] arr; //deallocate memory
}
};

int main() //main function
{
Demo <int>obj; //creating object obj of class Demo
obj.input(); //taking input
obj.display(); //display the array
obj.calc_max(); //calculate the max element
return 0; //exit
}

















Output:






isha28@ubuntu:~/codes$
g++ max_array.cpp


isha28@ubuntu:~/codes$
./a.out






Enter number of
elements::0






Please enter valid
number of elements::-1






Please enter valid
number of elements::7










Enter elements of an
array::


Elemenet 0::4






Elemenet 1::5






Elemenet 2::2






Elemenet 3::6






Elemenet 4::1






Elemenet 5::7






Elemenet 6::3






Entered array
is:: 4 5 2 6 1 7 3






Largest element in
array is::7

isha28@ubuntu:~/codes$



More Articles of Isha Pardikar:

Name Views Likes
C++ code to find largest element in an array. 118 0

Comments