Write a java program to find the sum of all odd numbers between 1 to n - using do...while loop
import java.util.Scanner;
class Main {
public static void main(String[] args) {
//Write a java program to find the sum of all odd numbers //between 1 to n - using do...while loop
Scanner cin=new Scanner(System.in);
System.out.print("Please enter n:");
int n=cin.nextInt();
int sum=0;
//out summ all od numbers using do[]while
//n--;
do
{
n--;
if(n==1)
break;
if(n%2==1)//if current num is odd
sum+=n;
}while(n!=1);
System.out.println("Sum al odd numbers:"+sum);
}
}
Comments
Leave a comment