Reputation:
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
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