Sunday, August 2, 2009

C++Write the prototype and definition of the function hasnegative() which accepts an integer array and its siz

I'm can't finish in time without help . Write the prototype and definition of the function hasnegative() which accepts an integer array and its size and returns true if any array element is %26lt; 0, otherwise it returns false. Test this function in a simple program with a 5-element array entered by the user.





I only got started on this, I know it's easy to most, but programming is my sworn enemy!








int x[];








for (int k=1; k%26lt;=10; k++)


{


if (x[k] %26lt; 0)


return 1;


else


return 0;


}

C++Write the prototype and definition of the function hasnegative() which accepts an integer array and its siz
When I was first learning C++, I had trouble with pointers too. Here's a working version.





PROTOTYPE = bool hasnegative( int*, int)





FUNCTION:





bool hasnegative( int* array, int size )


{


for (int i = 0; i %26lt; size; i++ )


{


if ( *(array+i) %26lt; 0 ) return true;


else return false;


}


}





Just pass this function the array and it's size. When you pass the array, what is passed is the address of the first element of the array. When an array is declared, it allocates a contiguous number of memory cells (so everything in the array is all grouped together in the one location). Since we have the address of the first element, all we have to do is add 1 to this address to then have the address of the 2nd element. Add 2 and you will have the address of the 3rd element, and etc.





Just loop through it, and access the value at that memory address (using the *), and that's about it.
Reply:Some people have a thing for it, some people don't. Don't worry, it takes some getting use to regardless of what level you start at.





It would usually be best to pass only the array and have the function determine the size of the array. However, lets just say that you trust the user to pass the correct size for the array.





You have your if-statement wrong, you only want to return false if the number is less than 0. Remove the else statement. The else statement forces a return after checking the first position in the array, which in turn ends your loop and function.





At the end of your for-loop (outside the loop), return true. This allows your program to check all the values in the array. If it found a negative one then it would have returned false. If it didn't find one, then you'd reach the end of your function where it would return true.


No comments:

Post a Comment