Write a Java Program to find the Sum Of Odd Numbers from Given range
Input: 5 to 22
output: 117
output: 117
import java.util.Scanner; public class SumOfOddNumbers { public static void main(String[] args) { Scanner scan = new java.util.Scanner(System.in); System.out.println("Enter the starting number: "); int n1=scan.nextInt(); System.out.println("Enter the end number: "); int n2=scan.nextInt(); int sum=0; for(int i=n1; i<=n2; i++) { if(i%2!=0) { System.out.println(i); sum=sum+i; } } System.out.println("Sum of Odd Numbers from given range: "); System.out.println("= "+sum); } }Output:
Enter the starting number:
20
Enter the end number:
30
21
23
25
27
29
Sum of Odd Numbers from given range:
= 125
No comments:
Post a Comment
If you have any doubts, please let me know