Write a for statement to compute the sum 1 + 2² + 3² + 4² + 5² + ... + n².
import javax.swing.JOptionPane;
public class LabExercise14 {
public static void main(String[] args) {
String b = "";
int a = 0;
int n;
int count=0;
n = Short.parseShort(JOptionPane.showInputDialog("Enter an integer: "));
for (int i=0;count<n;i++){
if(i%2!=0){
b = b + " " + i;
a+=i*i;
count++;
}
}
JOptionPane.showMessageDialog(null,"Sum(square) of: "+b +"\nis: " +a);
}
}
import javax.swing.JOptionPane;
public class LabExercise14 {
public static void main(String[] args) {
String b = "";
int a = 0;
int n;
int count=0;
n = Short.parseShort(JOptionPane.showInputDialog("Enter an integer: "));
for (int i=0;count<n;i++){
if(i%2!=0){
b = b + " " + i;
a+=i*i;
count++;
}
}
JOptionPane.showMessageDialog(null,"Sum(square) of: "+b +"\nis: " +a);
}
}
No comments:
Post a Comment