array

hello im trying to track how many the user will input 10 or greater than
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
    int a[9],b,c=0;
    for(b = 0; b < 10; b++){
        cin>>a[b];
        if ( a[b] >= 10){
            c++;
        }
    }
    cout<<c;
}

output:
2
2
2
2
2
2
2
2
2
2
2 // this should be 0

Last edited on
a[9], but b<10. That is an out of range error, i.e. undefined behaviour.

However, why does the program have any array at all?
i did it because array starts at 0. so 0,1,2,3,4,5,6,7,8,9 = 10
and b < 10 = 10 also

this is the problem
Write a program that asks the user to type 10 integers of an array. The program must compute and write how many integers are greater than or equal to 10.
Array a[9] has only 9 elements: 0..8
i see i see.
i forgot. lol thats why i cant figure it out.
thank you.
also can you figure out what is better.
my code or this one?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
int main ()
{
 int N = 10;
    int t[N], i=0, V;
    for (i = 0; i < N; i++)
    {
        cout << "Type an integer: ";
        cin >> t[i];
    }
 
    cout << "Type the value of V: ";
    cin >> V;
    for (i = 0; i < N; i++)
    {
        if (t[i] == V)
        {
          cout << "V is in the array" << endl;
          return 0;
        }
    }
    cout << "V is not in the array" << endl;
}
Can't say which is better. They don't do the same thing.
@AbstractionAnon
oops sorry.
i mean my code or this one

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace std;
 
#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[]);
 
int testFunc(int array[]);
 
void inputFunc(int array[]);
 
int main(int argc, char* argv[])
{  int array[X];
 
   inputFunc(array);
 
   outputFunc(array);
 
   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[])
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }
}
 
int testFunc(int array[])
{  int count = 0;
 
   for(int i = 0; i < X; ++i)
      if(array[i] >= 10)
         ++count;
 
   return count;
}
 
void outputFunc(int array[])
{  cout << "\n\tYou entered " << testFunc(array) << " integers greater than or equal to"
        << " 10.\n" << endl;
}
Topic archived. No new replies allowed.