I need help in C Given nA and a 0 a 1 a nA 1 with the elem
I need help in C++
Given nA and a [0], a [1], …, a [nA – 1], with the elements a [j] in nondecreasing order (a [0] <= a [1] <= … <= a [nA-1]), give a segment of code that will copy the ”unique” (or “distinct” or “different”) elements in a into a new array b, “squeezing out the duplicates,” and will set nB equal to the number of elements copied into b.
That is, if nA=5, a[0]=0.0, a [1]=0.0, a[2]=1.2, a[3]=2.3, and a [4] =2.3, then after execution of the code the contents should be b[0] =0.0, b[1] =1.2 , and b[2] = 2.3, and nB=3. The duplicate elements (the second value of 0.0 and the second value of 2.3) have been eliminated from the array.
Note: You may assume both arrays are of type double. This is only an example. Your code must be general and must not contain any “magic number”.
Solution
//this method has been tested on gcc compiler
//start of code
#include <iostream>
using namespace std;
int main() {
int nA; //variable to store size of array a
cout<<\"Enter size of array A \"<<endl; //asking user to enter the size of array a
cin>>nA;
double a[nA]; //initialize double array a of size nA
cout<<\"Enter elements of Array A \"<<endl; //asking user to enter elements of array
for(int i=0;i<nA;i++)
cin>>a[i];
double b[nA]; //initialize double array b of size nA
int index=0; //variable to keep track of unique elements of array A
for(int i=0;i<nA;i++) //loop till size of array a
{
if(a[i]!=a[i+1]) //as array a is sorted alternate elements must be different,than store that //element in array b
{b[index]=a[i];
index++;
}
}
int nB=index; //set size of array b that is nB=index
cout<<endl<<\"Unique elements of array b i.e after “squeezing out the duplicates,:\"<<endl;
for(int i=0;i<nB;i++) //print elements of array B “squeezing out the duplicates,” from array a
cout<<b[i]<<\" \";
return 0;
}
//end of code
**********OUTPUT*******
Enter size of array A
5
Enter elements of Array A
0.0 0.0 1.2 2.3 2.3
Unique elements of array b i.e after “squeezing out the duplicates,:
0 1.2 2.3
**********OUTPUT*******
Please let me know in case of any doubt,Thanks.
![I need help in C++ Given nA and a [0], a [1], …, a [nA – 1], with the elements a [j] in nondecreasing order (a [0] <= a [1] <= … <= a [nA-1]), give a s I need help in C++ Given nA and a [0], a [1], …, a [nA – 1], with the elements a [j] in nondecreasing order (a [0] <= a [1] <= … <= a [nA-1]), give a s](/WebImages/3/i-need-help-in-c-given-na-and-a-0-a-1-a-na-1-with-the-elem-975458-1761500314-0.webp)