Summary
In this lab, we successfully implemented a C program that finds the largest number among a set of user-provided numbers. Let's review what we accomplished:
-
Problem Understanding: We identified the need to process a collection of numbers and determine which one is the largest.
-
Program Structure: We created a well-structured C program with proper includes, variable declarations, and a logical flow.
-
User Input Handling: We implemented code to get input from users, including validation to ensure proper data.
-
Algorithm Implementation: We used a simple but effective algorithm to find the maximum value:
- Initialize with the first value
- Compare each subsequent value with the current maximum
- Update the maximum when a larger value is found
-
Testing and Execution: We compiled our program and tested it with various inputs to verify it works correctly.
This lab demonstrates fundamental programming concepts that are valuable in many contexts:
- Sequential execution
- Conditional statements
- Looping constructs
- Variable tracking
- Input/output operations
The Complete Code
Here's the complete code we developed in this lab:
#include <stdio.h>
int main() {
// Declare variables
int n; // To store the number of elements
float big; // To store the largest number found
// Prompt the user for the number of elements
printf("Enter the number of elements you wish to find the greatest element of: ");
scanf("%d", &n);
// Check if the input is valid
if (n <= 0) {
printf("Please enter a positive number of elements.\n");
return 1; // Exit with error code
}
// Prompt for the first number and initialize 'big' with it
printf("Enter %d numbers:\n", n);
printf("Enter element 1: ");
scanf("%f", &big);
// Process remaining numbers using a loop
for (int i = 2; i <= n; i++) {
float current; // Variable to store the current number
// Prompt for the current number
printf("Enter element %d: ", i);
scanf("%f", ¤t);
// Compare with the current largest
if (current > big) {
big = current; // Update 'big' if current number is larger
}
}
// Display the result
printf("The largest of the %d numbers is %.2f\n", n, big);
return 0;
}
You can extend this program in several ways:
- Find both the largest and smallest numbers
- Calculate the average of all numbers
- Sort the numbers in ascending or descending order
- Handle more complex data structures like arrays
We hope this lab has helped you understand the basics of C programming and algorithmic thinking. These concepts form the foundation for more advanced programming topics and problem-solving techniques.