Function to print squares of the first n natural numbers, taking n as an argument to the method.

 import java.util.*;

class Square{

    public static void square(int x){

        int sq;

       for(int i=1; i<=x; i++){

        sq=i*i;

        System.out.println("the square of "+i+" is = "+sq);

       }

    }

    public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

System.out.print("enter the value of n=");

int n=sc.nextInt();

square(n);

    }

}


■》 Output->

enter the value of n=8

the square of 1 is = 1

the square of 2 is = 4

the square of 3 is = 9

the square of 4 is = 16

the square of 5 is = 25

the square of 6 is = 36

the square of 7 is = 49

the square of 8 is = 64


Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.