c-sharp
  1. c-sharp-program-to-find-largest-element-in-an-array

Program to Find Largest Element in an Array - (C# Basic Programs)

Finding the largest element in an array is a common programming task. In this tutorial, we will discuss a C# program to find the largest element in an array.

Syntax

The syntax for finding the largest element in an array in C# is as follows:

// Initialize an array
int[] arr = { 5, 10, 3, 8, 12 };

// Initialize a variable to store the largest element
int largest = arr[0];

// Iterate through the array to find the largest element
for (int i = 1; i < arr.Length; i++)
{
    if (arr[i] > largest)
    {
        largest = arr[i];
    }
}

// Print the largest element
Console.WriteLine("The largest element in the array is: " + largest);

Example

using System;

public class Program
{
    public static void Main()
    {
        // Initialize an array
        int[] arr = { 5, 10, 3, 8, 12 };

        // Initialize a variable to store the largest element
        int largest = arr[0];

        // Iterate through the array to find the largest element
        for (int i = 1; i < arr.Length; i++)
        {
            if (arr[i] > largest)
            {
                largest = arr[i];
            }
        }

        // Print the largest element
        Console.WriteLine("The largest element in the array is: " + largest);
    }
}

Output:

The largest element in the array is: 12

Explanation

The program first initializes an array of integers with five elements, then initializes a variable largest to be equal to the first element in the array. Then, the program iterates through each element in the array starting from the second element, comparing each element to the largest variable. If the current element is greater than largest, largest is set to the value of the current element. After iterating through the entire array, the largest element is printed to the console.

Use

Finding the largest element in an array is a common task in many programming tasks, such as sorting algorithms, searching algorithms, and data analysis. Understanding how to find the largest element in an array is an essential skill for any programmer.

Summary

In this tutorial, we discussed a C# program to find the largest element in an array. We covered the syntax, example, explanation, use, and the practical importance of this program. By understanding and practicing this program, you can develop the skills necessary to build more complex algorithms and applications.

Published on: