Archive for August, 2013


Continuing the previous lecture of alternate formats,today we will print the table of a number using TERNARY Operator.We are taking the same example again and again so that it would be easy for us to understand the various methods that can be applied to accomplish the very same task so that if in future we get struck at some point then we are easily able to get out of it successfully.

package Loops_Iterators;

/**
*
* @author aprimit
*/
import java.util.Scanner;

public class table_ternary {

public static void main(String[] args) {

System.out.println(“This program illustrates the for loop…..”);
System.out.println(“Let us print table of a number with proper allignment….”);
Scanner inputno;//reference variable
inputno = new Scanner(System.in);
int i, n;
n = inputno.nextInt();
for (i = 1; i <= 10; i++) {
int m = n * i;
System.out.println((m < 10 ? “0” + m : m));//use of ternary operator..
}
}
}

OUTPUT : This program illustrates the for loop…..

Let us print table of a number with proper allignment…

3

03

06

09

12

15

18

21

24

27

30

Poly forms of FOR loop…

Since we have covered for loop recently,i want to mention some of its analogous formats.

package Loops_Iterators;

/**
*
* @author aprimit
*/import java.util.Scanner;
public class For_alternative {

public static void main(String[] args) {
System.out.println(“This program makes use of a different format of the ‘FOR’ loop…”);
System.out.println(“Let us print the series of odd numbers….”);
Scanner input=new Scanner(System.in);
System.out.println(“Enter the number till which you want to print the odd number series..”);
int m, i = 1, n = input.nextInt();

for (; i <= n;) {  //only condition is specified in the brackets
m = (2*i)-1;
System.out.println(“The format used is similar to that of ‘While’ loop…”);
System.out.println(m);
i++;
}

}

}

OUTPUT : This program makes use of a different format of the ‘FOR’ loop…

Let us print the series of odd numbers….

Enter the number till which you want to print the odd number series.. 20

1

3

5

7

9

11

13

15

17

19

Lets have a look at another one…

package Loops_Iterators;

/**
*
* @author aprimit
*/
import java.util.Scanner;

public class table_for_alternate {

public static void main(String[] args) {
System.out.println(“This program prints the table of a number…”);
System.out.println(“Using alternative ‘for’ syntax….”);
System.out.println(“Enter the number whose table you want to print..”);
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 1; i <= 10; System.out.println(n * (i++))){}
}
}

OUTPUT : This program prints the table of a number…

Using alternative ‘for’ syntax….

Enter the number whose table you want to print..4

4

8

12

16

20

24

28

32

36

40

However,the alignment in the last program is not proper but the main purpose of the program is to illustrate alternate formats of the ‘for’ loop.

In the last session if u had noticed carefully,when we started printing the table of a desired number (e.g- 9 in previous example) the first calculation i.e 9*1=9 was not aligned properly….
so today we will fix it…Watch.!

package Loops_Iterators;

/**
* @author aprimit
*/
import java.util.Scanner;

public class table_alligned {

public static void main(String[] args) {
System.out.println(“This program illustrates the for loop…..”);
System.out.println(“Let us print table of a number with proper allignment….”);
Scanner inputno;//reference variable
inputno = new Scanner(System.in);//memory allocation
int i, n;
System.out.println(“Enter the number: “);
n = inputno.nextInt(); //converting the input from String to Int
for (i = 1; i <= 10; i++) {
int m = n * i;
if (m < 10) {
System.out.println(“0” + m);

} else {

System.out.println(m);

}
}
}
}

OUTPUT: This program illustrates the for loop…..

Let us print table of a number with proper allignment….

Enter the number:9

09

18

27

36

45

54

63

72

81

90

JAVA FOR loop insight…

After the detailed study of the FOR loop, we shall move on to its code….but before that lets have a look at the crux of the last session.

package Loops_Iterators;

/**
*
* @author aprimit
*/
import java.util.Scanner;

public class For_loop {

public static void main(String[] args) {
System.out.println(“This program illustrates the ‘for’ loop…..”);
System.out.println(“Let us print table of a number….”);
Scanner inputno;//reference variable
inputno = new Scanner(System.in);//memory allocation
int i, n;
n = inputno.nextInt();
for (i = 1; i <= 10; i++) {
int m = n * i;
System.out.println(m);
}
System.out.println();
}
}

OUTPUT :This program illustrates the ‘for’ loop…..

Let us print table of a number….

9

9

18

27

36

45

54

63

72

81

90

Loops continued…

FOR Loop

The first loop we’re going to look at is the for loop. Both Pascal and Basic have for loops, as do C and C++. Like those languages, the for loop in Java is designed for writing counted loops–loops that repeat a specified number of times.

Unlike the Pascal or Basic for loop, however, the for loop in Java can do much more than simple counted loops. The for loop in Java works almost exactly like the for loop in C++; it is a general purpose, “test at the top” loop, that makes writing counted loops very straightforward, but can be used for other purposes.

Syntax

As mentioned previously, the body of the for loop follows the loop’s test condition; you test first, then, if the test evaluates to true, you enter the loop body, as you can see in the illustration. [click image to enlarge]

Image illustrates the for loop syntax.

The for loop’s condition involves more than a simple boolean test, however. In fact, it involves three different expressions:

  • The initialization expression
  • The test expression
  • The update expression

Each of these three expressions is separated from the others by a semicolon. You can omit any–or all–of the expressions, but the semicolons are required. [Make sure that you don’t accidentally use commas instead of semicolons. When you do so, the javac compiler is not particularly helpful with its error messages]

The loop body following the loop condition is usually enclosed in braces, although, technically, braces are not required if the loop body consists of a single statement. As a practical matter, though, you’ll almost always use braces, and, since they don’t hurt–even when not strictly required–you should always put them in as a matter of course.

Let’s return to the for loop condition, and take a closer look at each of its three expressions.

Back to Top

The Initialization Expression

When a for loop is encountered, the first part of the loop condition, the initialization expression, is executed. It is always executed, regardless of the other parts of the for statement, almost as if it occurred on the previous line.

The initialization expression is evaluated only once, and is usually used to define the counter variable that will control your loop, like this:

The for Loop Initialization Expression
for (int counter = 0; ... ; ...)
{
   // Can use counter here
}
// Cannot use counter here

Variables declared inside the for loop initialization section, like counter, shown here, are local to the body of the for loop. Once the loop is finished, the variable goes out of scope and can no longer be used.

The boolean Test

The second section of the for loop is called the test condition. The test condition is a boolean expression which is evaluated immediately after the initialization expression.

If the test condition is true, [when it is evaluated], then execution begins with the first statement in the loop. If it is false, then the entire loop body is skipped, and execution continues at the first statement following the loop body.

To continue our example, we can test the value of counter, checking to make sure it is less than ten:

The for Loop Test Expression
for (int counter = 0; 
    counter < 10 ; ...)
{
   // Can use counter here
}
// Cannot use counter here

Using counter like this insures that the loop will execute ten times. This is a common idiom in Java programming:

  • start counter at 0
  • test that counter is less than the upper bounds

An idiom is just a common and widely accepted way of “phrasing” a particular operation. This particular idiom works well, because you can immediately tell how many times the loop will execute just by glancing at the test condition.

The Update Expression

In Lesson 6.1, “Introduction to Loops”, you learned to make sure that every repetition of a loop moves closer to the loop bounds. But, in the for loop shown here, there are nostatements that move toward the bounds; in fact, as written, this example is an endless loop! Since counter is never updated, it always remains at zero.

Updating the counter is the responsibility of the third part of the for loop condition–the update expression. The update expression is evaluated after the body of the loop is finished, but before the test expression is evaluated for the next repetition.

For a counted loop, you’ll use the test expression to update your counter like this:

The for Loop Update Expression
for (int counter = 0; 
     counter < 10 ; 
     ++counter)
{
   // Can use counter here
}
// Cannot use counter here

Counting Variations

You’ve probably noticed that this loop doesn’t really do anything; the portion that we’ve written simply repeats ten times. However, you can use this basic skeleton for any loop that needs to repeat a fixed number of times. Simply replace 10 with the number of times you want to repeat, and you’re all set.

In addition to acting as a loop control, you can also use your counter variable to process different pieces of information during each repetition of the loop. Here, for instance, is a loop that sums the Unicode values for all the characters in a String:

Using the for Loop
String s = myTF.getText();
int nChars = s.length();
int sumOfCodes = 0;for (int counter= 0; counter < nChars ; ++counter)
{
   sumOfCodes += s.charAt(counter);
}myTF.setText("Sum of codes = " + sumOfCodes);How much is your name worth? Type your name into the text area shown below, and press ENTER. The applet shown here [SumOfCodes.java] will total up the Unicode values for each of the characters in your name, and display your “weight” in Unicode.

Counting Down

When you create a counted loop using foryou are responsible for initializing the counter in the intitialization expression, and for updating it in the update expression. There’s no law that says you have to start at zero, and there’s nothing to stop you from counting down rather than up.

Here’s a fragment that displays the characters in a String in reverse order. It works by walking through the characters of the String from the end to the beginning, using a for loop to count down, instead of counting up.

Counting Down With the for Loop
String s = myTF.getText();
int nChars = s.length();
String output = "";for (int counter = nChars - 1; 
     counter >= 0 ; 
     --counter)
{
   output += s.charAt(counter);
}outputLbl.setText(output);Type in a phrase, press ENTER, and the applet shown here [ReverseString.java] will reverse it, thanks to the magic of the for loop.
What’s with the -1?
You might wonder why the code shown here subtracts one from the length of the String in the initialization expression. In a String, the characters are numbered starting with zero. Thus, if there are 10 characters in a particular String, then the last character is in position 9.
Shows that individual characters in a String are numbered starting at 0. [Click to enlarge]

Counting by Steps

Not only can you count up and count down, you can also count by values other than 1 simply by changing the value in the update expression. The Basic language allows you do do this via its STEP clause, but the Java for loop allows you to use any expression you like, not just different constant values.

Here, for instance, is how you could calculate the sum of all the even numbers less than 100:

Sum = 0;
for (int i = 0; i < 100; i += 2)
{
  Sum += i;
}

And, here’s a loop that displays exponential growth. How many numbers do you think that this will print?

for (int i = 2; i < 10000; i *= i)
{
  System.out.println(i);
}

JAVA Loops…

Introduction to LOOPS

What is iteration? Iteration is a Computer Science term that simply means repeating a set of actions. Iteration is also called repetition or looping. The statements that are used in iteration are called loops.

Both iteration statements and selection statements are flow-of-control statements; they control which code is executed in your program. Like the if statement, iteration is based upon evaluating a booleantrue/false–condition, and then performing a set of actions if the test is true, and skipping them if the test is false. Thus a loop, like an if statement, has both acondition part–the test that is performed–and a body part–the actions that are taken.Iteration, however, is not the same as selection. Beginning programmers often attempt to use a selection statement where they should use a loop, and vice versa. It is important to be able to distinguish the two, and equally important to be able to select the right control structure for the job.The selection structure works much like the illustration shown here. [click the image to enlarge]. Driving down a divided highway, you come to a rest stop, and you pull off. When you leave the rest stop, you rejoin the highway a little further down the road.

Image illustrates the if statement as a highway turnout.

Once you rejoin the highway, you have no opportunity to go back and revisit the rest stop again. Those who bypass the turnoff, skip the rest stop altogether.

A loop structure looks similar, but not the same. As you can see in this illustration, there is still a boolean test, as there is with selection. But, after you’ve had your break, the rest stop exit road “loops back” [hence the name], and you rejoin the highway right where you initially left it.

If you like, you can choose to enter the rest stop once again, even though the highway is one-way. In this sense, a loop also works a little bit like a cloverleaf interchange.

Image illustrates the loop as a highway cloverleaf turnout.

Java and Iteration

Java has three loop statements, the while loop, the dowhile loop, and the for loop. As you might expect, each of these loops varies in the way that it is used, and the place where it is most effectively employed.

Where?

One difference between the loops is where the test takes place–that is, the relative position of the loop test and the actions contained in the loop body.

One loop, the dowhile loop, doesn’t make its test until after it has performed the actions in the loop body at least once.

This is called a “test at the bottom” loop. It is also sometimes called a hasty loop or an unguarded loop because it “leaps before it looks”.

{  // Loop body

}Loop Test

The other two loops, the for loop and the while loop, both make their boolean test before performing the actions in the loop body.

With these loops, if the test condition is false, then the actions inside the loop body are never performed at all. Thus, they are both guarded loops.

Loop Test
{  // Loop body

}

Back to Top

Counted and Indefinite

Classifying loops according to where their condition is tested helps keep the Java syntax straight in our minds, but it’s not really as useful as classifying loops by the kind of boundsthat they employ.A loop’s bounds are the conditions under which it will repeat its actions. In a simple, counter controlled loop, the bounds might be expressed as “the counter has a value less than ten”. In other, more complex loops, the bounds may be a combination of conditions involving ANDs and ORs.

There are two major kinds of loops that can be built using the basic building blocks [forwhile, and dowhile] provided by Java. Let’s look at them briefly, before we start looking at code in the next section.

Counting or Counted Loops

counting, [or counted], loop is a loop that repeats a fixed number of times–a “gimme fifty pushups” kind of loop.With a “pure” counting loop you can look at the code and tell how many times it should execute. In real life, however, things are not so clear-cut. You often won’t know what theactual number of repetitions is until your program runs. The number of repetitions may be based upon the number of characters in a String, for instance, or some other number which is not computed until your program runs.

Indefinite Loops

With an indefinite loop, you can never tell how many times the loop will repeat by examining the code. An indefinite loop is a loop that tests for the occurence of a particular event, not a count of the number of repetitions.”Read characters until you encounter a period” is an example of an indefinite loop. The condition may occur after reading three characters, or it may occur after reading three-thousand. It’s also possible that the period might be the first character read or, sometimes, that a period might not occur at all.

There are three commonly encountered types of indefinite loops that you should be aware of. Each of these indefinite loops uses a different sort of bounds:

  • Data loop. A data loop is a loop that keeps going until there is no more data. This is used when reading files or sending Web pages over the Net. We’ll cover data loops in more detail in Lesson 14, “Streams and Files.”
  • Sentinel loop. A sentinel loop is an indefinite loop that looks for the presence of a special marker contained within its input. In the “read characters until you encounter a period” example, the period is the sentinel; this kind of loop is a sentinelloop. Sentinel loops are often used in searching, but have other uses as well.
  • Limit loop. Limit loops are loops that end when another repetition of the loop won’t get you any closer to your goal. Limit loops are often used in scientific calculations and other numeric algorithms, when stating a precise termination condition is not possible. Often this involves monitoring the difference between two variables, and stopping the loop when the difference passes a predetermined threshhold.
Back to Top

A Loop Building Strategy

Writing perfect code the first time is something of a “Holy Grail” among programmers. By that, I mean that most programmers long to do it, but the vast majority consider its attainment to be the stuff of legend.Writing loops is one area where programming errors often crop up. Several years ago, however, I happened upon a technique developed by Doug Cooper, the Berkeley professor of “Oh! Pascal” fame, for building loops. This technique really does increase your chances of building correct loops the first time, and it’s worth your time to learn it.

The Three Faces

If you put a loop inside a program, as we’ve done with this top-tested loop, you can see that there are:

  • actions that occur before the loop is encountered.
  • actions that occur inside the loop body.
  • actions that occur after the loop is complete.
// Before
Loop Condition
{
  // Inside
}
// After

These three “faces” of a loop are called its precondition, its action or operation, and its postcondition. The loop condition, as you’ve already learned, is called the loop’s bound.

JAVA Dynamics…

So far we have gone through  the most basic codes in JAVA.One more aspect has to be covered which not only provides dynamics to the previous programs but will also be used in upcoming ones.
Till date we have declared the variables in the program itself,but now we will learn to get input from the user so as to generalize the code for all kind of values.

Here we go.!

package basics;

/**
*
* @author aprimit
*/
import java.util.Scanner; //to enable input from the user

public class Keyboard_input {

public static void main(String[] args) {
System.out.println(“This program takes input from the user”);
System.out.println(“Scanner class is imported so as to enable input from the user..”);
int a, b, c;

Scanner obj;//reference variable
obj = new Scanner(System.in);//memory allocation
System.out.println(“Input the value of a…”);
a = obj.nextInt();
System.out.println(“Input the value of b…”);
b = obj.nextInt();
c = a + b;
System.out.println(“The sum of the input variables is …” + c);
}
}

OUTPUT :This program takes input from the user

Scanner class is imported so as to enable input from the user..

Input the value of a…5

Input the value of b…8

The sum of the input variables is …13

Logical Operators JAVA…

Logical Operators

The relational operators we’ve learned so far (<<=>>=!===) are sufficient when you only need to check one condition. However what if a particular action is to be taken only if several conditions are true? You can use a sequence of if statements to test the conditions, as follows:

if (x == 2) { if (y != 2) { System.out.println("Both conditions are true."); } } 

This, however, is hard to write and harder to read. It only gets worse as you add more conditions. Fortunately, Java provides an easy way to handle multiple conditions: the logic operators. There are three logic operators, &&|| and !.

&& is logical and. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance

boolean b; b = 3 > 2 && 5 < 7; // b is true b = 2 > 3 && 5 < 7; // b is now false 

|| is logical or. || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance

boolean b; b = 3 > 2 || 5 < 7; // b is true b = 2 > 3 || 5 < 7; // b is still true b = 2 > 3 || 5 > 7; // now b is false 

The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true.

boolean b; b = !(3 > 2); // b is false b = !(2 > 3); // b is true 

Have a look at the following code:

package basics;

/**
*
* @author aprimit
*/
public class Logical {

public static void main(String[] args) {
System.out.println(“This program illustrates the logical opertions…”);
System.out.println(“The logical operators are…”);
System.out.println(“&&” + “,” + “||”);
System.out.println(“In case of && operator…if the first condition is false then the second condition is not evaluated”);
System.out.println(“In case of || operator…if the first condition is true then the second condition is not evaluated”);
int a = 9, b = 8, c = 5;
if (a >= b && b >= c) {
System.out.println(“TRUE”);

} else {
System.out.println(“FALSE”);

}
}
}

OUTPUT: This program illustrates the logical opertions...

The logical operators are...

&&,||

In case of && operator...if the first condition is false then the second condition is not evaluated

In case of || operator...if the first condition is true then the second condition is not evaluated

TRUE

Operators continued….

Relational Operations……

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use “==“, not “=“, when testing if two primitive values are equal.

==      equal to
!=      not equal to
>       greater than
>=      greater than or equal to
<       less than
<=      less than or equal to
 See this code. .

package basics;

/**
*
* @author aprimit
*/
public class Relational {

public static void main(String[] args) {
System.out.println(“This program illustrates Relational operations”);
System.out.println(“Relational operators are meant for comparison”);
System.out.println(“Relational operations result in BOOLEAN”);
System.out.println(“<” + ” ” + “Less than”);
System.out.println(“>” + ” ” + “Greater than”);
System.out.println(“<=” + ” ” + “Less than or Equal to”);
System.out.println(“>=” + ” ” + “Greater than or Equal to”);
System.out.println(“==” + ” ” + “Equal to”);
System.out.println(“!=” + ” ” + “NOT Equal to”);
int a = 5, b = 4;
boolean z = a > b; //z is declared as BOOLEAN since it returns either TRUE or FALSE.
System.out.println(z);
boolean y = (a == b);//y is declared as BOOLEAN since it returns either TRUE or FALSE.
System.out.println(y);
boolean x = (a != b);//x is declared as BOOLEAN since it returns either TRUE or FALSE.
System.out.println(x);

}
}

OUTPUT: z=TRUE

y=FALSE

x=TRUE

After  practice of a day. i feel quite relaxed in arithmetic operations.Moving on to the next part,we have Increment & Decrement operations ahead of us.

The ++ and the are java’s increment and decrement operators.As you will see, they have some special properties that make them quite interesting. Let’s begin by reviewing precisely what the increment and decrement operators do.

The increment operator increases its operand by one. The decrement operator decreases its operand by one. For example, this statement:

 x = x + 1;

can be rewritten like this by use for the increment operator:

x++;

Similarly, this statement

  x = x –1;

is equivalent to

x–;

These operators are unique in that they can appear both in postfix form, where they follow the operand as just shown, and prefix form, where they precede the operand. in foregoing examples, there is no difference between the prefix and postfix forms. However, when the increment and / pr decrement operators are part of a larger expression, then a subtle, yet powerful, difference between these two forms appears. In the prefix form, the operand is incremented or decremented before the value is obtained for use in the expression. In postfix form, the previous value is obtained for use in the expression, and then the operand is modified. For example:

x = 42;

y = ++x;

In this case, y is set to 43 as you would expect, because the increment occurs before x is assigned to y. thus, the line y=++x; is the equivalent of these two statements:

x = 42;

 y = x++;

The value of x is obtained before the increment operator is executed, so the value of y is 42. Of course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two statements:

y =x;

 x = x + 1;

 Lets have a program to bring the above concept to life.

package basics;

/**
*
* @author aprimit
*/
public class Increment {

public static void main(String[] args) {
System.out.println(“This program illustrates increement/decreement operations..”);
System.out.println(“Increement/decreement operators are…”);
System.out.println(“++” + “and” + “–“);
int a = 20, b, c, d, e;
b = ++a; //pre-increement operator
System.out.println(b);
c = a++; //post increement operator
System.out.println(c);
d = –a; //pre-increement operator
System.out.println(d);
e = a–; //post increement operator
System.out.println(e);
}
}

OUTPUT: b=21

c=20

d=20

e=20