Skip to main content

Posts

Showing posts with the label 8. Write a Java program to find sum of all odd numbers between 1 to n.

ads1

8. Write a Java program to find sum of all odd numbers between 1 to n.

8. Write a Java program to find sum of all odd numbers between 1 to n. Static :-   class loop8 { public static void main(String args[]) { int i=1,n=20,sum=0; while(i<=n) { if(i%2!=0) sum = sum + i; i++; } System.out.println(sum); } } Output :-  Dynamic :-  import java.util.*; class loop8 { public static void main(String args[]) { Scanner in = new Scanner(System.in); int i,j,sum=0; System.out.println("Enter the First number:- "); i=in.nextInt(); System.out.println("Enter the Last number:- "); j=in.nextInt(); while(i<=j) { if(i%2!=0) sum =sum +i; i++; } System.out.println(sum); } } Output :-  

ads2