The code below prints sum from 1 to 10:
\$1\$
\$1+2 =\$
\$1+2+3 =\$
\$1+2+3+4 =\$
\$......\$
\$1 + ... 10 = 55\$
public class Solution{
public static void print_sums(){
int sum = 0 ;
for(int i = 1 ; i <= 10 ; i++){
for(int j = 1 ; j <= i; j++ ){
sum = sum + j ;
}
System.out.println( sum) ;
sum = 0 ;
}
}
public static void main(String[] args)
{
print_sums() ;
}
}
I wonder out of "efficiency curiosity" - is it possible to do it in 1 loop? Without 2 nested loops?
i.e. put both i
and j
in one loop and increment them from there.
I think it is impossible, because **the whole loop will run only 10 times - i = [1,10]
for(int i = 1 , j = 1 ; j <= i && i <= 10 ; i++, j++)
//for(int j = 1 ; j <= i; j++ ){
sum = sum + j ;
//}
System.out.println( sum) ;
sum = 0 ;
1 to N
. \$\endgroup\$