Java Program to Print the First n Square Numbers

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.

  1.  
  2. //Java Program to Print the First n square Numbers
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6.  
  7. public class PrintNSquareNumbers {
  8.     // Function to read n and display the numbers
  9.     public static void main(String[] args) {
  10.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11.         int n;
  12.         System.out.println("Enter the value of n");
  13.         try{
  14.             n = Integer.parseInt(br.readLine());
  15.         }catch (Exception e){
  16.             System.out.println("An error occurred");
  17.             return;
  18.         }
  19.         if(n<=0){
  20.             System.out.println("n should be greater than zero");
  21.             return;
  22.         }
  23.         System.out.println("First " + n + " square numbers are ");
  24.         int i;
  25.         for(i=1; i<=n; i++){
  26.             System.out.print(i*i + " ");
  27.         }
  28.     }
  29. }
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
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..

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.