Thread: New to C, Array Help

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    2

    New to C, Array Help

    I'm trying to put what i've learned into a little program that calculates batting average.

    I want to store the batting averages of the players in an array and printf the best average at the end by name for example Dennis Ritchie had best batting average at .600.

    I'm having trouble understanding how and what type of array to use.

    Looking for a little guidance, also if I could have done something smarter or easier please let me know, much appreciated.

    Code:
    
    int main(int argc, const char * argv[])
    {
        char playerName[20];
        int totalPlayers, atBats, totalHits, x;
        float battingAvg;
        
        // Get total number of batters
        printf("How many batters?\n");
        scanf(" %i", &totalPlayers);
        
        // Check averages of all batters
        for ( x = 0; x < totalPlayers; x++ )
        {
            printf("Players name?\n");
            scanf(" %s", *&playerName);
            // Total at bats
            printf("at bats?\n");
            scanf(" %i", &atBats);
            // Total hits
            printf("hits?\n");
            scanf(" %i", &totalHits);
            // Hits divided by at bats = bAvg
            battingAvg = totalHits / (float)atBats;
            printf ("%s batting average is %.3f\n\n", playerName, battingAvg);
        }
        return 0;
    }

  2. #2
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    Do you have to use arrays here? It seems like you need at least 2 or 3 pieces of data per each "player".

    Using arrays you would need 2-3 arrays and maintain each one in parallel for each piece of data per player.

    The ideal solution would be to use structures. Then you could represent a player like this:
    Code:
    struct player_info {
        char name[20];
        long atbats;
        long hits;
        double battingAvg;
    };
    Then you just need 1 array of "players":
    Code:
    struct player_info players[NUM_PLAYERS];
    And you can manage your data in a unified manner, still using simple array semantics, with a single array.

  3. #3
    Registered User
    Join Date
    Apr 2014
    Posts
    2
    Thanks nonpuz! I'll have a look at it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 07-31-2013, 12:15 AM
  2. Replies: 2
    Last Post: 03-20-2012, 08:41 AM
  3. Replies: 9
    Last Post: 08-23-2010, 02:31 PM
  4. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  5. Replies: 1
    Last Post: 04-25-2006, 12:14 AM