Answer to Question #254869 in C++ for Agy

Question #254869
Write a C++ code to create a on eh dimensional integer (integer type) array of size N. Create a menubased approach and solve the following. I) number of occurances of a given number in the array. ii) Remove the duplicate elements in the array. iii) Second Largest and Second Smallest element in the array. iv) Search an element in an array. v) Sort the array elements in ascending and descending based on user choice.
1
Expert's answer
2021-10-22T02:05:51-0400


#include<iostream>
#include<set>
using namespace std;


int occurrences(int a[], int size, int n)
{
    int result = 0;
    for (int i=0; i<size; i++)
        if (n == a[i])
          result++;
    return result;
}
 
 int  deleteduplicates(int a[], int size)
{
  
   
  int count=0;
    
    set<int> st;
  
 
    for (int i = 0; i < size; i++) {
  
        
        st.insert(a[i]);
    }
  
    set<int>::iterator iter;
  
   
    cout << "\nAfter removing duplicates:\n";
    for (iter = st.begin(); iter != st.end(); ++iter)
    
        cout << *iter << ", ";
    cout << '\n';


}


void swapping(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 


void sorting(int arr[], int n)
{
    int  min;
 
   
    for (int i = 0; i < n - 1; i++) {
 
        
        min = i;
        for ( int j = i + 1; j < n; j++)
            if (arr[j] < arr[min])
                min = j;
 
        
        swapping(&arr[min], &arr[i]);
    }
}
int searching(int a[], int size, int element)
{
    
    for (int i = 0; i < size; i++)
        if (a[i] == element)
            return i;
    return -1;
}
int main()
{
 int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 };
   int n = sizeof(arr)/sizeof(arr[0]);
    int x = 2;
	cout<<"Select an option:\n1.Number of occurances of a given number\n2. Sorting the array\n3.Remove the duplicates\n4. Display the second largest element\n";
	cout<<"5. Search for an element:\n";
	int choice;
	cin>>choice;
	switch(choice){
		case 1:
			cout << occurrences(arr, n, x);
		break;
		case 2:
				sorting(arr, n);
				for(int i=0; i<n; i++){
					cout<<arr[i]<<" ";
				}
				cout<<endl;
				break;
		case 3:
				deleteduplicates(arr,n);
				break;
		case 4:
			cout<<"Second smallest element is: "<<arr[1]<<endl;
	      cout<<"Second largest element is: "<<arr[n-3]<<endl;
	    case 5:
	    	int resu = searching(arr, n, 4);
	    	if(resu== -1){
	    		cout<<"Element not found";
			}
			else{
				cout<<"Element found\n";
			}
  
       
			
	}
	
   
  
    




	
	
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS