Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print each character of the string using a for loop.
DSA Java
String word = "hello"; for (int i = 0; i [1] word.length(); i++) { System.out.print(word.charAt(i)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes an error because it tries to access an index equal to word.length().
✗ Incorrect
The loop should run from 0 up to but not including word.length() to avoid IndexOutOfBoundsException.
2fill in blank
mediumComplete the code to check if the first character of the string is 'A'.
DSA Java
String name = "Alice"; if (name.charAt([1]) == 'A') { System.out.println("Starts with A"); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 accesses the second character, not the first.
✗ Incorrect
The first character of a string is at index 0.
3fill in blank
hardFix the error in the code to print characters in reverse order.
DSA Java
String text = "code"; for (int i = text.length() - 1; i [1] 0; i--) { System.out.print(text.charAt(i)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > skips the character at index 0.
✗ Incorrect
To include index 0, the loop condition should be i >= 0.
4fill in blank
hardFill both blanks to create a loop that prints only uppercase letters from the string.
DSA Java
String message = "HeLLo123"; for (int i = 0; i [1] message.length(); i++) { char ch = message.charAt(i); if (ch [2] 'A' && ch <= 'Z') { System.out.print(ch); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of >= skips the letter 'A'.
Using <= in loop condition causes index error.
✗ Incorrect
The loop runs while i < message.length(). The condition checks if ch >= 'A' and ch <= 'Z' to find uppercase letters.
5fill in blank
hardFill all three blanks to create a loop that counts vowels in the string.
DSA Java
String input = "Education"; int count = 0; for (int [1] = 0; i [2] input.length(); [3]++) { char c = input.charAt(i); if ("aeiouAEIOU".indexOf(c) != -1) { count++; } } System.out.println(count);
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using <= causes index error.
✗ Incorrect
The loop variable is i, starting at 0, running while i < input.length(), and incrementing i each time.
