Problem Statement:
Write a function that returns the largest number in an array.
Approach:
- Initialize a variable
largest
to-Infinity
. - Loop through the array.
- If the current element is greater than
largest
, updatelargest
. - Return
largest
after the loop ends.
Example:
Input: arr = [2, -6, 4, 8, 1, -9]
Output:8
Time & Space Complexity:
Time Complexity: O(n)
– where n is
the number of elements in the array.
Space Complexity: O(1)
– Only a counter variable is
used.
Visualisation:

function findLargest(arr) {
let largest = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
let arr = [2, -6, 4, 8, 1, -9];
let result = findLargest(arr);
console.log("Result:", result); // Output: 8
def find_largest(arr):
largest = float('-inf')
for num in arr:
if num > largest:
largest = num
return largest
arr = [2, -6, 4, 8, 1, -9]
result = find_largest(arr)
print("Result:", result) # Output: 8
public class Main {
public static int findLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
largest = num;
}
}
return largest;
}
public static void main(String[] args) {
int[] arr = {2, -6, 4, 8, 1, -9};
int result = findLargest(arr);
System.out.println("Result: " + result); // Output: 8
}
}
#include <iostream>
using namespace std;
int findLargest(int arr[], int n) {
int largest = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = findLargest(arr, 6);
cout << "Result: " << result << endl; // Output: 8
return 0;
}
#include <stdio.h>
int findLargest(int arr[], int n) {
int largest = -2147483648; // INT_MIN
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = findLargest(arr, 6);
printf("Result: %d\n", result); // Output: 8
return 0;
}
using System;
class Program
{
static void Main()
{
int[] arr = { 2, -6, 4, 8, 1, -9 };
int largest = FindLargest(arr);
Console.WriteLine("Largest number in the array: " + largest);
}
static int FindLargest(int[] arr)
{
int largest = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
}
return largest;
}
}