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)
#include <iostream>
#include <iomanip>
usingnamespace 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;
}
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.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int m, i;
cin >> m;
double* a = newdouble[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.