Average of two double numbers – Computer Sir Ki Class

Code Learning #JAVA#573

Average of two double numbers

Finding average of two double numbers.

Learning Objectives

To learn java concepts related to :

• Initializing variables dynamically.
• Variations while passing arguments in println() method.

Program Approach

The objective is to demonstrate the dynamic initialization of variables.

We will be firstly declaring two variables with their initial values. Then we be dynamically initializing the third variable with the average of the above values.

Source Code

 class Average { public static void main (String[] args) { double num1=23.5; double num2=12.5; double avg=(num1+num2)/2; System.out.println("Average of "+ num1+" and "+ num2+" is : "+avg); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

Run Output

``Average of 23.5 and 12.5 is 18.0``

Code Understanding

double avg=(num1+num2)/2;

Here, we have dynamically initialized the variable avg with the average of the values stored in the variables num1 and num2. Since we were not sure whether the average would be an integer or a decimal number so we have declared it with double data type. If you have declared any expression in double data type and its value comes out to be a perfect integer then also the double data type will add .0after that integer so that it may also become a decimal number.

System.out.println(“Average of “+
num1+” and “+
num2+” is : “+avg);

This statement has been written in three different lines in order to demonstrate that within println() method we can terminate a statement and start it from the next line only after a +operator.

Suggested Filename(s): Average.java

admin| Created: 16-Aug-2016 | Updated: 21-Mar-2018|

×