Reputation: 3
How do I import A[n] array elements greater than k (in this case, the first element of the array A[n]), and print them? This doesn't work, can you explain me why?
#include <iostream>
using namespace std;
main() {
int a[100], b[100], n, k, i=0;
cin>>n;
for (i; i<n; i++)
cin>>a[i];
i=0;
k=a[0];
for (i; i<n; i++) {
if (a[i]>k)
b[i]=a[i];
}
i=0;
for (i; i<n; i++)
cout<<b[i];
}
Upvotes: 0
Views: 67
Reputation: 80
The reason your output of array b won't work perfectly is because not all elements of array b has a value stored in it. For all the values of i for which a[i]<=k, b[i] will have a value 0 or a garbage value (dependent on the compiler).
In order to avoid it you should write your code as:
#include<iostream>
using namespace std;
main() {
int a[100], b[100], n, k, i=0;
cin>>n;
for (i; i<n; i++)
cin>>a[i];
i=0;
k=a[0];
int j=0; //another variable j for keeping track of array b
for (i; i<n; i++) {
if (a[i]>k) {
b[j]=a[i];
j++;
}
}
i=0;
for (i; i<j; i++) //Run the value of i from i=0 to i=j
cout<<b[i];
}
Upvotes: 0