0

Why am I getting different outputs in these two types of loops(the while loop is correct though)

class forExample2 { public static void main(String[] args) { //for loop int triangularNumber = 1; /* for(int x = 1; x <= 10; x++){ System.out.println(triangularNumber); triangularNumber = triangularNumber + x; }*/ //while loop int y = 1; while(y <= 10){ System.out.println(triangularNumber); y++; triangularNumber = triangularNumber + y; } } }

25th Mar 2021, 9:49 AM
Karuchiu Wamahiga
Karuchiu Wamahiga - avatar
4 odpowiedzi
0
also using triangularNumber += x can save you some time :)
25th Mar 2021, 11:05 AM
Alexander Crum
Alexander Crum - avatar
+ 1
Im still new to java but this is what I found: if you change int x = 1 to equals 2 instead itll output the traingular numbers. Since the incrementation only happens after the code has been executed you’ll kind of fall behind otherwise. Having int x = 2 will lead to you’re code only outputting 9 numbers but you can change that very easily.
25th Mar 2021, 11:02 AM
Alexander Crum
Alexander Crum - avatar
0
This code outputs triangular numbers i.e 1,3,6,10, 15,21,28,36,45,55 The second loop (while loop) outputs it well. The first loop(for loop) won't output correctly. class forExample2 { public static void main(String[] args) { //for loop int triangularNumber = 1; for(int x = 1; x <= 10; x++){ System.out.println(triangularNumber); triangularNumber = triangularNumber + x; } } }
25th Mar 2021, 10:23 AM
Karuchiu Wamahiga
Karuchiu Wamahiga - avatar
0
Alexander Crum thanks😁 let me try it out
25th Mar 2021, 2:27 PM
Karuchiu Wamahiga
Karuchiu Wamahiga - avatar