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.

advertisement
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

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..

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn