| | |
Is my homework Correct :P
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Apr 2009
Posts: 149
Reputation:
Solved Threads: 7
Hello
I have this task below & I need someone to tell me if I have done it correctly. The part where I am not sure is if I am correctly checking if the array is empty.
I have this task below & I need someone to tell me if I have done it correctly. The part where I am not sure is if I am correctly checking if the array is empty.
•
•
•
•
Write a function to find the maximum value in an array of ints a.
int findMax(int a[], int n)
// precondition : a[0..n-1] is an array of ints
// postcondition : returns the maximum value in array or
// INT_MIN if array is empty
Recall that INT_MIN is a predefined constant indicating the minimum value of an integer.
C++ Syntax (Toggle Plain Text)
int findMax(int a[], int n) { /// Homework 2 /// int max = 0; if (n >= 0) { // does this check if the array is empty?? for (int i=0; i<n; i++) { if (a[i] > max) { max = a[i]; } } return max; } else return INT_MIN; // array is empty so return INT_MIN }
Consider what happens if all the numbers in the array are negative. Then the
if(a[i]>max) will never return true. There are two ways you can do this. Either set max to INT_MIN or set max to a[0] and loop from 1 to n then. Another option is set max to a[0] .
![]() |
Similar Threads
- Writing to a text file (Java)
- Help with homework - Days Since Last Birthday (C++)
- C++ Homework #1 (C++)
- a homework on methods, constructors etc (Java)
- 2 ASP Questions (ASP.NET)
Other Threads in the C++ Forum
- Previous Thread: Random Number Function - Change output each call
- Next Thread: logical error____please help me soon
| Thread Tools | Search this Thread |
api application array arrays based beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete desktop developer directshow dll dynamiccharacterarray email encryption error file forms fstream function functions game generator getline graph homeworkhelper iamthwee ifstream input int integer java lib linux list loop looping loops map math matrix memory multiple newbie news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates text tree url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






