Correct or not Correct??

closed account (LE3bqMoL)
I was asked this question and my answer is:'-1"
Is this correct??
if not correct is it this then: '-15111723"??


What will be the contents of a[0] after the execution of the following code:

int a[5];
for (int j=0; j<5; j++)
a[j] = 3*j - 1;
for (j=3; j>=0; j--)
a[j] = a[j+1] + j;
Last edited on
closed account (S6k9GNh0)
Is this a class assignment? This isn't the first post like this you've made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int a[5]; //Declares an array of 6 integers

for (int j=0; j<5; j++) //Iterates through the for loop 5 times.
{
  a[j] = 3*j - 1;
  //a[0] = -1
  //a[1] = 2
  //a[2] = 5
  //a[3] = 8
  //a[4] = 11
}

for (j=3; j>=0; j--) //Iterates through the for loop 3 times.
{
  a[j] = a[j+1] + j;
  //a[3] = 14
  //a[2] = 16
  //a[1] = 17
  //a[0] = 17
}


Working code that shows you the that this is it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int a[4]; //This declares an array of 5 integers.

    for ( int j=0; j<5; j++ )
    {
        a[j] = 3 * j - 1;
    }

    for ( int j=3; j >= 0; j-- )
    {
        a[j] = a[j+1] + j;
    }
    std::cout << a[0] << std::endl;
}

In short your not right. The answer is 17.
Where'd you get your answers?
Last edited on
closed account (LE3bqMoL)
Just checking my answers??
Last edited on
int a[4]; //This allocates an array of 5 integers.

No it doesn't.

Anyway, I hated these assignments. At first glance I picked -1 as well but 17 is correct. I'm sure that computerquip was just pointing out that this was easy to test in a simple main function. If anything this exercise should be a good lesson as to why whitespace is important in a program. When things are mashed together your eyes play tricks on you. It is a little easier to see when the code is formatted better.

int a[4]; //This allocates an array of 5 integers.

LOL. I wouldn't want to be your supervisor. That's one nice potential buffer overflow you got there.
Topic archived. No new replies allowed.