Arrays with variables

Hey there guys, I have a problem with a program i am making.
I will show you the basic problem.

int x[50];
for(int y=0; y<51; y++;)
{

x[y]=y; //this is the first problem. I can't define which element of the array
//x[50] with a variable, y.


//Now i have the second problem. How can I add all the elements of
//x[50] together?
//Is this use of accumulate correct?
int z=accumulate(x[0], x[50], 0);
cout<<z<<endl;

}
First of all if you have defined an array as x[50] then its subscriptors are in the range 0 - 49. So the loop for(int y=0; y<51; y++;) is incorrect. Also you have placed a semicolon after y++. It is a syntax error.
Shall be

for ( int i = 0; i < 50; i++ )

And do not use name y as an index. It is a bad style. It is better to use for indexes names as i, j, k, l, m, n.

As for calculation of the sum then you can write

int sum = std::accumulate( std::begin( x ), std::end( x ), 0 );

Do not forget to include header <iterator> and <numeric>

Or can write

int sum = std::accumulate( x , x + 50, 0 );
Last edited on
Ok thank you, I wrote this code very quickly. What about defining an element with a variable?
ex:
x[y]=y;
It gives me an error, and I need to do it for another program I am writing.
This statement

x[y] = y;

shall not issue an error if y is in the range of 0 - 49.

Or show the error message.
closed account (zb0S216C)
swedishfished wrote:
 
for(int y=0; y<51; y++;)

The only issue I see here is the semi-colon after y++. You can name your variables in anyway you please. For instance, you could name a double my_house_consists_of_bricks if you wanted to; there's nothing stopping you. Don't let anyone tell you otherwise.

Wazzak
Last edited on
float count = 0;

for(int addtodenominator=1; addtodenominator<101; addtodenominator+=2)
{
int count1= count/2;
int count2=count/2;
int x[50];
if(count1==count2){
x[count]=(-1/addtodenominator);



}

if(count1!=count2){
x[count]=1/addtodenominator; //It gives me the error "Array subscript
//is not an integer."



}


count++;
cout<<count<<endl;

}

return 0;
Last edited on
to add the numbers subsequentially:

1
2
3
4
5
6
int total = 0;
total = (x[0] + x[1]);
for(int y = 2; y <= 49; y++)
{
    total = (total + x[y]);
}

this will add like so: 1+ 2 then 3 + 3 then 6 + 4

essentially you are doing this: 1+2+3+4... n+50

First of all this code has no any sense.
As for your error then subscript shall be an integral type. But you use as a subscript the float.

float count = 0;
x[count]=1
How does my code "has no any sense"?
For example

count1 is always equal to count2.
int count1= count/2;
int count2=count/2;

So I do not see any sense in comparision

if(count1==count2){

Also I do not see any sense in declaration of the local array x

int x[50];
Last edited on
count2 was supposed to be a float
Topic archived. No new replies allowed.