Biyernes, Setyembre 20, 2013

LabExer#14

14. Write a for statement to compute the sum 1 + 2² + 3² + 4² + 5² + ... + n².




import javax.swing.JOptionPane;

public class TheSum{   
    public static void main(String[] args){
           
        int a=1,b=2,n,num=0,total=0;

        n=Integer.parseInt(JOptionPane.showInputDialog("How many odd integers do you want to display? "));
       
        for (int i=0;i<n;i++){
        num=a*a;
        System.out.print(a + "² + ");
        a=a+b;
        total=total+num;       
        }   
        System.out.println(" ");
        System.out.println("The sum is: "+total);       
    }
}

Walang komento:

Mag-post ng isang Komento