Arrays - 2 (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Assignments

Arrays - 2
Assignments Solution
Q1. Count the number of elements strictly greater than x.
Solution:

#include <iostream>

using namespace std;

int main() {

int x;

cin>>x;

int a[5];

cout<<”Enter 5 elements for the array”<<endl;

for(int i=0;i<5;i++)cin>>a[i];

int ans=0;

for(int i=0;i<5;i++){

if(a[i]>x) ans++;

cout<<ans<<endl;

return 0;

Q2. WAP to find the largest three elements in the array.


Solution:

#include <iostream>

using namespace std;

int main() {

int arr[5]={10,3,1,21,3};

int max, max2, max3;

max3 = max = max2 = arr[0];

for(int i = 0; i < 5; i++){

if (arr[i] > max){

max3 = max2;

max2 = max;

max = arr[i];

else if (arr[i] > max2){

max3 = max2;

max2 = arr[i];

else if (arr[i] > max3)

max3 = arr[i];

cout<<endl<<"Three largest elements of the array are "<<max<<",


"<<max2<<",

"<<max3;

return 0;

Java
C++ &+ DSA
DSA
Assignments Solution
Q3. Check if the given array is sorted or not.
Solution:

#include <iostream>

using namespace std;

int main() {

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

for (int i = 1; i < 5; i++){

// Unsorted pair found

if (arr[i - 1] > arr[i]){

cout<<”NO”<<endl;

return 0;

// No unsorted pair found

cout<<”YES”<<endl;

return 0;

Q4. Find the difference between the sum of elements at even indices to the sum of elements at odd

indices.
Solution:

#include <iostream>

using namespace std;

int main() {

int a[5]={7,2,32,5,20};

int sume=sumo=0;

for(int i=0;i<5;i++){

if(i%2==0)

sume+=a[i];

else

sumo+=a[i];

cout<<abs(sume-sumo);

return 0;

Q5. Given an array of integers, change the value of all odd indexed elements to its second multiple

and increment all even indexed values by 10.


Solution:

#include <iostream>

using namespace std;

int main() {

int arr[5]={7,2,32,5,20};

for(int i=0;i<5;i++){

Java
C++ &+ DSA
DSA
Assignments Solution
if(i%2==0) arr[i]+=10;

else arr[i]=2*arr[i];

cout<<arr[i]<<” “;

return 0;

Q6. Find the unique number in a given Array where all the elements are being repeated twice with one

value being unique.


Solution:

#include <iostream>

using namespace std;

int main() {

int arr[5]={2,2,1,1,20};

for(int i=0;i<5;i++){

int count=0;

for(int j=0;j<5;j++){

if(arr[i]==arr[j]) count++;

if(count==0){

cout<<arr[i];

return 0;

cout<<”No unique value.”;

return 0;

Java
C++ &+ DSA
DSA
THANK

YOU !

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy