Saturday, March 18, 2023

Write a C++ program to find the second largest value from Array.

Write a C++ program to find the second largest value from Array. C++ program to find the second largest value in an array

#include <iostream>
using namespace std;

int main() {
  int arr[] = {5, 8, 1, 9, 4, 3, 7, 2, 6};
  int n = sizeof(arr)/sizeof(arr[0]);
  int max1 = arr[0], max2 = arr[0];
  
  // Finding the maximum value
  for (int i = 0; i < n; i++) {
    if (arr[i] > max1) {
      max2 = max1;
      max1 = arr[i];
    }
    else if (arr[i] > max2 && arr[i] != max1) {
      max2 = arr[i];
    }
  }
  
  cout << "The second largest value in the array is " << max2 << endl;

  return 0;
}


Explanation:

  • An array is a collection of elements of the same data type, stored in contiguous memory locations.
  • In this program, we have declared an array named arr containing some integer values.
  • We have used the sizeof operator to determine the size of the array in bytes and divided it by the size of the first element to get the number of elements in the array, which is stored in the variable n.
  • We have initialized two variables max1 and max2 with the first element of the array. These variables will be used to store the maximum and second maximum values in the array, respectively.
  • We have used a for loop to iterate over each element in the array. Inside the loop, we have used an if statement to compare the current element with max1. If it is greater than max1, we update both max1 and max2 accordingly. If it is not greater than max1, we check if it is greater than max2 and not equal to max1, and if so, we update max2 to the current element.
  • Finally, we print out the second largest value in the array, which is stored in the variable max2.

Notes:

  • To find the second largest value in an array, we need to compare each element in the array with the current maximum and second maximum values and update them accordingly.
  • We can use a for loop to iterate over each element in the array and compare it with the maximum and second maximum values.
  • We need to initialize the maximum and second maximum variables with appropriate values before starting the loop.
  • We can use if statements to check if an element is greater than the current maximum or second maximum, and update the variables accordingly.
  • After the loop, the second maximum value will be stored in the appropriate variable, and we can print it out to the console.

No comments:

Post a Comment

Write a c++ program to show the difference between an array and a list.

Array vs List Example Write a c++ program to show the difference between an array and a list. Arrays are useful when you know the number ...