Share on Google+Share on Google+

Java number calculation using while loop

Advertisement
In this tutorial, you will learn how to use while loop to solve certain number calculations.

Java number calculation using while loop

In this tutorial, you will learn how to use while loop to solve certain number calculations. Here is an example that prompts the user to input two integers : FirstNum and secondNum.( FirstNum must be less than secondNum.) and output all the odd numbers between firstNum and secondNum inclusive. It also find the sum of all the even numbers between FirstNum and secondNum inclusive and display all the numbers and their squares between 1-10. Moreover, it also calculates the sum of the squares of all the odd numbers between firstNum and secondNum inclusive.

Example:

import java.util.*;
public class NumberExample{
public static void main(String[]args){
int sum=0,sumSquares=0;
int num1=0,num2=0;
Scanner input=new Scanner(System.in);
System.out.print("Enter First Number: ");
num1=input.nextInt();

System.out.print("Enter Second Number: ");
num2=input.nextInt();

if(num1>num2){
System.out.print("Your First Number is greater than second.So Please re-enter: ");
num1=input.nextInt();
}
else{
System.out.println("Odd Numbers: ");
while(num1 <= num2) {
if(num1%2 != 0) {
System.out.println(num1);
sumSquares+=(num1*num1);
}
if(num1%2 == 0) {
sum+=num1;
}
num1++;
}
System.out.println("Sum Of Even Numbers: "+sum);
System.out.println("Numbers and their squares between 1 and 10");
int i=1;
while(i <= 10) {
System.out.println(i+" "+(i*i));
i++;
}
System.out.println("Sum Of square of odd Numbers: "+sumSquares);
}
}
}

Output:

Enter First Number: 4
Enter Second Number: 20
Odd Numbers:
5
7
9
11
13
15
17
19
Sum Of Even Numbers: 108
Numbers and their squares between 1 and 10
1    1
2    4
3    9
4    16
5    25
6    36
7    49
8    64
9    81
10    100
Sum Of square of odd Numbers: 1320

Advertisements

Advertisement

Posted on: December 15, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.