Part 1 Write a program that will compute the sum of the firs

Part 1:

Write a program 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. Use for loop to implement the project. The program accept integer n from keyboard.

Part2:

Rewrite the program by using the while loop.

Solution

Answer :

Part 1:

Write a program 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. Use for loop to implement the project. The program accept integer n from keyboard.

Answer :

import java.util.*;

import java.lang.*;

import java.io.*;

import java.util.scanner;

class SumInteger
{
   public static void main (String[] args) throws java.lang.Exception
   {
        int n,
        number = 1,
        sum = 0;
        System.out.print(\"Enter an Integer n :\");
        n =input.nextInt();
        for(int i = 0; i < n; i++)
        {
          sum += number;
          number += 2;
         }
        System.out.println(”Sum of 1st ” + n + ” positive odd integers is: ” + sum);
   }
}

              (or)

import javax.swing.*;
public class SumInteger

{
      public static void main(String[] args)

     {
           int n , number = 1,sum = 0;

       n=Integer.parseInt(JOptionPane.showInputDialog(“Enter Positive Number: “));
           for(int i = 0; i < n; i++)

          {
              sum += number;
              number += 2;
            }

             JOptionPane.showMessageDialog(null,”Sum of 1st ” + n + ” positive odd integers is: ” + sum);

       }

}

......................

Part2:

Rewrite the program by using the while loop.

Answer :

import java.util.*;

import java.lang.*;

import java.io.*;

import java.util.scanner;

class SumInteger
{

public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
         int n,
        number = 1,
        sum = 0;
        System.out.print(\"Enter an Integer n :\");
        n =input.nextInt();
        int i=0;
        while(i < n)
        {
          sum += number;
          number += 2;
          i++;
         }
       
        System.out.println(”Sum of 1st ” + n + ” positive odd integers is: ” + sum);
    }
}
    ..........................................

Part 1: Write a program 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. Use for loop
Part 1: Write a program 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. Use for loop

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site