element insertion in an array

here's my problem. i need to insert a value in an array before an element which has the same value as "x" (which is read from the keyboard). i tried to solve it, but my program is not working right. here's how I thought the program should look like:
#include<iostream>
using namespace std;
int main()
{
int v[100],n,i,x,m,a;
cout<<"n= ";
cin>>n;
cout<<"x= ";
cin>>x;
cout<<"m= ";
cin>>m;
for(i=1;i<=n;i++)
{
cout<<"v["<<i<<"]= ";
cin>>v[i];
}
for(i=1;i<=n;i++)
{
if(v[i]==x)
{
n=n+1;
a=i;
for(i=n;i>a;i--)
{
v[i]=v[i-1];
}
v[i-1]=m;
}
}
for(i=1;i<=n;i++)
{
cout<<v[i]<<" ";
}
}

where is the mistake???
I wish I could tell you but there are two things preventing me from reading/understanding your code:

1. You have no formatting, put some indents and blank lines in there
2. Give meaningful names to your label names. You may know what n, x, and m are supposed to do, but I have absolutely no idea of their intent.

As far as I can tell, your program is running exactly as programmed.
I started purusing your code and noticed this:
In line 25 you create another nested loop, but you try and re-use the same index variable (originally i). That over-writes the index used in the outer-loop and so the outer one is not going to iterate as I think you expected.

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
29
30
31
32
33
#include<iostream>
using namespace std;
int main()
{
	int v[100],size,index,x,m,a;
	cout<<"size= ";
	cin>>size;
	cout<<"x= ";
	cin>>x;
	cout<<"m= ";
	cin>>m;

	for(index=1; index<=size; index++)
	{
		cout<<"v["<<index<<"]= ";
		cin>>v[index];
	}
	for(index=1; index<=size; index++)
	{
		if(v[index]==x)
		{
			size++;
			a=index;

			for(index=size; index>a; index--)
				v[index]=v[index-1];

			v[index-1]=m;	
		}
	}
	for(index=1; index<=size; index++)
		cout<<v[index]<<" ";
}
Topic archived. No new replies allowed.