13. Write a fragment of code that will compute the sum of the first n positive odd integers. For example, if n is 5, you should compute 1 + 3 + 5 + 7 + 9.
import javax.swing.JOptionPane;
public class OddIntegers{
public static void main(String[] args){
int a=1,b=2,n,num=0;
n=Integer.parseInt(JOptionPane.showInputDialog("How many odd integers do you want to display? "));
for (int i=0;i<n;i++){
System.out.print(a + " + ");
a=a+b;
num=n*n;
}
System.out.println(" ");
System.out.println("The sum of all odd integers is: "+num);
}
}
Walang komento:
Mag-post ng isang Komento