you have been an integer array A of size N.you need to pfint the number with the value closest to zero.if there are multiple elements print the number with greater value.
#include <iostream>
using namespace std;
int main()
{
//Allocating memory for an array A[N] and entering data
int N;
cout << "enter the size of the array: ";
cin >> N;
int *A = new int[N];
for(int i =0;i<N;i++)
{
cout << "enter " <<i<<" element of the array: ";
cin>>A[i];
}
// Finding the element closest to zero
int elem_index=0;
for(int i =0;i<N;i++)
{
if ((A[i] >= 0 && A[i]<=A[elem_index]) || (A[i]< 0 && A[i]>A[elem_index]))
{
elem_index = i;
}
}
// Outputting the result and freeing the memory of a dynamic array
cout<<"element closest to zero A["<<elem_index<<"]="<<A[elem_index];
delete[] A;
A= nullptr;
return 0;
}
Comments
Leave a comment