Statement problem in loop

I'm supposed to write a program that checks whenever the number the user inputs (m) exists in the array and outputs its position (a[0] would be in "0"). If m is not in the array I need to cout "m is not in the array".

Problem is that I don't know how to implement the cout verse without it getting repeated in the loop or appearing in the cout even when m exists.

Would appreciate any help, please excuse for my bad English.
(I'm not supposed to use any version newer than 98)

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
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int m, i;
    cin >> m;

    double a[m];

    for (i = 0; i < m; i++)
    {
        cin >> a[i];
    }

    for (i = m-1; i > -1; i--)
    {
        if (a[i] == 7)
        {
            cout << i << " ";
        }
    }

    cout << m << " is not in the array";
    return 0;
}
Last edited on
Note that double a[m];, with m not being a constant known at compile time, is wrong. Some compilers let you create a variable array on the stack like that, but they shouldn't. It's incorrect C++.

Below is some simple code. It could be less simple, but this is very simple to make it easy to understand. It uses a boolean to keep track of the value existing in the array or not, and another value to keep track of where in the array.

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
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int m, i;
    cin >> m;

    double* a = new double[m]; // this is the correct way to create an array in C++ when
                               // you don't know its size when you write the code

    for (i = 0; i < m; i++)
    {
        cin >> a[i];
    }

    bool value_exists_in_array = false;
    int element_containing_value = -1;
    for (i = 0; i<m; i++)
    {
        if (a[i] == 7)
        {
            value_exists_in_array = true;
            element_containing_value = i;
        }
    }

  if (value_exists_in_array)
  {
     cout << "Value exists, location: " << element_containing_value;
  }
  else
  {
    cout << m << " is not in the array";
  }
  delete[] a;
    return 0;
}


Since you're searching for an int value, I'd advise you have an array of int rather than an array of double. You're asking for trouble comparing int and double values.
Last edited on
@repeater Thank you so much, I got my code worked :)
Topic archived. No new replies allowed.