Find the Largest Number Among N Numbers

CCBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/variables("Variables") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} c/if_else -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} c/for_loop -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} c/create_files -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} c/user_input -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} c/output -.-> lab-123252{{"Find the Largest Number Among N Numbers"}} end

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.

  1. Navigate to the project directory in the terminal panel:

    cd ~/project
  2. Now, 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".

  3. Name the file main.c and press Enter.

  4. 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;
    }
  5. 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 like printf() and scanf()
  • 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:

  1. Declare variables to store our data
  2. Prompt the user for the number of elements
  3. 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:

  1. Variable Declaration:

    • int n: An integer variable to store how many numbers the user wants to enter
    • float big: A floating-point variable to store the largest number found
  2. 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 in n
    • The & before n is the "address-of" operator, which tells scanf() where to store the input value
  3. 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)
  4. First Number Input:

    • We prompt the user to enter the first number
    • We store this first number in big since, 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:

  1. Iterate through the remaining numbers (from the 2nd to the nth)
  2. Compare each number with our current largest value
  3. 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", &current);

        // 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:

  1. For Loop:

    • We start from i = 2 because we've already processed the first element
    • We continue until we've processed n elements
    • For each iteration, we increment i by 1
  2. Process Each Number:

    • We declare a new variable current to store each input number
    • We prompt the user to enter the current element
    • We read the input using scanf()
  3. Finding the Maximum:

    • We compare the current input current with our current largest big
    • If current is larger, we update big to store this new largest value
    • If not, we leave big unchanged and move to the next input
  4. Display Result:

    • After processing all inputs, we display the largest number found
    • The %.2f format specifier displays the floating-point number with 2 decimal places

This implementation follows a common pattern for finding the maximum value in a sequence:

  1. Initialize the maximum with the first value
  2. Iterate through the remaining values
  3. Update the maximum whenever we find a larger value
  4. 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.

  1. To compile the program, run the following command in the terminal:

    gcc ~/project/main.c -o ~/project/main

    This command invokes the GNU C Compiler (gcc) to compile our source file main.c and create an executable file named main. The -o flag specifies the output filename.

  2. If there are no errors in your code, the command will execute without any output. This means your program compiled successfully.

  3. 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
  4. Once you've successfully compiled the program, run it using:

    ~/project/main
  5. Test 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.9

    Expected output:

    The largest of the 5 numbers is 25.80
  6. Try 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.7

    Expected output:

    The largest of the 3 numbers is -2.30
  7. Also 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.0

    Expected 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:

  1. Problem Understanding: We identified the need to process a collection of numbers and determine which one is the largest.

  2. Program Structure: We created a well-structured C program with proper includes, variable declarations, and a logical flow.

  3. User Input Handling: We implemented code to get input from users, including validation to ensure proper data.

  4. 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
  5. 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", &current);

        // 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.