samedi 14 décembre 2019

Why is assignment operator is used

I have some understanding issues in the program, where I have to extract the 3 largest integer elements present in the array.

In the second if statement arr[i]< first why we used the assignments of third to second, second to first? Can't we directly Assigns the First to the value of arr at i position?

#include<bits/stdc++.h>
using namespace std;

void three_largest(int arr[], int arr_size)
  {
   int i, first, second, third;

    if (arr_size < 3)
    {
        cout << "Invalid Input";
    }

    third = first = second = INT_MIN;
    for (i = 0; i < arr_size ; i ++)
    {
        if (arr[i] > first)
        {
            third = second;
            second = first;
            first = arr[i];
        }
         else if (arr[i] > second)
        {
            third = second;
            second = arr[i];
        }

        else if (arr[i] > third)
            third = arr[i];
    }

      cout << "\nThree largest elements are: " <<first <<", "<< second <<", "<< third;
}
int main()
{
    int nums[] = {7, 12, 9, 15, 19, 32, 56, 70};
    int n = sizeof(nums)/sizeof(nums[0]);
    cout << "Original array: ";
    for (int i=0; i < n; i++) 
    cout << nums[i] <<" ";
   three_largest(nums, n);
    return 0;
}

Original array: 7 12 9 15 19 32 56 70
Three largest elements are: 70, 56, 32

Aucun commentaire:

Enregistrer un commentaire