Second Largest Element in Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Second Largest Element in Array in C: Program to Find Second Maximum

šŸ“‘ On this page:
  • Introduction
  • C Program to Find Second Largest
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • How to find the second largest element in an array
  • How to handle arrays with duplicate elements
  • How to handle arrays with less than 2 elements
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to find the second largest element in an array.

Finding the second largest element is a common programming problem that tests your understanding of array traversal and comparison logic. It is used in many real-world applications, such as:

  • Finding the second highest score in a class
  • Finding the second highest salary in a company
  • Finding the runner-up in a competition
  • Finding the second highest temperature reading

šŸ’” Key Point: To find the second largest element, we keep track of the largest and second largest elements while traversing the array. When we find a new largest, the old largest becomes the second largest.

C Program to Find Second Largest Element in Array

#include <stdio.h>

int main() {
    int n, i;
    int largest, second_largest;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Check if array has at least 2 elements
    if(n < 2) {
        printf("\nArray must have at least 2 elements.\n");
        return 1;
    }
    
    // Declare array
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Initialize largest and second largest
    largest = arr[0];
    second_largest = -1;  // Use -1 or a very small number
    
    // Find second largest
    for(i = 1; i < n; i++) {
        if(arr[i] > largest) {
            second_largest = largest;
            largest = arr[i];
        }
        else if(arr[i] > second_largest && arr[i] != largest) {
            second_largest = arr[i];
        }
    }
    
    // Display result
    if(second_largest == -1) {
        printf("\nNo second largest element found.\n");
    } else {
        printf("\nLargest element: %d\n", largest);
        printf("Second largest element: %d\n", second_largest);
    }
    
    return 0;
}

Sample Output

Enter the number of elements: 6
Enter 6 elements:
50 20 40 10 30 60

Largest element: 60
Second largest element: 50

Example with Duplicate Elements:

Enter the number of elements: 7
Enter 7 elements:
50 50 40 10 30 60 60

Largest element: 60
Second largest element: 50

When All Elements are Same:

Enter the number of elements: 5
Enter 5 elements:
10 10 10 10 10

Largest element: 10
No second largest element found.

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — number of elements
    • int i; — loop counter
    • int largest; — stores the largest element
    • int second_largest; — stores the second largest element
  3. Validate Input: Checks if the array has at least 2 elements. If not, displays an error message.
  4. Initialize Variables:
    • largest = arr[0]; — assumes the first element is the largest
    • second_largest = -1; — initialized to a value that won't conflict
  5. Find Second Largest: The loop traverses from index 1 to n-1:
    • If arr[i] > largest:
      • Old largest becomes second largest
      • New element becomes largest
    • Else If arr[i] > second_largest && arr[i] != largest:
      • Update second largest
      • Skip duplicates of the largest element
  6. Display Result: Prints the largest and second largest elements.
  7. Return: return 0; indicates successful program execution.

šŸ“ Note: The condition arr[i] != largest ensures that duplicate values of the largest element are not considered as the second largest.

Algorithm to Find Second Largest Element

Step-by-step algorithm:

  1. Start
  2. Read the array elements
  3. If n < 2, print "Array must have at least 2 elements" and exit
  4. Set largest = arr[0]
  5. Set second_largest = -1
  6. For i = 1 to n-1:
    • If arr[i] > largest:
      • second_largest = largest
      • largest = arr[i]
    • Else If arr[i] > second_largest && arr[i] != largest:
      • second_largest = arr[i]
  7. If second_largest == -1:
    • Print "No second largest element found"
  8. Else:
    • Print largest and second largest
  9. End

Visual Example

Finding the second largest in the array [50, 20, 40, 10, 30, 60]:

Initialize: largest = 50, second_largest = -1

i=1: arr[1]=20 → 20 < 50 and 20 > -1 → second_largest = 20

i=2: arr[2]=40 → 40 < 50 and 40 > 20 → second_largest = 40

i=3: arr[3]=10 → 10 < 40 → no change

i=4: arr[4]=30 → 30 < 40 → no change

i=5: arr[5]=60 → 60 > 50 → second_largest = 50, largest = 60

Result: Largest = 60, Second Largest = 50

Alternative Method: Sorting Approach

Another approach is to sort the array and then find the second largest element. This is simpler but less efficient for large arrays.

#include <stdio.h>

int main() {
    int n, i, j, temp;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    if(n < 2) {
        printf("\nArray must have at least 2 elements.\n");
        return 1;
    }
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Sort array in descending order (bubble sort)
    for(i = 0; i < n-1; i++) {
        for(j = 0; j < n-i-1; j++) {
            if(arr[j] < arr[j+1]) {
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    
    // Find second largest (skip duplicates of largest)
    int second_largest = -1;
    for(i = 1; i < n; i++) {
        if(arr[i] != arr[0]) {
            second_largest = arr[i];
            break;
        }
    }
    
    printf("\nLargest element: %d\n", arr[0]);
    if(second_largest != -1) {
        printf("Second largest element: %d\n", second_largest);
    } else {
        printf("No second largest element found.\n");
    }
    
    return 0;
}

Time and Space Complexity

Method Time Complexity Space Complexity
Single Pass (Optimized) O(n) O(1)
Sorting Approach O(n²) O(1)

šŸ’» Practice Exercise

Challenge 1: Modify the program to find the second smallest element in the array.

Challenge 2: Find the third largest element in the array.

šŸ” Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n, i;
    int smallest, second_smallest;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    if(n < 2) {
        printf("\nArray must have at least 2 elements.\n");
        return 1;
    }
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    smallest = arr[0];
    second_smallest = 999999;  // Large initial value
    
    for(i = 1; i < n; i++) {
        if(arr[i] < smallest) {
            second_smallest = smallest;
            smallest = arr[i];
        }
        else if(arr[i] < second_smallest && arr[i] != smallest) {
            second_smallest = arr[i];
        }
    }
    
    printf("\nSmallest element: %d\n", smallest);
    if(second_smallest != 999999) {
        printf("Second smallest element: %d\n", second_smallest);
    } else {
        printf("No second smallest element found.\n");
    }
    
    return 0;
}

Frequently Asked Questions

1. How do you find the second largest element in an array in C?

Traverse the array once, keeping track of the largest and second largest elements. When you find a new largest, the old largest becomes the second largest.

2. What if the array has duplicate elements?

Use the condition arr[i] != largest when updating the second largest. This ensures duplicates of the largest element are not counted as the second largest.

3. What is the time complexity of finding the second largest?

The optimal approach has a time complexity of O(n), where n is the number of elements. It requires only a single pass through the array.

4. What happens if all elements are the same?

If all elements are the same, there is no second largest element. The program will display "No second largest element found."

5. Can I use sorting to find the second largest element?

Yes, you can sort the array and then find the second largest. However, this is less efficient (O(n²) for bubble sort) and not recommended for large arrays.

šŸ’” Tip: Always initialize second_largest to a value that will be replaced by any valid element (like -1 or INT_MIN from limits.h).

šŸ“– Related Tutorials

  • Find Maximum Element in Array
  • Find Minimum Element in Array
  • Search in Sorted Array
  • More Array Assignments

Previous Topic: -->> Search in Sorted Array   ||   Next topic: -->> Remove Duplicate Elements from Array


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.