Code a program in C that prints a list of levels in a game a
Code a program in C that prints a list of levels in a game, along with a count of how many players are at each level. The level will be determined by the amount of health points, using this guide:
Level
Points
Level 1
0 – 9
Level 2
10 – 19
Level 3
20 – 29
Level 4
30 – 39
Level 5
40 – 49
Level 6
Anything 50 or over
Player points are inputted by the user. Your program must use a sentinel-controlled loop to process the data typed by the user, until the user types -1.
After all the data has been entered, display the final counts in a nicely-formatted chart.
Requirements
The number of players at each level is to be stored in an array. So the first element in the array stores the count for Level 1, the second element in the array stores the count for Level 2, etc.
You must use a function called updateLevel to update the count for a level. This function needs two arguments: the points for a player (input argument) and the array (output argument – but remember, it’s an array). Within the function, use a selection statement to determine which element of the array should be incremented.
You must use a function called displayLevels to display the contents of the array after all the data has been entered. This function needs one argument (the array). Line up the output neatly. You must use a loop in this function to display the output.
The results must line up at the decimal point.
| Level | Points |
| Level 1 | 0 – 9 |
| Level 2 | 10 – 19 |
| Level 3 | 20 – 29 |
| Level 4 | 30 – 39 |
| Level 5 | 40 – 49 |
| Level 6 | Anything 50 or over |
Solution
Following is the required c code :
#include <stdio.h>
void updateLevel( int points, int* array ){
int levelIs = 0;
if( points >= 0 && points <= 9){ levelIs = 1; }
if( points >= 10 && points <= 19){ levelIs = 2; }
if( points >= 20 && points <= 29){ levelIs = 3; }
if( points >= 30 && points <= 39){ levelIs = 4; }
if( points >= 40 && points <= 49){ levelIs = 5; }
if( points >= 50 ){ levelIs = 6; }
if( levelIs == 0 ){ return; } //wrong input
array[ levelIs - 1 ]++;
return;
}
void displayLevels( int* array ){
int index = 0;
for(; index < 6; index++ ){
printf(\"Level %d : %d\ \", index+1, array[index] );
}
}
int main(){
int array[6]; //as levels are from level 1 to 6, total 6 elements only
//iniitialize array with zeros
int index = 0;
for( ; index < 6; index++ ){
array[index] = 0;
}
int input;
printf(\"Enter health points: \");
scanf(\"%d\",&input);
while(input != -1 ){
//got input
updateLevel( input, array );
printf(\"Enter health points: \");
scanf(\"%d\",&input);
}
displayLevels( array );
return 0;
}

