Please answer this question given n and a 0 a 1 an1 give
Please answer this question.
given n and a [0], a [1] , ..., a[n-1] , give a segment of c++ code that will \"squeeze out the zeroes in-place\". That is, if n=10 and the contents of a [ j ], j = 0 to n-1 are initially: 0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0 then after execution of the code the contents should be n = 4, a [ 0 ] = 1.2, a [1] = 2.3, a [2] = 9.7 , and a [ 3 ]=5.6.
Note:
(The contents of a [ 4 ] through a [9 ] can be anything.)
This is only an example. Your code must be general and must not contain any \"magic numbers\".
Solution
//this code has been tested on gcc compiler
#include <iostream>
using namespace std;
int main()
{int n=10; //taking n=10,as given in the question
float a[n]={0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0}; //initializing float array a[n] with the //given sets of inputs in the question
float b[n]; //creating an another array for copying non-zero item //of array a
int j=0; //index for storing total no.of non zero items in array a
for(int i=0;i<n;i++) //loop till the size of array a
{
if(a[i] != 0.0) //if element is non-zero
{
b[j]=a[i]; //copy that element in array b
j++; //increase the index of j
}
}
for(int k=0;k<j;k++)
a[k]=b[k]; //place the non-zero element of array a in array a itself
cout<<endl<<\"n = \"<<j<<\", \"; //printing in the given format
for(int i=0;i<j;i++)
cout<<\"a[\"<<i<<\"] = \"<<a[i]<<\", \"; //printing non-zero elements with the index
return 0;
}
//end of code
***********OUTPUT**************
n = 4, a[0] = 1.2, a[1] = 2.3, a[2] = 9.7, a[3] = 5.6.
***********OUTPUT**************
Please let me know in case of any doubt,Thanks
![Please answer this question. given n and a [0], a [1] , ..., a[n-1] , give a segment of c++ code that will \ Please answer this question. given n and a [0], a [1] , ..., a[n-1] , give a segment of c++ code that will \](/WebImages/31/please-answer-this-question-given-n-and-a-0-a-1-an1-give-1090592-1761574189-0.webp)