Computer Science, asked by Monkiko, 4 months ago

W.A.P to input 5 numbers. Display the sum of even and odd numbers using for loop in JAVA​

Answers

Answered by ankitamoharana80
1

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


Monkiko: Can you tell without using scanner class too?....but still thanks for the answer :)
BrainlyProgrammer: Hello @Monkiko Scanner Class is used to accept input from the user
BrainlyProgrammer: as you can see in my answer "Scanner sc=new Scanner(System.in);" here sc is the object created by the Scanner Class and to input sc.nextInt()
BrainlyProgrammer: is used
Answered by BrainlyProgrammer
3

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

  1. I:- loop variable
  2. n:- to accept numbers as input from the user
  3. e:- to find the sum of even numbers
  4. 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.

________________________

•Output Attached

Attachments:
Similar questions