W.A.P to input 5 numbers. Display the sum of even and odd numbers using for loop in JAVA
Answers
Answer:
import java.util.Scanner;
class OddEvenSum{
public static void main (String args[]){
int i,num; //declare variable i,num
int oddSum=0,evenSum=0;
//declare and initialize variables oddSum,evenSum
Scanner scan=new Scanner(System.in);
//create a scanner object for input
System.out.print("Enter the number for num: \n");
num=scan.nextInt();//reads num1 from user
for(i=1; i<=num; i++){
if(i%2==0)
evenSum=evenSum+i;
else
oddSum=oddSum+i;
}
System.out.println("Sum of all odd numbers are: "+oddSum);
System.out.println("Sum of all even numbers are: "+evenSum);
}
}
output:
Enter the number for num:
10
Sum of all odd numbers are: 25
Sum of all even numbers are: 30
Question:-
- Input 5 numbers and display even and odd numbers using for loop in Java
Answer:-
package Coder;
import java.util.*;
public class EveOdSum
{
public static void main (String ar [])
{
Scanner sc = new Scanner (System.in);
int I,e=0,o=0;
for(I=1;I<=5;I++)
{
System.out.println("Enter a number");
int n=sc.nextInt();
if(n%2==0)
e+=n; //Calculation of even numbers
else
o+=n; //Calculation of odd numbers
}
System.out.println("Even Sum:"+e+"\nOdd Sum:"+o);
}
}
_________________________
Variable Description:-
- I:- loop variable
- n:- to accept numbers as input from the user
- e:- to find the sum of even numbers
- o:- to find the sum of odd numbers
_________________________
Code Explaination:-
- The program runs a loop from 1 to 5
- In each iteration, it accepts a number as input from the user
- if the number is even then it calculates the sum and store it in variable 'e', if not even, then it stores the sum in variable 'o'.
- Once Loop value becomes greater than 5, Loop terminates
- Finally, Program ends.