JAVA Control Statements
The if-else Statement
Java if-else statement works much like the IF statement in any other
language. Here, condition is a
Boolean expression. If condition is true, then the statement is executed.
If condition is false, then the statement is bypassed.
Switch Statement
switch statement is Java’s multiway branch statement. It provides an
easy way to
dispatch
execution to different parts of your code based on the value of an expression.
As
such, it often provides a better alternative than a large series of if-else-if
statements.
The for Loop
The for Loop
for(initialization; condition;
iteration) {
// body
}
The While Loop
while(condition) {
// body of loop
}
The do-while Loop
The do-while Loop
do {
// body of loop
} while (condition);
Prorgam # 1
java
program finds factorial of a number. Entered number is checked first if its
negative then an error message is printed.
public class
Factorial
{
public static void main(String args[])
{
int n=10, c, fact = 1;
if ( n < 0 )
System.out.println("Number should
be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of
"+n+" is = "+fact);
}
}
}
Output:
Math Classes
Math class contains all the floating-point functions that are used for
geometry and trigonometry, as well as several general-purpose methods. Math defines
two double constants: E (approximately 2.72) and PI (approximately
3.14).
The
Java Math library function Math.random() generates a double value in the range [0,1). Notice
this range does not include the 1.
import java.lang.Math;
public class MathDemo
{
public static void main(String[] args)
{ double num = -4876.1874d;
double x=10.0,y=20.0;
int max=15;
// print absolute value of num
System.out.println("\nMath.abs(" + x + ")= " + Math.abs(num));
// print square root value of x
System.out.println("\nMath.sqrt(" + x + ")= " + Math.sqrt(x));
// print power value of x
System.out.println("\nMath.pow(" + x + ")= " + Math.pow(x,y));
// print exponential value of x
System.out.println("\nMath.exp(" + x + ")= " + Math.exp(x));
// print sine value of x in radian
System.out.println("\nMath.sin(" + x + ")= " + Math.sin(x));
// print maximum value
System.out.println("\nMath.max(" + x + ")= " + Math.max(x,y));
// print random value
System.out.println("\nMath.random()= " +(Math.random());
}
}
Output:
No comments:
Post a Comment