This is the Java Program to Print the First n square Numbers.
Problem Description
Given an integer says n, write a java program to print the first n squared numbers.
Problem Solution
Iterate through the loop from 1 to n and print the square of the loop variable.
Program/Source Code
Here is the source code of the Java Program to Print the First n square Numbers. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Print the First n square Numbers
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PrintNSquareNumbers {
// Function to read n and display the numbers
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("Enter the value of n");
try{
n = Integer.parseInt(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
if(n<=0){
System.out.println("n should be greater than zero");
return;
}
System.out.println("First " + n + " square numbers are ");
int i;
for(i=1; i<=n; i++){
System.out.print(i*i + " ");
}
}
}
Program Explanation
In the function main(), first, an integer say n is entered and then using the loop for(i=1; i<=n; i++) the first n squared numbers are displayed.
advertisement
Time Complexity: O(n).
Runtime Test Cases
Case 1 (Simple Test Case): Enter the value of n 15 First 15 square numbers are 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225
Sanfoundry Global Education & Learning Series – Java Programs..
Related Posts:
- Practice Programming MCQs
- Apply for Java Internship
- Check Programming Books
- Practice Information Technology MCQs
- Practice BCA MCQs