Print the following star pattern using Apex code:
*****
****
***
**
*
Answer:
public class StarPattern {
public static void printStarPattern() {
Integer totalRows = 5;
for (Integer i = totalRows; i > 0; i--) {
String row = '';
for (Integer j = 0; j < i; j++) {
row += '*';
}
System.debug(row);
}
}
}
Explanation:
● The outer loop (i) controls the number of rows, starting from 5 down to 1.
● The inner loop (j) adds the stars for each row.
● System.debug(row); prints each row to the debug log (Apex uses debug logs instead
of direct console output).
How to Run:
You can run this in the Developer Console in Salesforce:
1. Open Developer Console.
2. Go to Debug > Open Execute Anonymous Window.
3. Paste this line and check "Open Log":
StarPattern.printStarPattern();
4. Click "Execute" and view the output in the debug log.