why does for each loop doesn't traverse the array, when we insert the values dynamically?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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+" "); } } }

6th Jan 2023, 2:11 PM
Harshanand Raykar
Harshanand Raykar - avatar
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.
6th Jan 2023, 2:59 PM
Ipang
+ 1
Thank you buddy❤
7th Jan 2023, 2:36 PM
Harshanand Raykar
Harshanand Raykar - avatar