In this tutorial you will learn about the C++ Programs to Insert Element in Array and its application with practical example.
C++ Program to Insert Element in Array
In this tutorial, we will learn to create a C++ program that will do Insert Element in Array using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ Programming.
- Creating and Using the user-defined function in C++ programming.
Insert Element in Array:-
In this tutorial, we will make a program that will insert the element in the array using c++ programming. First will take the five elements of an array from the user. Then will take the new elements from the user for inserting in the array. And at last, we will insert that element at the end of the array.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Step 1. Initialize the required variable for the prohgram. Step 2. Take size of array from the user. Step 3. Take the elements of array from the user. Step 4. Take location to insert an element in the array. Step 5. Insert the element in the array. Step 6. Printing the result array. Step 7. End program. |
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* C++ Programs to Insert an Element in Array */ #include<iostream> using namespace std; int main() { //Declaring the variable for the program. int arr[6], i, elem; //Taking the input from the user cout<<"Enter 5 Array Elements: "; for(i=0; i<5; i++) cin>>arr[i]; //Taking the elements of the array cout<<"\nEnter Element to Insert: "; cin>>elem; arr[i] = elem; //Taking the elements to insert in the array cout<<"\nThe New Array is:\n"; for(i=0; i<6; i++) cout<<arr[i]<<" "; cout<<endl; return 0; } |
Output:-
In the above program, we have first declared and initialized a set of variables required in the program.
- i = it will hold the integer value.
- arr[6] = it will hold the elements in an array.
- elem = it will hold the integer value that will be inserted in the array.
Taking input from the user:-
New elements from the user.
Taking input elements to add from the user.