Introduction
In this lab, we will learn how to write a C program that finds the largest number among a set of user-provided numbers. This is a fundamental programming exercise that teaches several important concepts:
- Taking user input
- Working with loops
- Making comparisons
- Tracking the maximum value through iterations
The algorithm we will implement is straightforward: we will ask the user how many numbers they want to enter, then iterate through each input number. As we process each number, we will compare it with the current largest number we have found so far, updating our "largest" variable when necessary.
By the end of this lab, you will have created a program that can handle any number of inputs and reliably identify the largest value among them.
Creating our Program File
Let's start by creating a new C file for our program. In the WebIDE, we'll create a file named main.c in the project directory.
Navigate to the project directory in the terminal panel:
cd ~/projectNow, in the WebIDE, click on the "New File" button in the Explorer panel on the left side, or right-click in the Explorer panel and select "New File".
Name the file
main.cand press Enter.Let's begin by adding the basic structure of our C program to the newly created file:
#include <stdio.h> int main() { // We will add our code here return 0; }Save the file by pressing Ctrl+S or by selecting File > Save from the menu.
This structure includes:
- The
#include <stdio.h>directive that brings in the Standard Input/Output library, which we need for functions likeprintf()andscanf() - The
main()function, which is the entry point of any C program - A
return 0;statement that indicates successful execution of our program
The stdio.h header file provides functions for input and output operations. The main() function is where our program execution begins, and return 0; signals to the operating system that our program terminated without errors.
Handling User Input
Next, we need to set up our program to interact with the user. We'll need to:
- Declare variables to store our data
- Prompt the user for the number of elements
- Set up the process for receiving the first number
Let's update our code in main.c:
#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);
return 0;
}
Let's understand what we've added:
Variable Declaration:
int n: An integer variable to store how many numbers the user wants to enterfloat big: A floating-point variable to store the largest number found
User Input for Count:
- We use
printf()to display a prompt asking for the number of elements - We use
scanf("%d", &n)to read an integer from the user and store it inn - The
&beforenis the "address-of" operator, which tellsscanf()where to store the input value
- We use
Input Validation:
- We check if the user entered a positive number
- If not, we display an error message and exit the program with return code 1 (indicating error)
First Number Input:
- We prompt the user to enter the first number
- We store this first number in
bigsince, at this point, it's the only (and therefore largest) number we have
When you run this code, it will ask for the number of elements and then for the first element, but it won't do anything with that information yet. In the next step, we'll add the logic to process all numbers and find the largest one.
Finding the Largest Number
Now we'll implement the core logic of our program - finding the largest number among the inputs. We'll use a for loop to:
- Iterate through the remaining numbers (from the 2nd to the nth)
- Compare each number with our current largest value
- Update the largest value if we find a bigger number
Update your main.c file with the following code:
#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;
}
Let's understand the new code we've added:
For Loop:
- We start from
i = 2because we've already processed the first element - We continue until we've processed
nelements - For each iteration, we increment
iby 1
- We start from
Process Each Number:
- We declare a new variable
currentto store each input number - We prompt the user to enter the current element
- We read the input using
scanf()
- We declare a new variable
Finding the Maximum:
- We compare the current input
currentwith our current largestbig - If
currentis larger, we updatebigto store this new largest value - If not, we leave
bigunchanged and move to the next input
- We compare the current input
Display Result:
- After processing all inputs, we display the largest number found
- The
%.2fformat specifier displays the floating-point number with 2 decimal places
This implementation follows a common pattern for finding the maximum value in a sequence:
- Initialize the maximum with the first value
- Iterate through the remaining values
- Update the maximum whenever we find a larger value
- At the end, the variable contains the largest value from the sequence
Compiling and Testing the Program
Now that we have written our complete C program, we need to compile and run it to see if it works correctly.
To compile the program, run the following command in the terminal:
gcc ~/project/main.c -o ~/project/mainThis command invokes the GNU C Compiler (gcc) to compile our source file
main.cand create an executable file namedmain. The-oflag specifies the output filename.If there are no errors in your code, the command will execute without any output. This means your program compiled successfully.
If you see any error messages, carefully read them to understand what went wrong. Common errors include:
- Missing semicolons (
;) - Mismatched braces (
{and}) - Incorrect variable names or types
- Missing or incorrect include statements
- Missing semicolons (
Once you've successfully compiled the program, run it using:
~/project/mainTest your program with different inputs. Here's an example test case:
Input:
Enter the number of elements you wish to find the greatest element of: 5 Enter 5 numbers: Enter element 1: 12.5 Enter element 2: 9.7 Enter element 3: 25.8 Enter element 4: 15.2 Enter element 5: 4.9Expected output:
The largest of the 5 numbers is 25.80Try another test case with negative numbers:
Input:
Enter the number of elements you wish to find the greatest element of: 3 Enter 3 numbers: Enter element 1: -10.5 Enter element 2: -2.3 Enter element 3: -15.7Expected output:
The largest of the 3 numbers is -2.30Also test with a single number:
Input:
Enter the number of elements you wish to find the greatest element of: 1 Enter 1 numbers: Enter element 1: 42.0Expected output:
The largest of the 1 numbers is 42.00
If your program produces the expected outputs for these test cases, congratulations! You have successfully implemented a program to find the largest number among N input numbers.
This process of compiling and testing is an essential part of software development. It allows you to verify that your code works as expected and helps you identify and fix any bugs or issues.
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.



