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; } } }
4 Answers
0
also using triangularNumber += x can save you some time :)
+ 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.
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;
}
}
}
0
Alexander Crum thanksđ
let me try it out