204k views
2 votes
Write a java program that finds the sum of all even numbers between 1 and 55.

Also what modification would you do to the program if you wanted the sum of all odd numbers between 1 and 55

User Zia Yamin
by
8.4k points

1 Answer

3 votes

Answer:

For sum of even Number :

public class even{

public static void main(String []args){

int sum = 0;

for(int i=1;i<=55;i++){

if(i%2==0){

sum = sum + i;

}

}

System.out.println(sum);

}

}

Modification for sum of odd:

change the condition of if statement:

i%2==1 instead of i%2==0

Step-by-step explanation:

create the main function and declare the variable with zero.

Then, take a for loop for traversing the number from 1 from 55.

Inside the for loop, if statement check the condition for even number

A number is even if number divide by 2 and give zero reminder.

so, number%2==0 it is the condition for even number.

then add the even number until condition TRUE.

and finally print the result.

Modification for sum of odd number:

A number is odd, if number divide by 2 and give one reminder.

it means, number%2==1 it is the condition for odd number.

just change the if condition with above.

User Arjun T Raj
by
7.3k points