Functions -return maximum

This is a discussion on Functions -return maximum within the C Programming forums, part of the General Programming Boards category; I have been working on this program and am getting nowhere fast. The program returns the maximum value as 0 ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    7

    Question Functions -return maximum

    I have been working on this program and am getting nowhere fast. The program returns the maximum value as 0 each time. At this point I am lost and have probably done more damage than good.
    The program should ask the user to enter 20 integers and return the largest number. I would greatly appreciate any help.

    Code:
    #include <stdio.h>
    
    int Max_Num(int[]); /* Function prototype*/
    main()
    {
    	
    		int num[21];
    		int number;
    		int max;
    		
    		printf("\nPlease enter 20 numbers.\n\n");
    		for (number = 0; number < 20; ++number)
    		{
    		printf("\nEnter the number for %d:", number +1);
    		scanf("%d", &num[number]);
    		}
    		
    		max = Max_Num(num);
    		printf("\nThe max interger was %d", num     [max]);
    		return 0;
    		}
    		
    /* Function Header*/
    		int Max_Num(int num[])
    		{
    		int temp;
    		int max = 0;
    		for (temp = 0; temp <=20; ++temp)
    		{
    		if (max < num[temp])
    		   max = num[temp];
    		}
    		return max;
    		}

  2. #2
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Change two lines:

    >> printf("\nThe max interger was %d", num [max]);
    printf("\nThe max interger was %d", max);

    >> for (temp = 0; temp <=20; ++temp)
    for (temp = 0; temp < 20; ++temp)

    num[20] would go out of bounds
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How can I make this code more elegant?
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2009, 08:55 AM
  2. DirectInput help
    By Muphin in forum Game Programming
    Replies: 2
    Last Post: 09-10-2005, 11:52 AM
  3. Replies: 4
    Last Post: 11-23-2003, 06:15 AM
  4. OpenGL and Windows
    By sean345 in forum Game Programming
    Replies: 5
    Last Post: 06-24-2002, 10:14 PM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 11:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21