Skip to content

Instantly share code, notes, and snippets.

@s3f
Created December 29, 2016 22:57
Show Gist options
  • Save s3f/3c883a6370b1037db9e2559c48c564ab to your computer and use it in GitHub Desktop.
Save s3f/3c883a6370b1037db9e2559c48c564ab to your computer and use it in GitHub Desktop.
Chapter 21- Reviewing Arrays created by s3f - https://repl.it/EvIX/7
// Reviewing Arrays
/*
Remember: An array is simply a list of items with a specific name. An array of characters can only have characters. An array of integers can only contain integers and so on
To define an array, you must add brackets after the name and specify the max number of elements you'll put inside the array.
ex: char name[6] = "Italy";
Also remember that an array's numbers start from 0 so forexample:
int vals[5] = {10, 40, 70, 90, 120}
10 = vals}[0]
40 = vals[1]
The following program below keeps track of how many points a player scored in each of 10 basketball games. The first six scores are entered when the array is initialized and then the user is asked for a players scores for games 7 -10. After all the data has been entered, the program loops through the 10 scores to compute the average points per game.
*/
#include <stdio.h>
main()
{
int gameScores[10] = { 12, 5, 21, 15, 32, 10 };
int totalPoints = 0;
int i;
float avg;
// Only need scores for last 4 games so the loop will cover array elements 6-9
for (i = 6; i < 10; i++)
{
printf("What did the player score in game %d ", i + 1);
scanf(" %d", &gameScores[i]);
}
/*
Now that we have all 10 scores, we will now loop through the scores to get total points in order to calculate an average
*/
for (i = 0; i < 10; i++)
{
totalPoints += gameScores[i];
}
// Use a floating point variable for the average
avg = ((float)totalPoints / 10);
printf("\n\nThe player's scoring average is %.1f.\n", avg);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment