Write a c program to find second largest/highest element/number in an array using single loop.

There is multiple approach to find the second highest element in an array. In my previous post i solve this problem using sorting approach to find second highest element of an array.

You can do it without sorting an array also.

Let's take an array.

To find the second highest element, i use the following logic.

1. Take two flag (i take highest and secondhighest) and Initialize

2.

There is multiple approach to find the second highest element in an array. In my previous post i solve this problem using sorting approach to find second highest element of an array.

You can do it without sorting an array also.

Let's take an array.

int arr[] = {4,5,2,1,7,8};

To find the second highest element, i use the following logic.

1. Take two flag (i take highest and secondhighest) and Initialize

**highest=0**and**secondhighest=0**element in the beginning.2.

**Traverse**an array, if an array element greater than highest value, assign them in highest, and assign the previous highest value to secondhighest.for(i=0;i<n;i++){ if(arr[i]>highest){ secondhighest = highest; highest = arr[i]; } }

### Program to Find Second Highest Element in an Array Without Using Sorting

#include <stdio.h> main() { int arr[] = {4,5,2,1,7,8}; int highest=0,i; int secondhighest = 0; int n = sizeof(arr)/sizeof(arr[0]); /* Traverse an array. */ for(i=0;i<n;i++){ /* If value of arr[index] is greater than highest value. */ if(arr[i]>highest){ secondhighest = highest; highest = arr[i]; }else if(arr[i]>secondhighest && arr[i] !=highest){ secondhighest = arr[i]; } } printf("Second highest is %d",secondhighest); }

Check some more Question on Arrays

check for 10,6,2,1 ans will be 0 which is wrong...:(

ReplyDeleteThanks for pointing my mistake, i have corrected it.

ReplyDelete