+ 1

Why the first elements prints as 0 - Java Arrays

Hello all, Trying to figure out why the output starts with 0? The code below prints [0, 7, 14, 21, 28], but what I'm trying to achieve should print/return [7, 14, 21, 28, 35] Here is my code: import java.util.*; public class MyClass { public static void main(String args[]) { int num = 7; int length = 5; int [] numbers = new int [length]; for (int i = 0; i < length; i++){ numbers[i] = num * i; } System.out.print(Arrays.toString(numbers)); } } Thanks for reading! : )

14th Apr 2023, 4:24 PM
GG128
3 Respostas
+ 8
GG128 that's because you multiply by 0 like in you store 7 in num variable and i variable is start with 0, when you run the loop then your condition inside is:- num*i that means 7*0=0 like that and when you use array then we should always put 0 in for loop because array index start with 0
14th Apr 2023, 4:31 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
+ 4
At first index : number[0] = 7 * 0 = 0 That's why.! you can do number[i] = num * ( i+1 ) ;
14th Apr 2023, 4:32 PM
Jayakrishna 🇮🇳
+ 3
Thank you both for your quick response. I actually tried number[i] = num * i+1 , but I was getting [1, 8, 15, 22, 29]. Putting the parenthesis for i+1 worked! : )
14th Apr 2023, 4:39 PM
GG128