简体   繁体   中英

Importing array elements greater than k into another array, C++

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];
}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM