Thursday, August 21, 2014

Sum first n positive odd integers

 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 LabExercise13 {
   
    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;
                    count++;
                }        
        }
        JOptionPane.showMessageDialog(null,"Sum of: "+b +"\nis: " +a);
    }
}

No comments:

Post a Comment

advertisement