user9771132
user9771132

Reputation:

What is wrong with this program?I need to find addition of all the odd numbers and even numbers using while

I need to find sum of even and odd numbers from 0 to 50 using While Statement,here is my code During runtime..I do not get any output from the compiler ..Help please

import java.util.Scanner;
class Odd_Even
public static void main(String args[])
{

    int i = 1, j = 1, oddsum = 0, evensum = 0;

    while (i <= 50) {
        if (i % 2 == 0) {
            evensum = i + evensum;
            i = i + 1;
        }
    }
    System.out.println("Answar of the Even number is=" + evensum);

    while (j <= 50){
        if (j % 2 == 1){
            oddsum = j + oddsum;
            j = j + 1;
        }
    }
System.out.println("sum of odd number is="+oddsum);


}

}

Upvotes: 0

Views: 58

Answers (1)

rmlan
rmlan

Reputation: 4657

You need to take the lines that increment your loop variables out of your if statements. Otherwise the loop variables will never be incremented:

while (i <= 50) {
    if (i % 2 == 0) {
        evensum = i + evensum;
    }
    i = i + 1;
}
System.out.println("Answar of the Even number is=" + evensum);

while (j <= 50){
    if (j % 2 == 1){
        oddsum = j + oddsum;
    }
    j = j + 1;
}

This problem could have been found rather easily if you attached a debugger to your program and stepped through the code. Step-through debugging is an invaluable tool that every developer should know how to use!

Upvotes: 2

Related Questions