SURVEY OF PROGRAMMING LANGUAGES


UNIT 4

SELECTION STATEMENT USING PJC (Pascal, Java, C++)

Selection statement or selection construct or selection structures is also called conditional or decision statement. The purpose is to make your program select a result from an option or from a list of options, when a specified condition is met.

4.1       PROGRAMS LAB EXAMPLES

4.1.1   Simple If Statement

In simple if statement, only a single condition is evaluated, the if-block is executed, if the condition is true.

Syntax:

Pascal

if condition then

    //statements

 

Java

if condition {

    //statements

}

 

C++

if condition {

    //statements

}

 

 

4.1.2   Lab 1 – program to test the age of a student, if he eligible to vote

Pascal

program lab1;

var

//declare variables

    age : integer;

begin

//display action for the user and accept input

  writeln('Enter your age');

  readln(age);

 

//test if age <18, show 'teenager…’

if (age <18) then

    writeln('You are a teenager, you cannot vote');

 

end.

TIP: If you enter an age value that is from 0-17, the program shows ‘you are a teenager, you cannot vote‘. However, if you enter a value equal or greater than 18 nothing happens. To advance this program, we will make use of if..then…else construct. If the condition is false, we use else to specify a new condition to test.

Java

import java.util.*;

public class lab1 {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter your age:: ");

        int age = sc.nextInt();

       

        if (age <18) {

            System.out.println("You are a teenager, you cannot vote");

        }      

     }

}

TIP: You must wrap the condition within a bracket, else it will show an error

 

C++

#include <iostream>

using namespace std;

 

int main()

{

    int age;

      

    cout<<"Please enter your age:: ";

    cin >> age;

   

    if (age <18) {

            cout << "You are a teenager, you cannot vote" <<endl;

   }      

   

    return 0;

}

 

4.1.3   If…else Statement

In if…else statement, when the condition of the if-block is evaluated to false, the statements in the else block, will get executed.

Syntax:

Pascal

if condition then

    //statements

Else

    //statements

 

Java

if condition {

    //statements

}

else{

    //statements

}

 

C++

if condition {

    //statements

}

else{

    //statements

}

 

 

4.1.4   Lab 2 – program to test the age of a student, if he eligible to vote

Pascal

program lab2;

var

//declare variables

    age : integer;

begin

//display action for the user and accept input

  writeln('Enter your age');

  readln(age);

 

//test if age <18, show 'teenager...'

if (age <18) then

    writeln('You are a teenager, you cannot vote')

else

    writeln('You are an adult, you can vote');

 

end.

TIP: Any time you are using if…else, put semicolon in the statement of the last else-block. If you put semicolon in the statement of the if-block, it will generate error.

Java

import java.util.*;

public class lab2 {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter your age:: ");

        int age = sc.nextInt();

       

        if (age <18) {

            System.out.println("You are a teenager, you cannot vote");

        }else{

            System.out.println("You are an adult, you can vote");

        }     

     }

}

TIP: You must wrap the condition within a bracket, else it will show an error

 

C++

#include <iostream>

using namespace std;

 

int main()

{

    int age;

      

    cout<<"Please enter your age:: ";

    cin >> age;

   

    if (age <18) {

            cout << "You are a teenager, you cannot vote" <<endl;

   } else{

                        cout << "You are an adult, you can vote" <<endl;

   }     

   

    return 0;

}

 

4.1.5   If…else…if…else Statement

In if…else…if….else statement, multiple conditions are evaluated, it is only the block that satisfies the specified condition that will get executed. You can add as many else-if-blocks as you want.

Syntax:

Pascal

if condition_1 then

    //statements

 else if condition_2  then

//statements

else if condition_3 then

    //statements

 else if condition_4 then

    //statements

else

    //statements

 

Java

if condition_1 {

    //statements

} else if condtion_2  {

    //statements

} else if condtion_3  {

    //statements

} else{

    //statements

}

 

C++

if condition_1 {

    //statements

} else if condtion_2  {

    //statements

} else if condtion_3  {

    //statements

} else{

    //statements

}

 

 

4.1.6   Lab 3 – program to test the classification of patient’s BMI (Body Mass Index), using the table below.

BMI

CLASSIFICATION

< 18.5

Under weight

18.5 to < 25

Normal

25 to < 30

Over weight

> =30

Obesity

 

Pascal

program lab3;

var

//declare variables

    weight, height, resultBmi : real;

begin

//display user action and accept input

  writeln('Enter weight value in KG:: ');

  readln(weight);

 

  writeln('Enter height value in meters from (0-2):: ');

  readln(height);

 

  //processing

  resultBmi := weight / (height * height);

 

 //display output

  writeln('Your body mass index is:: ', resultBmi:0:2);

 

 //test the BMI classification of the patient

 if resultBmi <18.5 then

    writeln('Your BMI is Under weight')

 else if (resultBmi >18.5) and (resultBmi <25)  then

 writeln('Your BMI is Normal')

 else if (resultBmi >25) and (resultBmi <30)  then

 writeln('Your BMI is Over weight')

 else if resultBmi > 30 then

    writeln('Your BMI is Obesity')

else

    writeln('Something went wrong');

 

end.

TIP: Take note that we put semicolon in the last else-block. If you put semicolon in the previous if-block or else-if-block , it will generate error.

Java

import java.util.*;

public class lab3 {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter weight value in KG:: ");

        double weight = sc.nextDouble();

       

        System. out. println("Enter height value in meters from (0-2):: ");

        double height = sc.nextDouble();

       

        double resultBmi = weight / (height * height);       

      

        //display output

        System.out.println("Your body mass index is:: " + String.format("%.2f", resultBmi));        

       

        //test the BMI classification of the patient

        if (resultBmi < 18.5) {

            System.out.println("Your BMI is Under weight");

        }else if ((resultBmi >18.5) && (resultBmi <25))  {

            System.out.println("Your BMI is Normal");

        }else if ((resultBmi >25) && (resultBmi <30))  {

            System.out.println("Your BMI is Over weight");

        }else if (resultBmi > 30) {

            System.out.println("Your BMI is Obesity");

        }else{

            System.out.println("Something went wrong");

        }

        

    }

}

TIP: You must wrap the condition within a bracket, else it will show an error. Observe the way we wrap the two conditions in the else-if-block. Also, we make use of logical and of java (&&)

 

C++

#include <iostream>

using namespace std;

 

int main()

{

    float weight, height, resultBmi;

   

    cout<<"Enter weight value:: ";

    cin >> weight;

   

    cout<<"Enter height value:: ";

    cin >> height;

   

    resultBmi = weight / (height * height);   

   

    //display output   

    cout << "Your body mass index is:: ";

            printf("%.2f", resultBmi);

           

            //test the BMI classification of the patient

            if (resultBmi < 18.5) {

            cout << "Your BMI is Under weight " << endl;

        }else if ((resultBmi >18.5) && (resultBmi <25))  {

            cout << "Your BMI is Normal " << endl;

        }else if ((resultBmi >25) && (resultBmi <30))  {

            cout << "Your BMI is Over weight " << endl;

        }else if (resultBmi > 30) {

            cout << "Your BMI is Obesity " << endl;

        }else{

            cout <<"Something went wrong";

        }

       

    return 0;

}

 

 

4.1.7   Lab 4 – program for a user to select his/her gender (take/read/accept character input from the user), using the table below.

value

CLASSIFICATION

m

Male

f

Female

When the user enters something else

Something went wrong

TIP: We will use the equality operator and the OR operator. Java and C++ OR operator use two vertical lines | |.

Operator

Pascal

Java

C++

OR

Or

| |

| |

Equality for char and integer in Pascal, while char, int, double in Java and C++

=

= =

= =

Equality for String datatype

 

.equals()

 

 

 

Pascal

program lab4;

var

//declare variables

    gender : char;

begin

//display user action and accept input

  writeln('Enter m/f to select your gender');

  readln(gender);

 

 //test the classification of the user

 if (gender = 'm') or (gender = 'M') then

    writeln('Male')

 else if (gender = 'f')  or (gender = 'F') then

 writeln('Female')

else

    writeln('Something went wrong');

 

end.

 

Java

import java.util.*;

public class lab4a {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter m/f to select your gender:: ");

        char gender = sc.next().charAt(0);

       

        //test

        if ((gender=='m') || (gender=='M')) {

            System.out.println("Male");

        }else if ((gender=='f') || (gender=='F'))  {

            System.out.println("Female");

        }else{

            System.out.println("Something went wrong");

        }

        

    }

}

TIP: In the above program, we surround the value m with single quotes

//if you use String datatype

import java.util.*;

public class lab4b {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter m/f to select your gender:: ");

        String gender = sc.next();

       

        //test

        if (gender.equals("m") || gender.equals("M")) {

            System.out.println("Male");

        }else if (gender.equals("f") || gender.equals("F")) {

            System.out.println("Female");

        }else{

            System.out.println("Something went wrong");

        }

        

    }

}

TIP: In the above program, we surround the value m with double quotes

 

C++

#include <iostream>

using namespace std;

 

int main()

{

    char gender;

   

    cout<<"Enter m/f to select your gender:: ";

    cin >> gender;  

           

            //test the classification

            if ((gender == 'm') || (gender == 'M')) {

            cout << "Male" << endl;

        }else if ((gender == 'f') || (gender == 'F')) {

            cout << "Female" << endl;

        }else{

            cout <<"Something went wrong";

        }

       

    return 0;

}

TIP: Take note of how we wrap the conditions into parentheses.

 

4.1.8   Switch Case Statement

Switch case statement is a simplified version of if…else…if…else statement, it helps to make the program to be more readable. Here, only a single condition is evaluated among several alternatives, the block the meets the condition is executed.

Syntax:

Pascal

case (expression) of

   label_1 : Statement_1;

   label_2 : Statement_2;

   label_3 : Statement_3;

   else

     //statements

end;

TIP: The label represent the condition to be evaluated, you can add as many labels as you want.

Java

switch(expression) {

  case label_1:

    // statements

    break;

  case label_2:

    // statements

    break;

  default:

    // statements

}

TIP: In the above syntax, we make use of the keyword case, break and default (which does the job of else)

 

C++

switch(expression) {

  case label_1:

    // statements

    break;

  case label_2:

    // statements

    break;

  default:

    // statements

}

 

4.1.9   Lab 5 – program to test a user gender. Modification of Lab4 program example

Pascal

program lab5;

var

//declare variables

   gender: char;

begin

   //display user action and accept input

  writeln('Enter m/f to select your gender');

  readln(gender);

 

   case (gender) of

   //test the classification of the user

      'm' : writeln('Male');

      'M' : writeln('Male');

      'f' : writeln('Female');

      'F' : writeln('Female');

      else

      writeln('Something went wrong');

   end;   

   writeln('Your gender is  ', gender );

end.

//this also works, by separating the labels with comma

//test the classification of the user

      'm', 'M' : writeln('Male');

      'f', 'F' : writeln('Female');

//code snippet to test for student grade within score range

//score is a variable

Case (score) of 

 90..100   : WriteLn ('Grade is A'); 

 80..89 : WriteLn ('Grade is B'); 

else 

  WriteLn ('You had a carry over'); 

end;

 

Java

import java.util.*;

public class lab5 {

    public static void main(String[] args) {

        //create scanner object sc (you can use any variable of your choice)

        Scanner sc = new Scanner(System. in);

       

        System. out. println("Enter m/f to select your gender:: ");

        char gender = sc.next().charAt(0);

       

        //test

        switch(gender) {

            case 'm':

              System.out.println("Male");

              break;

            case 'M':

              System.out.println("Male");

              break;

            case 'f':

              System.out.println("Female");

              break;

            case 'F':

              System.out.println("Female");

              break;

            default:

              System.out.println("Something went wrong");

          }      

        

    }

}

//this also works, by writing the labels on separate line with their own colon (:)

//this allows two or more labels to share statements

//test the classification of the user

            case 'M':

            case 'm':

              System.out.println("Male");

              break;

 

C++

#include <iostream>

using namespace std;

int main()

{

    char gender;

   

    cout<<"Enter m/f to select your gender:: ";

    cin >> gender;     

           

            //test the user classification

        switch(gender) {

            case 'm':

              cout << "Male" << endl;

              break;

            case 'M':

              cout << "Male" << endl;

              break;

            case 'f':

              cout << "Female" << endl;

              break;

            case 'F':

              cout << "Female" << endl;

              break;

            default:

              cout << "Something went wrong";

          }  

 

    return 0;

}

//this also works, by writing the labels on separate line with their own colon (:)

//this allows two or more labels to share statements

//test the classification of the user

            case 'M':

            case 'm':

             cout << "Male" << endl;

 


Comments

Popular posts from this blog

Basic Web Page - phase 1