Table of Contents
Back Button
Back to Chapter
C++ Setting Up
C++ Introduction
No items found.
C++ Basics
No items found.
C++ Control Statements
No items found.
C++ Logical Operators
No items found.
C++ Procedural Programming
No items found.
C++ Structural Programming
No items found.
C++ Implementation of OOPS
No items found.
C++ Arrays and Vectors
No items found.
C++ Error Handling
No items found.
C++ File Handling
No items found.

C++ Arrays Exercise

Write a C++ program to create an array and perform the following operations:

  1. Store integers entered by a user.
  2. Sort this array.
  3. Search for a key element 15 using binary search algorithm
  4. Insert an integer 20 at any given position as per the users choice.
  5. Delete an array element at position as requested by the user.

Solution:

#include using namespace std; void display(int a[],int n) { for (int i=0;i= pos; i--) arr[i] = arr[i - 1]; // insert a at positionX arr[pos - 1] = a; return n; } void create(int a[10],int n) { for(int i=0;i>a[i]; } } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // to implement bubble sort void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } //to delete an element from the array int deleteElement(int arr[], int n, int x) { // Search x in array int i; for (i=0; i>n; cout<>(ch); // to prompt user to perform preferred operation on created array switch(ch) { case 1: cout<<"enter the element you wish to insert:"; cin>>elem; cout<<"enter the position where you wish to insert"; cin>>pos; n=insertA(n,a,elem,pos); display(a,n); break; case 2: cout<>key; int found=search(a,n,key); if(found==1) { cout<<"element found"<>delem; n=deleteElement(a,n,delem); display(a,n); break; } case 5: cout<<"Exiting program"; exit(0); default: cout<<"Enter a valid choice;"; break; } }while(ch!=0); }
Output: how many elements you wish to enter:6 element 1:0 element 2:0 element 3:0 element 4:0 element 5:0 element 6:0 enter Array element 1:5 enter Array element 2:4 enter Array element 3:10 enter Array element 4:12 enter Array element 5:4 enter Array element 6:9 WHAT DO YOU WISH TO DO: 1.INSERT 2.SORT 3.SEARCH 4.DELETE 0.EXIT:1 enter the element you wish to insert:4 enter the position where you wish to insert2 element 1:5 element 2:4 element 3:4 element 4:10 element 5:12 element 6:4 element 7:9 WHAT DO YOU WISH TO DO: 1.INSERT 2.SORT 3.SEARCH 4.DELETE 0.EXIT:4 enter the element you wish to delete:10 element 1:5 element 2:4 element 3:4 element 4:12 element 5:4 element 6:9 WHAT DO YOU WISH TO DO: 1.INSERT 2.SORT 3.SEARCH 4.DELETE 0.EXIT:2 sorted Array element 1:4 element 2:4 element 3:4 element 4:5 element 5:9 element 6:12 WHAT DO YOU WISH TO DO: 1.INSERT 2.SORT 3.SEARCH 4.DELETE 0.EXIT:3
Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?