Write the program in Java to display the first ten terms of the following series: 1, 4, 9, 16,
Categories: Core Java Java 8(JDK1.8) Interview questions and answers Experienced Freshers Java Lambda NCERT Series Programming
package r4rin.com.Series;
/*
* Write the program in Java to display the first ten terms of the following series:
1, 4, 9, 16,
*/
import java.util.stream.Stream;
public class FirstTenTerms {
public static void main(String[] args) {
// First ways before jdk 1.8
for(int i=1;i<=10;i++) {
System.out.print(i*i+" ");
}
System.out.println();//New Line
//Second ways
//After Jdk 1.8 Using Stream APIs
//Stream.iterate(initial value, next value)
Stream.iterate(1,n->n+1).limit(10).forEach(i->System.out.print(i*i+" "));
}
}
Output:-
1 4 9 16 25 36 49 64 81 100
1 4 9 16 25 36 49 64 81 100
Note:-
- Here we use two ways to generate series.
- You can use any one But the best is using Stream API It will work JDK 1.8 or after all versions of java.
- It will not work JDK 1.7 or before versions.