Why this takes error?(the for loop) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why this takes error?(the for loop)

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); for(int i = arr.length ; i>=0 ; i--){ System.out.println(arr[i]); } } }

28th Apr 2022, 2:11 PM
juanestragon 10
juanestragon 10 - avatar
2 Answers
+ 6
juanestragon 10 Should be (arr.length - 1) Because index starts from 0 so ['a', 'b', 'c'] will have 0, 1, 2 index now think in reverse 2, 1, 0
28th Apr 2022, 2:23 PM
A͢J
A͢J - avatar
+ 4
Suppose you have an array on length 3. Then the highest index will be 2, not 3. However, your current loop would start with the non-existant index 3.
28th Apr 2022, 2:14 PM
Lisa
Lisa - avatar