• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array does not print negative numbers  RSS feed

 
kunal kapoor
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run the follwing piece of code,

int [] t;

t = new int[8];

for (int i=0; i<t.length; i++){
t[i] = 10-i;}

for (int element:t){
System.out.println(element);}

I was expecting the output to be: 10
9
8
7
6
5
4
3


However I got the follwing output: 10
9
8
7
6
0
0
0

Can anyone explain why?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Just compiled and ran program.... and got the expected output.

Henry
 
kunal kapoor
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right, I made a mistake. I typed s.length instead of t.length in for loop for assignment. 's' is another array which was of shorter length, had 5 elements. So the first five elements of the array got assigned and the ones after that were given the default assignment 0.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

you should always use copy and paste so you post real code, then we can see that sort of mistake easily.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!