C Online Compiler
Example: Multiple-Player Time Comparison in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Multiple-Player Time Comparison #include <stdio.h> #include <string.h> // Required for strcpy // Structure to hold player name and time struct Player { char name[50]; float time; }; int main() { int numPlayers, i; // Step 1: Get the number of players from the user printf("Enter the number of players: "); scanf("%d", &numPlayers); // Clear the input buffer after scanf for integer while (getchar() != '\n'); // Step 2: Declare an array of Player structures struct Player players[numPlayers]; // C99 feature: Variable Length Array // Initialize variables for tracking the winner float minTime = -1.0; // Use a value that will always be greater than any valid time char winnerName[50]; // Step 3: Loop through each player to get their data for (i = 0; i < numPlayers; i++) { printf("\nEnter details for Player %d:\n", i + 1); printf("Enter player name: "); fgets(players[i].name, sizeof(players[i].name), stdin); // Remove trailing newline character from fgets players[i].name[strcspn(players[i].name, "\n")] = 0; printf("Enter player time (in seconds): "); scanf("%f", &players[i].time); while (getchar() != '\n'); // Clear buffer for next fgets // Step 4: Compare current player's time with the minimum time found so far if (minTime == -1.0 || players[i].time < minTime) { minTime = players[i].time; strcpy(winnerName, players[i].name); } } // Step 5: Print the winner printf("\n--- Race Results ---\n"); if (numPlayers > 0) { printf("The winner is %s with a time of %.2f seconds!\n", winnerName, minTime); } else { printf("No players entered to determine a winner.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS