How to add 'n' amount of odd integers?

  • A+
Category:Languages

I'm trying to write a program that computes the sum of the first n positive odd integers.

I'm having trouble figuring out how to incorporate n into finding the sum. I already have a do/while loop to ensure I get a positive value when assigning n value. I know that I have to use a for loop but I'm not really sure how I would do that.

Scanner input = new Scanner(System.in); // open input stream     String cleanUpStr;                      // clean kbd buffer     int n;                                  // number     int sum;                                // sum of numbers     int cntr;                               // counter for loop      cleanUpStr = "nothing yet";     n = 0;     sum = 0;     cntr = 0;      //prompt user for the value of n     // use a loop to ensure a positive output     do     {         System.out.println("Enter the value of n");          n = input.nextInt();         cleanUpStr = input.nextLine();          // print error if n is invalid         if (n < 0)         {             System.out.println("Invalid n value of " + n + ", try again.");         } // end if      }while(n < 0);      for(cntr = 0; cntr < n; ++cntr)     {       } // end for     } // end main 

For example: if n = 5, then this should compute 1 + 3 + 5 + 7 + 9.

 


Stream is good, but if you're a beginner a plain old for loop is your best friend.

public static int sumForOddNumbers(int total) {     int sum = 0;      for(int i = 0, odd = 1; i < total; i++, odd += 2) {         sum += odd;     }      return sum; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: