Write C++ program to insert an element in array


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #define MAX_SIZE 100 //Maximum size of the array
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.  
  8. int arr[100];
  9. int i, num, size, position;
  10.  
  11. // Reading size and elements of array
  12. cout<<"Enter size of the array :";
  13. cin>>size;
  14. cout<<"Enter elements in array : ";
  15. for(i=0; i<size; i++)
  16. {
  17. cin>>arr[i];
  18. }
  19.  
  20. //Reading element to insert & position of the element
  21.  
  22. cout<<"Enter element to insert : ";
  23. cin>>num;
  24. cout<<"Enter the element position : ";
  25. cin>>position;
  26.  
  27. //checking elements valis position
  28.  
  29. if(position>size+1 || position<=0)
  30. {
  31. cout<<"Invalid position! Please enter position between 1 to "<<num;
  32. }
  33. else
  34. {
  35. //Inserting element in an array & increasing the size of the array
  36.  
  37. for(i=size; i>=position; i--)
  38. {
  39. arr[i] = arr[i-1];
  40. }
  41. arr[position-1] = num;
  42. size++;
  43.  
  44. // Printing new array with new element
  45.  
  46. cout<<"Array elements after insertion : ";
  47. for(i=0; i<size; i++)
  48. {
  49. cout<<arr[i]<<"\t";
  50. }
  51. }
  52.  
  53. return 0;
  54. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts