0
why does for each loop doesn't traverse the array, when we insert the values dynamically??
import java.util.Scanner; public class Advfor { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("How many numbers do you want to enter into the array :"); int num = sc.nextInt(); int[] arr = new int[num]; System.out.print("Enter the numbers :"); for(int i =0;i<=num; i++) { arr[i] = sc.nextInt(); } System.out.println("Will traverse using advanced for loop"); for(int arr1 : arr) { System.out.print(arr1+" "); } } }
2 Answers
+ 2
Nothing's wrong with the enhanced for..loop printing the elements. The problem is with the for...loop that reads the elements' values in ...
for( int i = 0; i < num; i++ )
Your loop runs from zero to <n> inclusively, while array only have slots zero to <n> - 1.
+ 1
Thank you buddyâ€