Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
C++ Program to Find the K'th largest element in a stream
Next article icon

C++ Program to Find the Second Largest Element in an Array

Last Updated : 30 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++.

Examples:

Input:   arr[] = {34, 5, 16, 14, 56, 7, 56}    Output: 34    Explanation: The largest element is 56 and the second largest element  is 34.

Find the Second Largest Element in an Array in C++

To find the second largest element in an array in C++, we can initialize two variables, first and second, to the minimum possible value for the data type. Then, we can traverse the array and update the first and second as we find elements larger than them.

Approach

  • Initialize two variables, first and second, to the minimum possible value to keep track of the largest and second largest elements in the array.
  • Start traversing the whole array using a loop.
  • For each element in the array, check if it is greater than the current largest element (first).
  • If it is greater, then update the second largest element (second) to be the current largest element, and update the largest element to be the current element.
  • If the current element is not greater than the largest element but is greater than the second largest element, then update the second largest element to be the current element.

C++ Program to Find the Second Largest Element in an Array

C++
// C++ Program to illustrate how to find the second largest // element in an array #include <climits> #include <iostream> using namespace std;  int main() {     // Initialize an array     int array[] = { 1, 2, 3, 4, 5 };     int n = sizeof(array) / sizeof(array[0]);      // Initialize first and second to the minimum possible     // value     int first = INT_MIN, second = INT_MIN;      // Traverse the array     for (int i = 0; i < n; i++) {         // If current element is greater than first         if (array[i] > first) {             second = first;             first = array[i];         }         // If current element is in between first and second         else if (array[i] > second && array[i] < first) {             second = array[i];         }     }      // Print the second largest element     cout << "Second Largest Element in the Array: "          << second << endl;      return 0; } 

Output
Second Largest Element in the Array: 4  

Time Complexity: O(N), where N is the size of the array.
Auxiliary space: O(1)




Next Article
C++ Program to Find the K'th largest element in a stream

R

rohan_paul
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-array
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • C++ Program to Find the K'th largest element in a stream
    Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input:stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...}k = 3Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on to
    7 min read
  • C++ Program to Sort the Elements of an Array in Ascending Order
    Here, we will see how to sort the elements of an array in ascending order using a C++ program. Below are the examples: Input: 3 4 5 8 1 10Output: 1 3 4 5 8 10 Input: 11 34 6 20 40 3Output: 3 6 11 20 34 40 There are 2 ways to sort an array in ascending order in C++: Brute-force Approach Using Bubble
    4 min read
  • C++ Program to Check for Majority Element in a sorted array
    Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majorit
    6 min read
  • How to Find the Second Smallest Element in an Array in C++?
    In C++, arrays are data structures that store the collection of data elements of the same type in contiguous memory locations. In this article, we will learn how to find the second smallest element in an array in C++. Example:Input:myArray = {10, 5, 8, 2, 7, 3, 15};Output:The second smallest element
    3 min read
  • C++ Program for Last duplicate element in a sorted array
    We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
    2 min read
  • C++ Program to Find the Minimum and Maximum Element of an Array
    Given an array, write functions to find the minimum and maximum elements in it.  Example: C/C++ Code // C++ program to find minimum (or maximum) element // in an array. #include <bits/stdc++.h> using namespace std; int getMin(int arr[], int n) { int res = arr[0]; for (int i = 1; i < n; i++)
    3 min read
  • Program to find largest element in an array using Dynamic Memory Allocation
    Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation. Examples: Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7. Input: arr[] = {8, 9, 10, 12} Output: 12Explanati
    5 min read
  • How to Find the Maximum Element of an Array using STL in C++?
    Given an array of n elements, the task is to find the maximum element using STL in C++. Examples Input: arr[] = {11, 13, 21, 45, 8}Output: 45Explanation: 45 is the largest element of the array. Input: arr[] = {1, 9, 2, 5, 7}Output: 9Explanation: 9 is the largest element of the array. STL provides th
    3 min read
  • C++ Program for Third largest element in an array of distinct elements
    Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :   Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 1
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences