Find the square of first n natural numbers using method in java language.

import java.util.*;

class Main
{
    public static void main(String[] args) 
{
     Scanner sc=new Scanner(System.in);
       System.out.print("enter the value to find.             square of first n natural numbers=");
     int n=sc.nextInt();

// create a object 
                      Find obj=new Find();

// calling method
                      obj.square(n);
    }
}

class Find
{
    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);
       }
    }
}

■》Output->

enter the value to find square of first n natural numbers=10

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
the square of 9 is=81
the square of 10 is=100

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.