I have been working in this code that its supposed to create an array with the o
ID: 3542788 • Letter: I
Question
I have been working in this code that its supposed to create an array with the odd numbers from 1 to 11 (inclusive) then print them. However when I try to print them I get the array printed six times, why is this happening? By the way I know I could use the enhanced for loop for this but I just want to know what is wrong in this particular program and how to fix it.
public static void main(String[] args) {
// TODO Auto-generated method stub
//Find the number of odd numbers from 1 to 11.
int[] array = new int[6];
for (int i = 0; i < array.length; i++)
{
for (int odd = 1; odd <= 11; odd += 2)
{
array[i] = odd;
System.out.println(array[i]);
}
}
}
Explanation / Answer
what you were doing wrong was that you were filling odd numbers at the same position in the array i.e., at the same ith index, your inner for was just overwriting values.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.