1

I'm trying to get a list of integers from 2 to N, however I am getting a weird output.

Code:

#define N 10

int main(int argc, char *argv[]) {

    int array[N]={2-N};
    for(int i=0;i<N;printf("%d ",array[i]), i++);
}

Output:

-8 0 0 0 0 0 0 0 0 0 

I'm trying to get it to read: 2,3,4,5,6,7,8,9,10

Any ideas? Thanks in advance

user1902535
  • 155
  • 1
  • 3
  • 10

4 Answers4

2

This statement

int array[N]={2-N};

Sets the first element of the array to 2-N, and as N is 8, that will set it to -8. The other elements are undefined, but happen to be zero.

You want something like

for (int i = 0; i < N; i++)
    array[i] = i+2;
abligh
  • 24,573
  • 4
  • 47
  • 84
0

N is 10, 2-N is -8. That is why the first array element is -8.

The other array elements are 0 because they were not explicitly initialized, so are initialized by default to 0.

You could initialize it as

int array[N]={2, 3, 4, 5, 6, 7, 8, 9, 10};

https://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Faryin.htm

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Save that that only initializes 9 out of the 10 elements, but to be fair OP didn't actually say what he wanted the 10th element to be. – abligh Feb 13 '14 at 21:29
0

Put that printf statement inside the loop itself, properly.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
-1
int array[N]={2-N};  

will initialize first element of array, i.e, array[0] to -8 and rest of them initialized to 0 implicitly (take a look here). So, you are getting right output.
To initialize your array from 2 to N, you need to use a for loop:

for (int i = 0; i < N; i++)
    array[i] = i+2;
Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • `array` is an automatic, allocated on the stack, so it is not initialized to 0 by default. It is undefined by default (unlike a static). – abligh Feb 13 '14 at 21:28
  • 2
    It is initialized by default according to IBM docs: ` If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. ` – Eric J. Feb 13 '14 at 21:29
  • @abligh; Yes it will. Run this program: `#include int main(){ int a[5] = {1}; for(int i = 0; i < 5; i++) printf("%d", a[i]);}` and see the result. – haccks Feb 13 '14 at 21:32
  • 1
    @haccks - you again! this time you are definitely right. I missed the *partial* initialisation. Apologies. – abligh Feb 13 '14 at 21:36
  • @abligh; No problem. It happens :) – haccks Feb 13 '14 at 21:37