An algorithm to insert new element at index m.
###An algorithm to insert new element in index m.
Flowchart given below:
Source Code in C++:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int n,x,i,j,a[1000],temp;
std::cout << "How many elements: " ;
std::cin >> n;
std::cout << "Take all the elements: " << '\n';
for (size_t i = 0; i <n; i++) {
std::cin >> a[i];
}std::cout << "Which element you wanna insert: " ;
std::cin >> x;
std::cout << "Which position you wanna insert: " ;
std::cin >> j;
for(i=n;i>=j-1;i--){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
a[j-1]=x;
std::cout << "After insertion we got: " << '\n';
for (size_t i = 0; i <=n; i++) {
std::cout << a[i] << '\n';
}
return 0;
}
Output:
How many elements: 6
Take all the elements:
1
2
3
4
5
6
Which element you wanna insert: 11
Which position you wanna insert: 5
After insertion we got:
1
2
3
4
11
5
6
Press any key to continue . . .
Explanation:
Here we were asked to insert an element in an index of an array.So,we first took an array.Then we took the number we wanna insert.Then we took the position where we wanna insert the number.The we created a gap in that position by swapping values using
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
Then we inserted that value in that place.Then we printed the array again with that inserted value.
Flowchart given below:
Source Code in C++:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int n,x,i,j,a[1000],temp;
std::cout << "How many elements: " ;
std::cin >> n;
std::cout << "Take all the elements: " << '\n';
for (size_t i = 0; i <n; i++) {
std::cin >> a[i];
}std::cout << "Which element you wanna insert: " ;
std::cin >> x;
std::cout << "Which position you wanna insert: " ;
std::cin >> j;
for(i=n;i>=j-1;i--){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
a[j-1]=x;
std::cout << "After insertion we got: " << '\n';
for (size_t i = 0; i <=n; i++) {
std::cout << a[i] << '\n';
}
return 0;
}
Output:
How many elements: 6
Take all the elements:
1
2
3
4
5
6
Which element you wanna insert: 11
Which position you wanna insert: 5
After insertion we got:
1
2
3
4
11
5
6
Press any key to continue . . .
Explanation:
Here we were asked to insert an element in an index of an array.So,we first took an array.Then we took the number we wanna insert.Then we took the position where we wanna insert the number.The we created a gap in that position by swapping values using
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
Then we inserted that value in that place.Then we printed the array again with that inserted value.
No comments