I have to write a program that will check each value in the array for a negative number then the program must either print "The array has no negative values" or "The array has at least one negative value". We have to use the funcion anynegatives(int a[], int arraysize) This is my code so far.
Any help would be appreciated.

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>

anyNegative(int a[], int arraysize);

int main()

{
	cont int arraysize=5;
	int a[arraysize];
	int i;
	cout<<"Enter "<<arraysize<<" integers: ";
	for (i=0; i=arraysize; i++)
		cin>>a[i];
{
	if( i >=0)
		cout<<"The array has no negative value";
	else
		cout<<"The array has at least one negative value";
}
	
	return 0;
}

Recommended Answers

All 5 Replies

You could simply loop through I guess:

bool anyNegatives(int nums[], int size)
{
   for (int i=0; i<size; ++i)
   {
      if (nums[i] < 0)
      {
          return true;
      }
   }
   return false;
}

Pretty simple. If you encounter one, then you can break.

Hmmm, looks like dee_dee is quite new at this.. are you learning it in school?? Lets fix a few things here... mostly it's correct..

#include <iostream>
using namespace std; // (replaces the prior 3 lines)
// #include <iomanip> // what is this junk? lol

bool anyNegative(int a[], int arraysize);

int main()

{
	const int arraysize=5;
	int a[arraysize];
	int i;
	cout << "Enter " << arraysize << " integers: ";
	for (i=0; i<arraysize; i++)
		cin >> a[i]; // get values
{
	if(anyNegative(a, 5)==false)
		cout << "The array has no negative value\n"; // '\n' is same as endl
	else
		cout << "The array has at least one negative value" << endl;
}
	
	return 0;
}

// using server_crash's method:

bool anyNegative(int a[], int arraysize)
{
   for (int i=0; i<arraysize; i++)
   {
      if (a[i] < 0)
      {
          return true;
      }
   }
   return false;
}

Oh boy! :cheesy: I'm a n00b too.. but catching on, much like dee_dee

Thanks for the help. Yeah i'm a noob. first course in school for C++

Many people would argue that limiting using directives to include only those items in a namespace that will be actually used instead of opening up all of the namespace would be prefered to something like the using namespace std statement. Even more limiting, and therefore more precise, if more onerous in the process of writing the code, is using the namespace name with the scope operator before each instance of something from the namespace, like this:

std::cout << "hello world" << std::endl;

i agree to lerner

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.