working with array

Jul 2, 2014 at 9:01am
hi all
this is my program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 #include <iostream>
#include <fstream>
using namespace std;
main()
{
	float x,y,z,dar,i;
	ofstream list("list.txt");
	cout<<"gheymate emroz:";
	cin>>x;
	cout<<"gheymate diroz:";
	cin>>y;
	x*=100;
	z=(x/y);
	z-=100;
	cout<<"%"<<z;
	float a[10];
	for(i=0;i<10;i++)
	a[i]=z;
	cout<<endl;
	cout<<"%"<<a[i];
	list<<'%'<<a[i];
}

my problem begins from a[10] i dont know how to save the z Variable to a[10]
:( when i writh this a[i]=z; my compiler will get error
Last edited on Jul 2, 2014 at 9:03am
Jul 2, 2014 at 9:53am
What's your error ?
Jul 2, 2014 at 10:00am
i must not be a floating point number. So float is not allowed, use int or similar
Jul 2, 2014 at 10:23am
I'm not exactly sure on what you're trying to do but I think this may be what you're after. Even if you're only going to have one statement in your for loop, use braces. It improves the codes readability tenfold.

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
#include <iostream>
#include <fstream>

using namespace std;

int main() { // return type int.

	float x, y, z, dar; // i cannot be a float.

	ofstream list("list.txt");

	cout << "gheymate emroz:";
	cin >> x;
	cout << "gheymate diroz:";
	cin >> y;

	x *= 100;
	z = (x / y);
	z -= 100;

	cout << "%" << z;

	float a[10];

	for (int i = 0; i < 10; i++) { 
		a[i] = z;	
		cout << endl;
		cout << "%" << a[i];
		list << '%' << a[i];
	}
}
Last edited on Jul 2, 2014 at 10:25am
Jul 2, 2014 at 1:57pm
my problem begins from a[10]

You can't assign anything to a[10]. a[10] is not a valid reference.
You've defined 10 occurrances. Those are a[0]-a[9]. a[10] is out of bounds.

Not clear from your original code which statements you intended to be within the scope of your for loop. As originally written, only line 18 will be executed within your for loop. If you intended lines 18-21 to be executed within the for loop, use {} as sausage suggested. As originally written, lines 19-21 will only be executed once you've exited the for loop. That's also going to cause another problem. When you exit the for loop, a will equal 10, causing you to reference a[10] which is not valid as explained above.

Topic archived. No new replies allowed.