tags:

views:

177

answers:

3

i am declaring a global array,and then assigning the values inside a if statement. But when i am using the array in another if statement the array has different values other than i assigned previously. For example:

int arr[5];
xyz(bool p,bool q)
{
    if(p)
    {
        for(int i=0;i<5;i++)
        {
            arr[i]=rand()%100;
        }
    }

    if(q)
    {
        for(i=0;i<5;i++)
        printf("%d",arr[i]);
    }
}

can anyone help??

+1  A: 
andand
I am calling function two times,in first p is true,q is false and second q is true and p is false. If in this case this is not possible then what is the way to access the array?
neha
@neha: Then please post some sample code showing how the function is called. Also, show what output you expected and what output you got. It's five integers in each case; that shouldn't be too hard.
David Thornley
@neha: I updated my answer in response to your comment.
andand
A: 

Try adjusting your first code block to something more like this:

if (p) {
    int temp;
    for (int i=0; i<5; i++) {
        temp = rand() % 100;
        printf("%i: %d\n", i, temp);
        arr[i] = temp;
    }
}

Now, you will get a listing of the random values before they are written into the array. Compare this list to what you get when you read them from the array later.

Update: I ran the above modification to your code on Codepad, and I am seeing the exact same values both times.

bta
A: 

I don't even see why you're adding those 'bool' variables since you're not creating to never run it! So just use this code [ which is the same as beta's version];

int temp;

for (int i=0; i<5; i++) {
    temp = rand() % 100;
    cout << i << temp << endl; 
    arr[i] = temp;
}
Eric