Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Control Statements

java controls

  • Please log in to reply
4 replies to this topic

#1 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 17 February 2013 - 01:48 AM

It is essential to have a thorough understanding of the problem and carefully plan approach to solving it before writing a program. It is essential to understand the types of building blocks that are available and how to employ them to program construction techniques. In  this article we discuss the issue of control statements and principles of structured programming.

 

Control Structures


Generally statements in a program are executed sequentially one after another in the order they are written. There are java  statements that enable the programmer to specify that the next statement to execute is not necessarily the next one in the sequence. This transfer of control can be specified according to the logical requirement of the program through selection statements and  repetition statements.

 

Selection Statements


Java has three types of selection statements – if statements, if...else statements, and switch statements.

 

if Statements

 

The if statement either performs/selects an action if a condition is true or skips the action if the condition is false.

 

if(weekDay== 1){
    System.out.println("Sunday");
}
 

 

if...else Statements


The if...else statement performs an action if a condition is true and performs a different action if the condition is false.

 

if(weekDay== 1){

    System.out.println("Sunday");

}else{

    System.out.println("its not Sunday!");

}

 

Nested if...else Statements


The if...else statement can be nested as follows

 

if(weekDay == 1) {
    System.out.println("Sunday");
}
else if(weekDay==2){
    System.out.println("Monday");
}
else if(weekDay==3){
    System.out.println("Tuesday");
}else{
    System.out.println("may be some other day");
} 

 

switch Statements


The switch statement performs one of many different actions, depending on the value of an expression

 

switch(weekDay) {
        case 1:
            System.out.println("Sunday");
            break;
        case 2:
            System.out.println("Monday");
            break;
        case 3:
            System.out.println("Tuesday");
            break;
        case 4:
            System.out.println("Wednesday");
            break;
        case 5:
            System.out.println("Thursday");
            break;
        case 6:
            System.out.println("Friday");
            break;
        case 7:
            System.out.println("Saturday");
            break;
        default:
            System.out.println("a week has only seven days");
        }

 

 

Note: Most switch statements use a break in each case to terminate the switch statements after processing the case. In the above example try writing the switch case program without break. You shall see that all print statement gets executed.

 


Repetition statements or Loops


Repetition statements or loops allows the programmer to specify that a program should repeat an action while some condition remains true. There are primarily three types loop statements in Java – while, for and do-while with the following structure.

 


while loop

 

while(<condition>){

...

}

 

while.jpg

 

Example

 

public class WhileDemo {
    public static void main(String[] args) {        
        int i = 1;
        while(i <= 10) {
            System.out.println(i);
            i++;
        }//end of while
    }//end of main
}//end of class
 

 

do-while loop


do{

...

 

}while(<condition>);


dowhile.jpg
 

Example

 

public class DoWhileDemo {

    public static void main(String[] args) {                
        int k = 1;
        do{
            System.out.println(k);
            k++;
        }while(k <= 10); //end of do-while
    }//end of main
}//end of class


for loop


for(<initialization>;<condition>;<expression>){

...


}


for.jpg

 

Example

 

public class ForDemo {

    public static void main(String[] args) {        

        for (int j = 1; j <= 10; j++) {

            System.out.println(i);

        }//end of for
    }//end of main
}//end of class
 


Though the structure of three loops looks different, they actually perform the same task, repeating the print statement to print all the numbers, 1 through 10 in this case. Choosing a particular looping structure is a matter of choice. However, there is a very subtle difference especially between do-while loop and for/while loop. for/while loops are almost similar apart from the initialization code written inside the braces of for. But the scenario is different in case of do-while loop. At the first entrance into do-while no condition is checked but for/while loop always checks the condition before entrance and after that all three types of loop acts in similar manner.

 

Nested Loops


Any of the for, while or do-while loops may be nested i.e. We may put one loop inside another with pretty much any combination like a while loop inside a for loop or for inside do-while etc. Lets try and example how it can be done.

 

//program to print the pattern
/*
* 1
* 12
* 123
* 1234
*/
public class Pattern1 {
    public static void main(String[] args) {
        int height = 4;
        for(int i=1;i<=height;i++){
            for(int j=1;j<=i;j++){
                System.out.print(j);
            }
            System.out.println("");
        }        
    }// end of main
}// end of class

 

Note: Looping exercises are very important because it not only gives a fine grasp on how to control your loops but also enhances logical thinking pattern, very helpful for budding programmers. It is like fingering exercise on the fret board when you first learn how to play a guitar.

 

break Statements


The break statement, when executed in a while, for, do-while or switch, cases immediate exit from the statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch.

 

Example

 

//program to find first number divisible by 7 between 100 and 200
public class BreakDemo {
    public static void main(String[] args) {
        int count;
        for(count = 100; count <= 200; count++) {
            if count % 7 == 0) {
                System.out.println("The number is: " + count);
                break;
            }
        }
        System.out.println("Broke out of the loop with count: " +count);
    }// end of main
}//end of class


 

continue Statement


The continue statement, when executed in a while, for, do-while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.

 

Example

 

//program to find numbers which are not divisible by 7 between 100 and 200

public class ContinueDemo {
    public static void main(String[] args) {
        int count;
        for (count = 100; count <= 200; count++) {
            if(count % 7 == 0) 
                continue;
            System.out.print(count+",");
            
        }
        System.out.println("Broke out of the loop with count: " + count);
    }//end of main
}//end of class


Logical operators


The if, if...else, while, do...while and for statements require some condition to determine how to continue program's flow of control. Simple conditions are expressed in terms of the relational operators >,<,>=,<= and the equality operators == and !=, and each expression tests only one condition. To test multiple conditions in the process of making a decision, we perform these tests in separate statements or in nested if or if...else statements. Java provides logical operators to enable programmers to form more complex conditions by combining simple conditions. The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT).


&& (conditional AND)


Expression with && and || operators are evaluated only until it is known whether the condition is true or false. Thus the evaluation (x==20) && (y<=30) stops immediately if x is not equal to 20 (i.e. The entire expression is false) and continues if x is equal to 20 (i.e. The entire expression can still be true if the condition y<=30 is true). This feature is called short circuit evaluation. The truth table below shows how the conditional AND operation is evaluated.

table11.jpg

 

|| (conditional OR)

 

When we wish to ensure that either or both of two condition are true before choosing a certain path of execution we use conditional OR statement as (x==20) || (y<=30). The truth table below shows how the conditional OR operation is evaluated.

table12.jpg

 

^ (boolean logical exclusive OR)


The operator evaluates to true if and only if one of its operands is true and other is false. The truth table below shows how the boolean logical exclusive OR operation is evaluated. This operator guaranteed to evaluate both of its operands (while && and || operator does not guarantee evaluation of both the operand).

table13.jpg

 

! (logical NOT)

 

This operator is also called logical negation or logical complement, operates to “reverse” the meaning of a condition such as: !(x==20) i.e. When x is not equal to 20.

table14.jpg


boolean logical AND (&) and boolean logical OR (|)

 

The boolean logical AND (&) and boolean logical OR (|) acts identically to && (conditional AND) and || (conditional OR) but with one exception. The boolean logical operators always evaluate both their operands i.e. The expression do not perform any short circuit evaluation. Example: (x==20) & (y<=30) and (x==20) | (y<=30).

 

Quizzes

 1. Which of the following are selection statements
(1) if, while, for
(2) if, if...else, while
(3) if, if...else, switch
(4) if, if...else, do-while

 2. When break is written inside a loop what does it do
(1) control gets out of the loop
(2) control return to the previous statement
(3) controls remains there
(4) control goes to the beginning of the loop

 3. When continue is written inside a loop what does it do
(1) control gets out of the loop
(2) control return to the previous statement
(3) controls remains there
(4) control goes to the beginning of the loop

 4. Which of the following is not a loop
(1) for
(2) while
(3) if...else
(4) do...while

 5. What makes do...while loop different from a for and while loop
(1) They are all the same
(2) They are not loop at all
(3) At the inception condition is not checked for do...while
(4) in fact while and do...while are same but for is different.

 6. What do you think following program would do

 

    public class XYZ {
    public static void main(String[] args) {
        for (int i = 0; true; i++)
        {
            System.out.println("hehe!");
        }
    }
    }
 


(1) The program will never run
(2) The program has a syntax error in the for loop
(3) “hehe” will be printed
(4) The program will not stop printing

 7. What do you think following program would do

  

 int a=5;
    if(a%2==0)
        System.out.println("even");
 


(1) The program will print  - even
(2) The program will print  - odd
(3) There is a syntax error
(4) Nothing will be printed

 8. ! operator
(1) reverses the condition
(2) there is no such operator
(3) a factorial sign
(4) none of the above

 9. if a=5, b=a++, then a, b respectively contains
(1) 5, 5
(2) 6, 5
(3) 6, 6
(4) 5, 6

 10. if a=5, b=--a, then a, b respectively contains
(1) 5, 5
(2) 4, 4
(3) 5, 4
(4) 4, 5

 11. What happen when no break is stated inside switch block
(1) control does not enter inside switch
(2) All the cases are evaluated
(3) Logical error
(4) Program does not compile

 12. What will be the output of the following code
 

    int i=10;
    for(;;i++)
    {
        if(i>10)
            break;
        else
            System.out.println(i);
    }
 


(1) 10
(2) Never ending loop
(3) The program will not compile
(4) Prints 1 through 10


Spoiler



Tasks: Try yourself

 

Write a program to print the following patterns

 

*
**
***
****

 

1
22
333
4444


1
121
12321
1234321


1
010
10101
0101010

 

  • Write a program to reverse a number

 

Previous: Java Application: First program in Java | Next: Methods | Back to Table of content


Edited by mdebnath, 08 March 2013 - 01:40 AM.

  • 0

#2 XB23

XB23

    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 03 July 2014 - 03:23 PM

The answer to question number 7 & number 9, is wrong I believe.


  • 1

#3 XB23

XB23

    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 03 July 2014 - 03:43 PM

What's the answer to the following?

1
010
10101
0101010

Edited by XB23, 03 July 2014 - 03:43 PM.

  • 0

#4 XB23

XB23

    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 03 July 2014 - 04:50 PM

I figured the second post:

 

for (int i = 1; i <= 4; i++) {
  for (int j = 1; j < (2*i); j++) {


    if ((i+j)% 2 == 0) {


      print(1);
    } 
    else {


      print(0);
    }
  }


  println();
}


















  

  • 2

#5 Davidjeone

Davidjeone

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 25 December 2016 - 10:49 AM

Transparency is not respected in the CONTROL_BACKGROUND image - both 8-bit powerpink and 32-bit alpha is ignored.

.
  • 0





Also tagged with one or more of these keywords: java, controls