Thread: Finding largest element in array

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    153

    Finding largest element in array

    Hey everyone,
    So I'm doing this programming exercise to make an array of ints that changes in size each time the prog is run. So, I'm supposed to create a function that goes through the final array and plucks out the largest number and the index of that number...here's what I came up with...although it seems bulky...I was just wondering if there was a better way to go about this than what I did here:

    Code:
    int maxint(int bunch[], int count)
    {
    	int i, largest = 0;
    	for (i = 0; i < count; i++)
    	{
    		if (largest < bunch[i])
    			largest = bunch[i];
    	}
    
    	for (i = 0; i < count; i++)
    	{
    		if (largest == bunch[i])
    			return i;
    	}
    }
    I felt like the second for loop was a bit overkill, but I couldnt figure out a way to combine the for loops...this is just a question about various solutions to the same problem. I think it would be cool to see other thought processes in action...
    peace, Chap

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    i think your first loop is all you need to find the largest value in an array.

    suggestion:
    You may want to consider saving the index of the largest element as well (this can be done at the same time whilst iterating through your first loop).
    Last edited by The Brain; 04-12-2005 at 08:54 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    You could use std::max_element.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Replies: 4
    Last Post: 01-05-2008, 11:30 PM
  3. Absolute value of each element in a given array
    By DriftinSW20 in forum C Programming
    Replies: 9
    Last Post: 11-15-2007, 04:08 PM
  4. How to return the last element of an array?
    By BuezaWebDev in forum C Programming
    Replies: 20
    Last Post: 03-26-2005, 10:57 AM
  5. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM