In: Computer Science
Write a main function that reads a list of integers from a user, adds to an array using dynamic memory allocation, and then displays the array. The program also displays the the largest element in the integer array.
Requirement: Using pointer notation.
Please do this with C++
Code:
#include<iostream>
using namespace std;
int main()
{
/*Main function*/
int n,i,larg;/*Declaring variables*/
cout<<"Enter no of elements in the array:
";
cin>>n;
/*Reading size of the array from the user*/
int *array=new int(n);
/*declaring the dynamic array*/
cout<<"Enter elements of the
array:"<<endl;
/*Asking user to enter the elements*/
for(i=0;i<n;i++)
{
cin>>*(array+i);
/*Here we read elements formt he
user*/
if(i==0)
{
/*If it is the
first element we make first element as larg*/
larg=*(array+0);
}
else
{
if(larg<*(array+i))
{
/*here we compare larg with the entered
element
if it is larger then we make larg as the new
element*/
larg=*(array+i);
}
}
}
cout<<"\nLargest element is:
"<<larg;
/*Finally we print the largest element of the
array*/
}
Output:
Indentation: