3 Arrays, Conditions and Loops




Arrays
Thus Arrays in java are actual objects that can be passed around and treated just like other objects.  Arrays can contain any type of value (base types or objects) but you cant store different types in a single array.  Hence Arrays are can be defined as the set of related data stored in a single variable.  There are three steps to create an array in Java.
1)                  Declare a variable to hold the array.
2)                  Create a new array object and assign it to be the array variable.
3)                  Store things in that array.

Declaring Array Variables
The first step to creating an array is creating a variable that will hold the array, just as you would any other variables.  Array variables indicate type of object array will hold, and the name of the array, followed by empty brackets( [  ] ).

For example:
Point hits ( [ ] );
Int temps ( [ ] );

Creating array objects
There are two ways of achieving this:

1)                  Using new. 
For example :
String [] names = new String[10];
When you create an array object using new, all its elements are initialized for you. ( 0 for numeric arrays, false for Boolean, ‘\0’ for character arrays, and null for everything else).

2)                  Directly initializing contents of that array.
We can also create and initialize an array at same time.
For example:
String[ ] cities ={“Mumbai”, “Delhi”, “Madras”, “Calcutta”};

Block Statements
A block statement is a group of other statements surrounded by braces ( { } ).  You can use a block anywhere a single statement would go, and the new block creates a new local scope for the statements inside it.  This means that you can declare and use local variables inside a block, and those variables will cease to exist after the block is finished executing.  

For example in the following example a block is inside a method definition that declares a new variable y.   You can not use y outside the block in which it is declared.

void testblock( ){
int x =10;
{
 // block starts
int y = 50;
System.out.println(“Inside the block”);
System.out.println(“ X ” + x);
System.out.println(“ Y ” + y);
    }// Block Ends;
}

Control Flow Statements

If Conditions
The if conditional, which enables you to execute different bits of code based on a simple test in java, is nearly identical to if statements in C language.
For example:
if (x>y)
System.out.println( “X is Greater than Y”);
The optional else keyword provides the statement  to execute if the test is false.
For example:
if( x>y)
System.out.println(“ X is Greater than Y”);
else
System.out.println(“ Y is Greater than X”);

Example 1(Testing If)
class IfClass{
public static void main(String args[]){
int a=50;
int b=100;
int c;
if (a>b){
c=a-b;
System.out.println("After Deducting B From A" + c);
}
if (b>a){
c=b-a;
System.out.println("After Deducting A From B" + c);
}
}
}

Switch Condition
The switch or case statements is an alternative to nested ifs.  It behaves as it does in C.
switch (test){
case valueone:
resultOne;
break;
case valueTwo;
resultTwo;
break;
}

Example 2(Testing Switch)
 class Signals {
   public static void main(String[] args) {
       int colors = 3;
      String Signal;         
      switch (colors) {
         case 1:
           Signal = "Yellow";
           break;
         case 2:
           Signal = "Red";
               break;
         case 3:
           Signal = "Green";
           break;
       default:
           Signal = "Invalid Signal";
           break;
      }
      System.out.println(Signal);
   }
}

for Loops
The for loop, as in C repeats statements or block of statements some number of times until a condition is matched.  For loops are frequently used for simple iteration in which you repeat a block of statements a certain number of times and then stop.  But you can use for just any kind of loop.

Syntax: For (initialization; test; increment){
statements;
}

For example
String strArray [ ] = new String[10];
int i;
(for I =0; i<=strArray.length; i++)
{
strArray[i] = “ “;
}

while Loop
while and do loops, like for loops, enable block of Java code to be executed repeatedly until specific condition is met.
Syntax: while(condition){
statements;
-          - - - -
-          - - - -
}

do…while Loop
do-while loop works similar to the while loop except that do-while loop executes at least once even if the condition is not true.
Syntax:
do{
statements;
-          - - - -
-          - - - -
} while(condition);

Breaking out of Loops
In all the loops, the loop ends when the condition you are testing, is met.  If something odd occurs within the body of the loop and if you want to exit the loop early use break keyword.  In switch statement we use break to stop the execution of the switch.  The break keyword when used with a loop, does the same thing, it immediately stops execution of current loop and the program merely continues executing next statement after the loop.

Practical Examples


Example 1

A program to generate integers between 1 and N that are divisible by D, where N and D are to be given as command line Arguments.

class Multiples{
public static void main(String [] args){
int value,divisor,val,div;
if(args.length==0){
System.out.println("USage : java Multiples are ");
System.exit(0);
}
else{
System.out.print("Program generates Integers Between ");
val=Integer.parseInt(args[0]);
div=Integer.parseInt(args[1]);
System.out.println(" 1 to " + val + " Divisible by " + div);
if(val<1)
System.out.println("Value Can not be Less than one ");
if(div<1)
System.out.println("Value Can not be Less than one ");
else{
System.out.println("\t");
for(int i=1;i<=val;i++)
if((i%div)==0)
System.out.print(i +"\t");
}
}
}
}

Example 2
A program to calculate maximum height reached by a ball that is thrown perpendicular from ground surface at a velocity of 20 mats/sec.

import java.io.*;
class Height{
public static void main(String [] args){
final double GraAcc = 9.8;
double velocity =0,time=0,height=0;
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
System.out.println(" ");
System.out.println("Calculating Distance Traversed By a Ball ");
System.out.print("********************************************** ");
try{
System.out.println("\n");
System.out.println("Enter value for The Valocity  ");
velocity=Double.valueOf(br.readLine( )).doubleValue( );
System.out.println("Enter value for Time To Reach that Height ");
time=Double.valueOf(br.readLine( )).doubleValue( );
height=velocity*time+(0.5*GraAcc*time*time);
}
catch(IOException ioe){
System.out.println("\n");
System.out.println("Input Exception Caught  "+ ioe);
}
System.out.print("The Height Reached By the Ball is " + height+" Metrees.");
System.out.println(" ");
}
}

Example 3 Fibonacci Series
import java.io.*;
import java.text.*;
class Fibonacci{
  public static void main(String [] args){
            InputStreamReader isr= new InputStreamReader(System.in);
            BufferedReader br= new BufferedReader(isr);
            int last=1,next=1,sum=0,num;
            try{
            System.out.println(" ");
            System.out.println("Enter length up to which calculation is to be done  ");
            num=Integer.parseInt(br.readLine( ));
            System.out.println(" ");
            System.out.println("Fibonacci Series up to number  "+ num);
            System.out.print(last+"\t" + next);
            int i =0;
            while(i<num){
            sum=last+next;
            System.out.print("\t"+sum);
            last=next;
            next=sum;
            i++;
            }
}
              catch(IOException ioe){
            System.out.println("Input Exception Caught  "+ ioe);
            }
   }                  
}

Example 4 Array Program
class Arrey
{
String[] firstname={"Sandhya","Devender","Arti","Leela","Seema"};
String[] lastname= new String[firstname.length];
void printname( )
{
int i=0;
System.out.println(firstname[i] + " "+lastname[i]);
i++;
System.out.println(firstname[i]+" " +lastname[i]);
i++;
System.out.println(firstname[i]+" " +lastname[i]);
i++;
System.out.println(firstname[i]+" " +lastname[i]);
i++;
}
public static void main(String arguments[])
{
Arrey a =new Arrey( );
a.printname( );
System.out.println(".......");
a.lastname[0] ="Chatarji";
a.lastname[1] = "Upadhyay";
a.lastname[2] = "Prabhu";
a.lastname[3] = "Day";
a.lastname[4] ="Madhavi";
a.printname( );
}
}

Example 5 IfElse Construct
Class ifelse{
public static void main(String arguments[])
{
int a =10;
if(a%2 ==0)
System.out.println(a + "is even Number “);
else
System.out.println(a + "is Odd Number “);
   }
}

Example 6 Do Loop
class DoLoop{
 public static void main (String arguments[]){
 int x = 1 ;
do{
System.out.println("Looping,Round"+ x);
x++;
}
while(x<=10);
}
}

Example 7 While Loop
class WhileDemo{
public static void main (String arguments[] )
{
int a=10, count =0;
while ( a<=20)
{
System.out.println("a = “ + a + “\t");
count++;
a++;
}
System.out.println("While Loop Executed" + count + “times”);
}
}

Example 8 For Loop
class ForDemo{
public static void main (String arguments[] )
{
for(int i=1; i<=5 ; i++)
System.out.println("Value of I is ” + i);
}
}

Example 9 Switch Construct
class Month {
   public static void main(String[] args) {
      int mmonth = 12;
      String month;
                   
      switch (mmonth) {
         case 1:
           month = "January";
           break;
         case 2:
           month = "February";
               break;
         case 3:
           month = "March";
           break;
         case 4:
           month = "April";
           break;
        case 5:
          month = "May";
           break;
         case 6:
           month = "June";
           break;
         case 7:
           month = "July";
      break;
  case 8:
           month = "August";
           break;
case 9:
              month = "September";
           break;
case 10:
           month = "October";
           break;
case 11:
           month = "November";
           break;
case 12:
           month = "December";
           break;
          default:
           day = "Invalid day";
           break;
      }
      System.out.println(month);
   }
}

No comments:

Post a Comment