Thread: get the largest element from the array and print it

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    1

    Question get the largest element from the array and print it

    can any body help me with this code ..i want to take an array from the user and get the largest element from the array and print it ..but it always gives me zero
    Code:
    #include<stdio.h>
    int a[100],i,m;
    
    int max(int a[])
    {
    
    for(int j=0;j<=5;j++)
    {
    m=a[i];
    if(a[i+1]>a[i])
    m=a[i+1];
    }
    
    return m;
    }
    
    void main()
    {
    printf("enter the array please \n");
    for(i=0;i<=5;i++)
    scanf("%d",&a[i]);
    printf("the max = %d",max(a) );
    }

  2. #2
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    That is not how max() really works; at least the one that I know of is max(a,b) returning the max of the two. One lame approach would be skipping the check/printf() within the for loop but create int nCurrentMax = 0 at the top of main() and then compare each entered value as it is entered like:
    Code:
    if( nCurrentMax < a[i])
    {
         nCurrentMax = a[i];
    }
    Then at the end of main() a printf("Max value entered was %d\n", nCurrentMax); should do the trick. I said this was lame b/c I think there is an STL call that will do the same, not on a basic C-style array but rather on a linked list or vector...

    YMMV
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Why the hell did you hijack someone else's thread??? Grrrr...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Towr of Hanoi move the disc
    By WatchTower in forum C Programming
    Replies: 9
    Last Post: 07-17-2009, 03:48 AM
  2. Replies: 7
    Last Post: 11-25-2008, 01:50 AM
  3. count/display non-repeated element of array
    By azsquall in forum C++ Programming
    Replies: 15
    Last Post: 07-10-2008, 09:42 AM
  4. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM