Why is the output how it is? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the output how it is?

for (int a=1; a<6; a++) { for(int b=1; b<=a; b++) { System.out.print('*'); } } Hello Everyone, so can please somebody explain to me why the output is: *************** And not: ***** I get what the loops are doing, when A and B are 1 it prints one *, when its 2 it prints ** and so on But I dont get the logic, where did I say to print it more than once? And arent the numbers in the loops only for how often it should run trough and not how much to print? Here is the code for better view https://code.sololearn.com/co3KZk0VL0i1/?ref=app

3rd May 2021, 4:38 PM
Kevin
Kevin - avatar
5 Answers
+ 1
As the outer loop runs once.. then the inner also but it is not like the inner loop runs only once each time ...but its number of times increase as the value of 'a' increases....so if 'a' is 4 in the 4th time of outer loop the inner loop will run 4 times and not 1.....so output will have more '*' then the number of times the outer loop runs
3rd May 2021, 4:52 PM
Abhinav Raj
Abhinav Raj - avatar
+ 2
public class Program { public static void main(String[] args) { for (int a=1; a<6; a++) { System.out.print('*'); } } } //Program to get your expected output
3rd May 2021, 5:34 PM
Atul [Inactive]
+ 1
Are you expecting this? public class Program { public static void main(String[] args) { for (int a=1; a<6; a++) { for(int b=1; b<=a; b++) { System.out.print('*'); } System.out.println (); } } }
3rd May 2021, 4:48 PM
Atul [Inactive]
+ 1
here how is changed a,b for each star 1,1 2,1 2,2 3,1 3,2 3,3 4,1 4,2 4,3 4,4 5,1 5,2 5,3 5,4 5,5
3rd May 2021, 4:54 PM
zemiak
+ 1
Thank you everybody I solved it!
3rd May 2021, 6:47 PM
Kevin
Kevin - avatar