Sei sulla pagina 1di 5

Arrays

Largest element :

#include<bits/stdc++.h>
using namespace std;
int find_largest(int nums[], int n) {
return *max_element(nums, nums + n);
}

int main() {
int nums[] = {
5,
4,
9,
12,
8
};
int n = sizeof(nums) / sizeof(nums[0]);
cout << "Original array:";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";

cout << "\nLargest element of the said array: "<< find_largest(nums,


n);
return 0;
}
Write a C++ program to find the largest three
elements in an array.
#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;
}

 Write a C++ program to find the most


occurring element in an array of integers

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

void most_occurred_number(int nums[], int size)


{
int max_count = 0;
cout << "\nMost occurred number: ";
for (int i=0; i<size; i++)
{
int count=1;
for (int j=i+1;j<size;j++)
if (nums[i]==nums[j])
count++;
if (count>max_count)
max_count = count;
}

for (int i=0;i<size;i++)


{
int count=1;
for (int j=i+1;j<size;j++)
if (nums[i]==nums[j])
count++;
if (count==max_count)
cout << nums[i] << endl;
}
}

int main()
{
int nums[] = {4, 5, 9, 12, 9, 22, 45, 7};
int n = sizeof(nums)/sizeof(nums[0]);
cout << "Original array: ";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
most_occurred_number(nums, n);
}

Write a C++ program to rearrange a given


sorted array of positive integers .

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

void rearrange_max_min(int nums[], int n)


{
int temp[n];
int small_num=0, large_num=n-1;
int result = true;

for (int i=0; i<n; i++)


{
if (result)
temp[i] = nums[large_num--];
else
temp[i] = nums[small_num++];

result = !result;
}

for (int i=0; i<n; i++)


nums[i] = temp[i];
}

int main()
{
int nums[] = {0, 1, 3, 4, 5, 6, 7, 8, 10};
int n = sizeof(nums)/sizeof(nums[0]);
cout << "Original array: ";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
rearrange_max_min(nums, n);

printf("\nArray elements after rearranging: ");


for (int i=0; i < n; i++)
cout << nums[i] <<" ";
return 0;

Potrebbero piacerti anche