#include <iostream>
using namespace std;
int main(){
int n, num[50], largest, second;
cout<<"Enter number of elements: ";
cin>>n;
for(int i=0; i<n; i++){
cout<<"Enter Array Element"<<(i+1)<<": ";
cin>>num[i];
}
/* Here we are comparing first two elements of the
* array, and storing the largest one in the variable
* "largest" and the other one to "second" variable.
*/
if(num[0]<num[1]){
largest = num[1];
second = num[0];
}
else{
largest = num[0];
second = num[1];
}
for (int i = 2; i< n ; i ++) {
/* If the current array element is greater than largest
* then the largest is copied to "second" and the element
* is copied to the "largest" variable.
*/
if (num[i] > largest) {
second = largest;
largest = num[i];
}
/* If current array element is less than largest but greater
* then second largest ("second" variable) then copy the
* element to "second"
*/
else if (num[i] > second && num[i] != largest) {
second = num[i];
}
}
cout<<"Second Largest Element in array is: "<<second;
return 0;
}
/*
quick explaination
basicly its searching for the largest UNSIGNED INT in an array of UNSIGNED INT where all the elements are the same size in bytes but the size in all the elements is a variable and can be changed
this method is finding the largest number but to find the second or third or even sort the array
i will create some sort of stack where each element is pushed but sense this is to find the 2nd largest number
it will just do that but you get the idea if you want to change the code to be something that fits you
suggestion : if you already know what size of numbers your array will be then its better to create
an easier and much effecient method in your case but this is a general one where the size isn't really knowen
*/
int GetLargestUnsignedIntElement(void* array_ptr, int array_length, int var_size)
{
void* var = malloc(var_size);
int second_largest = 0; //to be returned
int largest_index = 0;
//both the integers above are more like a "stack" but much more effecient
//than using a real stack class
bool Larger = false;
for (int x = 0; x < var_size; x++)
{
*(unsigned char*)((int)var + x) = 0;
}
for (int index = 0, ptr = (int)array_ptr; index < array_length; index++, ptr = ((int)array_ptr) + (index * var_size))
{
for (int i = 0, iptr = ptr; i < var_size; i++, iptr++)
{
if (*(unsigned char*)iptr > *(unsigned char*)((int)var + i))
{
Larger = true;
continue;
}
else if (*(unsigned char*)iptr == *(unsigned char*)((int)var + i))
{
continue;
}
else
{
Larger = false;
continue;
}
}
if (Larger)
{
for (int x = ptr, y = (int)var; x < (ptr + var_size); x++, y++)
{
*(unsigned char*)y = *(unsigned char*)x;
}
//push the result
second_largest = largest_index;
largest_index = index;
}
else
{
continue;
}
}
free(var);
return second_largest;
}