Array

Hi all, well am new in programming, so their is some confusion in Array, well I wanna to insert New element in array, at specific position, and I got the code, and its working , but I don't know how its work.
So is here any one who can explain this code to me...??
Thank you...!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  /**/
#include<conio.h>
#include<iostream>
using namespace std;
main()
{
     int Array[]={1,2,3,4,5}; 
     int Position=3, value=99,size=5,N=size,i;  
     cout<<" The Array without Insertion is: "<<endl;
     for(i=0;i<size;i++) 
     {
     	cout<<" Array ["<<i<<"] = "<<Array[i]<<endl;
     }
     
     size+=1;  
     while(N>=Position)
     {
     	Array[N+1]=Array[N]; 
     	N-=1;    
     }
     Array[Position]=value; 
     for(i=0;i<size;i++)
     {
     	cout<<" Array ["<<i<<"] ="<<Array[i]<<endl;
     }
return 0;
}
Did you write it? There's a serious problem with that code.
It stores original size of an array in the N variable (that is the first problem, it should store index of the last element i. e. size - 1 = 4) and then increments size of array by 1 (but not really and that is the second problem, you're gonna need to find a way to actually do it). For now you can change Array[] to Array[100] to reserve 100 locations, it doesn't matter if you don't use them all. Then program shifts all elements 'till the given position (with index of 3) to the right and then inserts given value.

So, e. g. your array is
1 2 3 4 5

By incrementing size by 1 (theoretically speaking) you get:
1 2 3 4 5 _ (one empty location)

while(N>=Position)
{
    Array[N+1]=Array[N]; 
    N-=1;    
}
Array[Position]=value;

So loop starts from the last element in the array (with index of N) and copies it to the next position. It does that for all elements 'till the given position overwriting some fields in the process:
1 2 3 4 5 _
1 2 3 4 5 5
1 2 3 4 4 5 - 4 overwrites 5

Now it simply overwrites element at the 3rd position with a new value.
1 2 3 99 4 5
Last edited on
Topic archived. No new replies allowed.