C/C++ Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingC/C++ Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old November 10th, 2009, 01:13 PM
Sherina Sherina is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Posts: 11 Sherina User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 29 m 57 sec
Reputation Power: 0
Function for finding highest/lowest value in an array

I'm trying to make a function that finds the highest number in an array but I keep getting errors about having too few arguments.

Code:
int highGrade(int h[], int const size) 
{	 	 	
         int max = 0; 		
         h = 0; 	  	

        for(int i = 0; i < size; ++i) 	
       { 	 	
        if(h[i] > max) 		
        max = h[i]; 		 	
      } 	
 	
     return max; 
}

int main ()
{

	ifstream myfile("a5.txt");
	
	string classGrades;
	int length, i, highest;
	float average;
	int* grades;
	
	
	
	
	if (myfile.is_open())
	{
	
			myfile.seekg (0, ios::end);
			length = myfile.tellg();
			myfile.seekg (0, ios::beg);
			grades = new int [length];
				
		myfile>>classGrades;
		
		while (!myfile.eof()) 
		{
			grades[i] = atoi (classGrades.c_str());
			average = Avg(grades[i]);
			highest = highGrade(grades[i]);
			i++;
			
			
			
			
			myfile>>classGrades;
						

		}
					cout<<highest<<endl;
					cout<<fixed<<setprecision(2)<<average<<endl;
					cout<<grades[1]<<endl;
		myfile.close();
		
	}
	
	else
	
		cout<<"Error: File 'a5.txt' Not Found."<<endl;
	
	

	return 0;
}

Reply With Quote
  #2  
Old November 11th, 2009, 04:32 AM
MaHuJa's Avatar
MaHuJa MaHuJa is offline
Contributing User
Click here for more information.
 
Join Date: Dec 2007
Posts: 990 MaHuJa User rank is Private First Class (20 - 50 Reputation Level)MaHuJa User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 1 Week 15 h 32 m 39 sec
Reputation Power: 3
Send a message via Skype to MaHuJa Send a message via XFire to MaHuJa
Quote:
Originally Posted by Sherina
errors about having too few arguments.
int highGrade(int h[], int const size)
highest = highGrade(grades[ i ]);

Of course you get that error.

The correct syntax for that function call is highGrade(grades,i);. I also strongly suggest you move that call to somewhere more appropriate (no reason to do it for every value read).

In your code, you fail to initialize i. As such, it can contain any value. Your grades[ i ]= can then be writing to anywhere in memory. Hope it crashes rather than wipe your harddrive

Also, I would suggest you use vectors rather than array/length pairs, especially coupled with the incredibly naive array allocation method.

Using the standard library where possible, (instead of writing the supporting functions myself, likely adding bugs in doing so) and being functionally identical to your program (just without the bugs),
cpp Code:
Original - cpp Code
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <fstream>
  4. #include <string>
  5. #include <vector>
  6. #include <algorithm>  // max_element
  7. #include <numeric> // accumulate (aka sum)
  8.  
  9. using namespace std;
  10.  
  11. int main ()
  12. {
  13.     ifstream myfile("a5.txt");
  14.     vector<int> grades;
  15.  
  16.     if (myfile.is_open())
  17.     {
  18.         // Not changing the input method (read to string, atoi) because there is some input
  19.         // it can accept (it will discard trailing letters, give 0 for words that start with letters)
  20.         // that the usual method would not.
  21.         string classGrades;
  22.         myfile>>classGrades;
  23.         while (myfile) // see http://www.cppreference.com/wiki/io/eof
  24.         {
  25.             grades.push_back(atoi (classGrades.c_str()));
  26.             myfile>>classGrades;
  27.         }
  28.         cout<< *max_element(grades.begin(),grades.end()) <<endl; // returns iterator, prefix * to get the value itself
  29.         float avg = accumulate(grades.begin(), grades.end(),0);
  30.         avg /= grades.size();
  31.         cout<<fixed<<setprecision(2)<<avg<<endl;
  32.         //cout<<grades[1]<<endl; // what was this line meant to do again?
  33.         myfile.close();
  34.     }
  35.     else
  36.         cout<<"Error: File 'a5.txt' Not Found."<<endl;
  37.     return 0;
  38. }
__________________
Quote:
Programming by Coincidence
Fred types in some more code, tries it, and it still seems to work. [Then] the program suddenly stops working. [...] Fred doesn’t know why the code is failing because he didn’t know why it worked in the first place.

Last edited by MaHuJa : November 11th, 2009 at 05:19 AM. Reason: Corrected the usual messageboard [i] formatting cockup

Reply With Quote
  #3  
Old November 11th, 2009, 05:13 PM
Sherina Sherina is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Posts: 11 Sherina User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 29 m 57 sec
Reputation Power: 0
Code:
//cout<<grades[1]<<endl; // what was this line meant to do again?


was just to see if the array worked. I remember learning how vectors were a little better than arrays but I never really understood how to use them properly. Thank you very much.

Reply With Quote
  #4  
Old November 11th, 2009, 05:25 PM
Sherina Sherina is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Posts: 11 Sherina User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 29 m 57 sec
Reputation Power: 0
double post.

Last edited by Sherina : November 11th, 2009 at 06:03 PM. Reason: Double Post

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingC/C++ Help > Function for finding highest/lowest value in an array


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump




 Free IT White Papers!
 
Create the Optimal Architecture for your Critical Applications
Warburton's the largest independently owned bakery in the UK faced a number of difficult challenges in providing the most robust yet efficient IT infrastructure for their organization's success. IBM's services combined with their xSeries servers created the perfect platform for their SAP environment with sufficient flexibility, and did so in very time effective fashion.

Request Your Free Technology Downloads!
 
Five Best Practices for Deploying a Successful Service-Oriented Architecture
This white paper describes the benefits you can expect with SOA, and how IBM can help take your business there.

Request Your Free Technology Downloads!
 
Gartner Magic Quadrant for Application Delivery Controllers
Gartner summarizes its view on Application Delivery Controllers, evaluates strengths and weaknesses of solutions, and provides Magic Quadrant reporting for a quick comparison across all vendors. Learn from Gartner how you can benefit from an all-in-one device like Citrix NetScaler that delivers the highest levels of availability, performance and security.

Request Your Free Technology Downloads!
 
Knowledge is Power
What you don't know can hurt you, and is likely costing you money and increasing your security risks during an era of scarce resources. This white paper proposes six key strategies that enterprise security managers can use to improve their network defense posture.

Request Your Free Technology Downloads!
 
Rationalizing the Multi-Tool Environment
The rationalized multi-tool approach is flexible, scalable and cost effective. It provides the necessary input to the IT service management business processes. It preserves prior investments in monitoring tools, empowers technologists to select the best tools with which to do their jobs, and enhances effective response to incidents.

Request Your Free Technology Downloads!
 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 




© 2003-2010 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
For more Enterprise Application Development news, visit eWeek