Formulating Expressions |
|
The C# language provides a set of control statements that allows you to conditionally control data input and output. These controls are referred to as loops. The while statement examines or evaluates a condition. The syntax of the while statement is: while(Condition) Statement; To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop. Here is an example: int number; while( number <= 12 ) { Console.Write("Number "); Console.WriteLine(number); number++; } To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use a get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows: An example would be: package Exercise; import System.*; public class Exercise { public static void main() { int number = 0; while( number <= 12 ) { Console.WriteLine("Number " + number); number++; } } } This would produce: Number 0 Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 Number 7 Number 8 Number 9 Number 10 Number 11 Number 12 |
|
Practical Learning: Introducing Conditional Statements |
package MVA; import System.*; public class Exercise { public static void main() { String firstName, lastName; String strOrganDonor; char gender; char DLClass; Console.WriteLine(" -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Application ---"); Console.Write("First Name: "); firstName = Console.ReadLine(); Console.Write("Last Name: "); lastName = Console.ReadLine(); Console.Write("Gender(F=Female/M=Male): "); gender = Char.Parse(Console.ReadLine()); Console.WriteLine(" - Driver's License Class -"); Console.WriteLine("A - All Non-commercial vehicles except motorcycles"); Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs."); Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs."); Console.WriteLine("K - Mopeds"); Console.WriteLine("M - Motorcycles"); Console.Write("Your Choice: "); DLClass = Char.Parse(Console.ReadLine()); Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? "); strOrganDonor = Console.ReadLine(); Console.WriteLine("\n -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Information ---"); Console.WriteLine("Full Name: {0} {1}", firstName, lastName); Console.Write("Gender: "); if( gender == 'f' ) Console.WriteLine("Female"); else if( gender == 'F' ) Console.WriteLine("Female"); else if( gender == 'm' ) Console.WriteLine("Male"); else if( gender == 'M' ) Console.WriteLine("Male"); else Console.WriteLine("Unknown"); switch(DLClass) { case 'a': case 'A': Console.WriteLine("Class: A"); break; case 'b': case 'B': Console.WriteLine("Class: B"); break; case 'c': case 'C': Console.WriteLine("Class: C"); break; case 'k': case 'K': Console.WriteLine("Class: K"); break; case 'm': case 'M': Console.WriteLine("Class: M"); break; default: Console.WriteLine("Class: Unknown"); break; } Console.Write("Organ Donor? "); if( strOrganDonor.Equals("1") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("0") ) Console.WriteLine("No"); Console.WriteLine(); } } |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 6 First Name: Henry Last Name: Dricks Sex(F=Female/M=Male): P - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: G Are you willing to be an Organ Donor(1=Yes/0=No)? 4 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: Not Specified Full Name: Henry Dricks Sex: Unknown Class: Unknown Organ Donor? Invalid Answer |
The do…while statement uses the following syntax: do Statement while (Condition); The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop. If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon. Another version of the counting program seen previously would be: package Exercise; import System.*; public class Exercise { public static void main() { int number = 0; do { Console.WriteLine("Number " + number); number++; }while( number <= 12 ); } } If the Statement is long and should span more than one line, start it with an opening curly bracket and end it with a closing curly bracket. The do…while statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that: |
upackage Exercise; import System.*; public class Exercise { public static void main() { char sittingDown; String strDown; Console.Write("For the next exercise, you need to be sitting down\n"); do { Console.Write("Are you sitting down now(y/n)? "); strDown = Console.ReadLine(); sittingDown = Char.Parse(strDown); } while( !(sittingDown == 'y') ); } }
Here is an example of running the program:
For the next exercise, you need to be sitting down Are you sitting down now(y/n)? t Are you sitting down now(y/n)? h Are you sitting down now(y/n)? G Are you sitting down now(y/n)? y
Practical Learning: Using do...While |
package MVA; import System.*; public class Exercise { public static void main() { final int NewDriversLicense = 1; final int UpgradeFromIDCard = 2; final int TransferFromAnotherState = 3; int typeOfApplication; String firstName, lastName; String strOrganDonor; char gender; char DLClass; Console.WriteLine(" -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Application ---"); do { Console.WriteLine(" - Select the type of application -"); Console.WriteLine("1 - Applying for a brand new Driver's License"); Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License"); Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state"); Console.Write("Your Choice: "); typeOfApplication = Integer.parseInt(Console.ReadLine()); Console.WriteLine(""); } while(typeOfApplication > 3); Console.Write("First Name: "); firstName = Console.ReadLine(); Console.Write("Last Name: "); lastName = Console.ReadLine(); Console.Write("Gender(F=Female/M=Male): "); gender = Char.Parse(Console.ReadLine()); Console.WriteLine(" - Driver's License Class -"); Console.WriteLine("A - All Non-commercial vehicles except motorcycles"); Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs."); Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs."); Console.WriteLine("K - Mopeds"); Console.WriteLine("M - Motorcycles"); Console.Write("Your Choice: "); DLClass = Char.Parse(Console.ReadLine()); Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? "); strOrganDonor = Console.ReadLine(); Console.WriteLine("\n -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Information ---"); Console.Write("Type of Application: "); switch(typeOfApplication) { case NewDriversLicense: Console.WriteLine("New Driver's License"); break; case UpgradeFromIDCard: Console.WriteLine("Upgrade From Identity Card"); break; case TransferFromAnotherState: Console.WriteLine("Transfer From Another State"); break; default: Console.WriteLine("Not Specified"); break; } Console.WriteLine("Full Name: {0} {1}", firstName, lastName); Console.Write("Gender: "); if( gender == 'f' ) Console.WriteLine("Female"); else if( gender == 'F' ) Console.WriteLine("Female"); else if( gender == 'm' ) Console.WriteLine("Male"); else if( gender == 'M' ) Console.WriteLine("Male"); else Console.WriteLine("Unknown"); switch(DLClass) { case 'a': case 'A': Console.WriteLine("Class: A"); break; case 'b': case 'B': Console.WriteLine("Class: B"); break; case 'c': case 'C': Console.WriteLine("Class: C"); break; case 'k': case 'K': Console.WriteLine("Class: K"); break; case 'm': case 'M': Console.WriteLine("Class: M"); break; default: Console.WriteLine("Class: Unknown"); break; } Console.Write("Organ Donor? "); if( strOrganDonor.Equals("1") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("0") ) Console.WriteLine("No"); Console.WriteLine(); } } |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 6 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 8 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 3 First Name: Alexandria Last Name: McArthur Sex(F=Female/M=Male): M - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: C Are you willing to be an Organ Donor(1=Yes/0=No)? 0 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: Transfer From Another State Full Name: Alexandria McArthur Sex: Male Class: C Organ Donor? No |
The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is: for(Start; End; Frequency) Statement; The Start expression is a variable assigned the starting value. This could be Count = 0; The End expression sets the criteria for ending the counting. An example would be Count < 24; which means that the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting.
The Frequency expression lets the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count. package Exercise; import System.*; public class Exercise { public static void main() { for(int count = 0; count <= 12; count++) { Console.Write("Number "); Console.WriteLine(count); } } } A variable declared as the counter of a for loop is available only in that for loop. This means that the scope of the counting variable is confined only to the for loop. This allows different for loops to use the same counter variable. Here is an example: |
package Exercise; import System.*; public class Exercise { public static void main() { for(int count = 0; count <= 12; count++) { Console.Write("Number "); Console.WriteLine(count); } Console.WriteLine(); for(int count = 10; count >= 2; count--) { Console.Write("Value "); Console.WriteLine(count); } } }
This would produce:
Number 0 Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 Number 7 Number 8 Number 9 Number 10 Number 11 Number 12 Value 10 Value 9 Value 8 Value 7 Value 6 Value 5 Value 4 Value 3 Value 2
Techniques of Writing Conditional Statements |
A condition can be created inside of another to write a more effective statement. This is referred to as nesting one condition inside of another. Almost any condition can be part of another and multiple conditions can be included inside of others. As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role. Here is an example of an if condition nested inside of a do...while loop: package Exercise; import System.*; public class Exercise { public static void main() { char sittingDown; String strDown; do { Console.Write("Are you sitting down now(y/n)? "); strDown = Console.ReadLine(); sittingDown = Char.Parse(strDown); if( sittingDown != 'y' ) Console.WriteLine("Could you please sit down for the next exercise? "); } while( !(sittingDown == 'y') ); } } Here is an example of running the program: Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? g Could you please sit down for the next exercise? Are you sitting down now(y/n)? y One of the reasons you would need to nest conditions is because one would lead to another. Sometimes, before checking one condition, another primary condition would have to be met. The ergonomic program we have been simulating so far is asking the user whether she is sitting down. Once the user is sitting down, you would write an exercise she would perform. Depending on her strength, at a certain time, one user will be tired and want to stop while for the same amount of previous exercises, another user would like to continue. Before continuing with a subsequent exercise, you may want to check whether the user would like to continue. Of course, this would be easily done with: |
package Exercise; import System.*; public class Exercise { public static void main() { char sittingDown; String strDown; do { Console.Write("Are you sitting down now(y/n)? "); strDown = Console.ReadLine(); sittingDown = Char.Parse(strDown); if( sittingDown != 'y' ) Console.WriteLine("Could you please sit down for the next exercise? "); } while( !(sittingDown == 'y') ); Console.Write("Wonderful. Now we will continue today's exercise..."); Console.WriteLine("\n...\nEnd of exercise"); char wantToContinue; Console.Write("\nDo you want to continue(y=Yes/n=No)? "); String toContinue = Console.ReadLine(); wantToContinue = Char.Parse(toContinue); } }
If the user answers No, you can stop the program. If she answers Yes, you would need to continue the program with another exercise. Because the user answered Yes, the subsequent exercise would be included in the previous condition because it does not apply for a user who wants to stop. In this case, one “if” could be inserted inside of another. Here is an example: |
package Exercise; import System.*; public class Exercise { public static void main() { char sittingDown; String strDown; do { Console.Write("Are you sitting down now(y/n)? "); strDown = Console.ReadLine(); sittingDown = Char.Parse(strDown); if( sittingDown != 'y' ) Console.WriteLine("Could you please sit down for the next exercise? "); }while( sittingDown != 'y' ); Console.WriteLine("Wonderful. Now we will continue today's exercise..."); Console.WriteLine("\n...\nEnd of exercise\n"); char wantToContinue; Console.Write("\nDo you want to continue(1=Yes/0=No)? "); String toContinue = Console.ReadLine(); wantToContinue = Char.Parse(toContinue); if(wantToContinue == '1') { char layOnBack; Console.WriteLine("Good. For the next exercise, you should lay on your back"); Console.Write("Are you laying on your back(1=Yes/0=No)? "); String lay = Console.ReadLine(); layOnBack = Char.Parse(lay); if(layOnBack == '1') Console.WriteLine("Great.\nNow we will start the next exercise."); else Console.WriteLine("\nWell, it looks like you are getting tired..."); } else Console.WriteLine("We had enough today"); Console.WriteLine("We will stop the session now\nThanks.\n"); } }
Practical Learning: Nesting Conditions |
package MVA; import System.*; public class Exercise { public static void main() { . . . No Change Console.WriteLine(" -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Application ---"); do { Console.WriteLine(" - Select the type of application -"); Console.WriteLine("1 - Applying for a brand new Driver's License"); Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License"); Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state"); Console.Write("Your Choice: "); typeOfApplication = Integer.parseInt(Console.ReadLine()); Console.WriteLine(""); if( typeOfApplication > 3 ) Console.WriteLine("Please enter a valid number as 1, 2, or 3"); } while(typeOfApplication > 3); . . . No Change Console.WriteLine(); } } |
The break statement is used to stop a loop for any reason or condition the programmer considers fit. The break statement can be used in a while condition to stop an ongoing action. The syntax of the break statement is simply: break; Although made of only one word, the break statement is a complete statement. Therefore, it can (and should always) stay on its own line (this makes the program easy to read). The break statement applies to the most previous conditional statement to it, provided that previous statement is applicable. The break statement is typically used to handle the cases in a switch statement as we saw it in the previous lesson. Besides the switch statement, the break statement can also be used in other conditional statements. For example, you can use a break statement inside of a for loop to interrupt its count. The following program would display letter from d to n but it is interrupted by a break when it encounters k: package Exercise; import System.*; public class Exercise { public static void main() { for(char c = 'd'; c <= 'n'; c++) { if (c == 'k') break; Console.WriteLine(c); } } } This would produce: d e f g h i j The break statement can also be used in a do…while or a for loop the same way. |
The continue statement uses the following formula: continue; When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, do…while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. The following programs asks the user to type 4 positive numbers and calculates the sum of the numbers by considering only the positive ones. If the user types a negative number, the program manages to ignore the numbers that do not fit in the specified category: |
package Exercise; import System.*; public class Exercise { public static void main() { // Declare necessary variables double number, sum = 0; String strNbr; // Request 4 positive numbers from the user Console.WriteLine("Type 4 positive numbers."); // Make sure the user types 4 positive numbers for( int count = 1; count <= 4; count++ ) { Console.Write("Number: "); strNbr = Console.ReadLine(); number = Double.parseDouble(strNbr); // If the number typed is not positive, ignore it if( number < 0 ) continue; // Add each number to the sum sum += number; } // Display the sum Console.WriteLine("Sum of the numbers you entered = {0}", (System.Double)sum); } }
This would produce:
Type 4 positive numbers. Number: 24.55 Number: 826.08 Number: 1450.85 Number: 262.58 Sum of the numbers you entered = 2564.06
Introduction |
The conditional statements we have used so far were applied to single situations. You can combine statements using techniques of logical operations to create more complex and complete expressions. One way to do this is by making sure that two conditions are met for the whole expression to be true. On the other hand, one or the other of two conditions can produce a true condition, as long as one of them is true. This is done with logical conjunction or disjunction. In the beginning of the previous lesson, we described ways to write clear, simple, and logical statements. The techniques are even more important when combining statements because, once again, you should be able to make a decision based on a short, truthful, and clear statement. One of the operations used in combining two statements consists of validating an expression made of two parts only if both parts of the statement are true. Imagine that a sport camp states on an application form that an interested candidate must be "a man at least 18 years old". This condition can be divided in two statements as follows:
The program to process an application can look like this: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Full Name: Ernestine Monay Gender(1=Male/0=Female): 6 Age: 16 Every time a new person has filled an application, his or her information would be evaluated according to the above statements:
If we evaluate these statement separately, we can tabulate them as follows:
Suppose an applicant answers the first question as being a female, but the statement on the application said that an applicant must be a male. Once this statement produces a false result. We don't care how old the applicant is, the whole statement would be false. This would produce the following table:
Here is an example of processing and validating the first question: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); if( gender == 1 ) { // If the applicant is a man, then we can continue Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); } else // If the applicant is not a man, let the applicant know Console.WriteLine("You don't qualify"); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Full Name: Samuel Golfer Gender(1=Male/0=Female): 1 Age: 16 Here is another example of running the same program: Enter the following pieces of information Full Name: Germain Gobb Gender(1=Male/0=Female): 6 You don't qualify If an application answers the first question and indicates that he is a man, then we can process the second question. If the applicant indicates that he is younger than 18, the second statement is false. Consequently, the applicant doesn't qualify. The process this second question, we can nest a condition and change the program as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); if( gender == 1 ) { // If the applicant is a man, then we can continue Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); if( age < 18 ) Console.WriteLine("You are not old enough!"); } else // If the applicant is not a man, let the applicant know Console.WriteLine("You don't qualify"); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Full Name: Joseph Davis Gender(1=Male/0=Female): 5 You don't qualify Here is another example of running the same program: Enter the following pieces of information Full Name: Thomas Lemm Gender(1=Male/0=Female): 1 Age: 16 You are not old enough! This would produce the following table:
In the same way, if the applicant answers to be a female and younger than 18, the whole statement is still false. This would produce the following table:
As a consequence, an applicant qualifies only if he is a male and at least 18. The program that evaluates this c an be written as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); if( gender == 1 ) { // If the applicant is a man, then we can continue Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); if( age < 18 ) Console.WriteLine("You are not old enough!"); else Console.WriteLine("Your application is valid"); } else // If the applicant is not a man, let the applicant know Console.WriteLine("You don't qualify"); Console.WriteLine(); } } This shows that an applicant qualifies only if both statements are true. In the above section, to evaluate related statements, we proceeded by nesting them, which made our program complete but longer. To process this type of related statements, you can combine them using the Boolean AND operator. Based on this, a statement such as "The applicant must be a man at least 18 years old" can be segmented in two statements joined as follows: "The applicant is a man" AND "The applicant is at least 18 years old" In C#, the logical conjunction is performed using the && operator. A combination of A AND B can be represented as follows:
The expression that evaluates this combined statement can be written as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); if( gender == 1 && age >= 18 ) Console.WriteLine("Your application is valid"); else Console.WriteLine("You don't qualify"); Console.WriteLine(); } } Based on the rules of operator, this logical operation will work. The compiler will evaluate the "Gender == 1" condition first, then it will evaluate the "Age >= 18" condition, then it will combine the first to the second. Sometime this expression can appear confusing to read. If you want, you can include each part of the combination in its own parentheses. Here is an example: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int gender; int age; Console.WriteLine("Enter the following pieces of information"); Console.Write("Full Name: "); fullName = Console.ReadLine(); Console.Write("Gender(1=Male/0=Female): "); gender = Integer.parseInt(Console.ReadLine()); Console.Write("Age: "); age = Integer.parseInt(Console.ReadLine()); if( (gender == 1) && (age >= 18) ) Console.WriteLine("Your application is valid"); else Console.WriteLine("You don't qualify"); Console.WriteLine(); } } This makes the program easier to read.
This can be represented in a truth table as follows:
Based on this table, here is an example of running the program: Enter the following pieces of information Full Name: Germain Asse Gender(1=Male/0=Female): 0 Age: 16 You don't qualify
This can be represented in a truth table as follows:
Based on this table, here is an example of running the program: Enter the following pieces of information Full Name: Germain Asse Gender(1=Male/0=Female): 0 Age: 24 You don't qualify In the same way
This can be represented in a truth table as follows:
Based on this table, here is an example of running the program: Enter the following pieces of information Full Name: Germain Asse Gender(1=Male/0=Female): 1 Age: 14 You don't qualify
This results in:
Based on this table, here is an example of running the program: Enter the following pieces of information Full Name: Germain Asse Gender(1=Male/0=Female): 1 Age: 22 Your application is valid The above tables can be combined into one as follows:
|
Practical Learning: Using the Logical AND Operator |
package MVA; import System.*; public class Exercise { public static void main() { final int NewDriversLicense = 1; final int UpgradeFromIDCard = 2; final int TransferFromAnotherState = 3; int typeOfApplication; String firstName, lastName; String strOrganDonor; char gender; char DLClass; Console.WriteLine(" -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Application ---"); do { Console.WriteLine(" - Select the type of application -"); Console.WriteLine("1 - Applying for a brand new Driver's License"); Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License"); Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state"); Console.Write("Your Choice: "); typeOfApplication = Integer.parseInt(Console.ReadLine()); Console.WriteLine(""); if( typeOfApplication > 3 ) Console.WriteLine("Please enter a valid number as 1, 2, or 3"); } while(typeOfApplication > 3); Console.Write("First Name: "); firstName = Console.ReadLine(); Console.Write("Last Name: "); lastName = Console.ReadLine(); do { Console.Write("Gender(F=Female/M=Male): "); gender = Char.Parse(Console.ReadLine()); if( (gender != 'f') && (gender != 'F') && (gender != 'm') && (gender != 'M') ) Console.WriteLine("\nInvalid Answer - Try Again"); } while( (gender != 'f') && (gender != 'F') && (gender != 'm') && (gender != 'M') ); Console.WriteLine(" - Driver's License Classes -"); Console.WriteLine("A - All Non-commercial vehicles except motorcycles"); Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs."); Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs."); Console.WriteLine("K - Mopeds"); Console.WriteLine("M - Motorcycles"); Console.Write("Your Choice: "); DLClass = Char.Parse(Console.ReadLine()); do { Console.Write("Are you willing to be an Organ Donor(y=Yes/n=No)? "); strOrganDonor = Console.ReadLine(); if( !(strOrganDonor.Equals("y")) && !(strOrganDonor.Equals("Y")) && !(strOrganDonor.Equals("n")) && !(strOrganDonor.Equals("N")) ) Console.WriteLine("\nInvalid Answer"); } while( !(strOrganDonor.Equals("y")) && !(strOrganDonor.Equals("Y")) && !(strOrganDonor.Equals("n")) && !(strOrganDonor.Equals("N")) ); Console.WriteLine("\n -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Information ---"); Console.Write("Type of Application: "); switch(typeOfApplication) { case NewDriversLicense: Console.WriteLine("New Driver's License"); break; case UpgradeFromIDCard: Console.WriteLine("Upgrade From Identity Card"); break; case TransferFromAnotherState: Console.WriteLine("Transfer From Another State"); break; default: Console.WriteLine("Not Specified"); break; } Console.WriteLine("Full Name: {0} {1}", firstName, lastName); Console.Write("Gender: "); if( gender == 'f' ) Console.WriteLine("Female"); else if( gender == 'F' ) Console.WriteLine("Female"); else if( gender == 'm' ) Console.WriteLine("Male"); else if( gender == 'M' ) Console.WriteLine("Male"); else Console.WriteLine("Unknown"); switch(DLClass) { case 'a': case 'A': Console.WriteLine("Class: A"); break; case 'b': case 'B': Console.WriteLine("Class: B"); break; case 'c': case 'C': Console.WriteLine("Class: C"); break; case 'k': case 'K': Console.WriteLine("Class: K"); break; case 'm': case 'M': Console.WriteLine("Class: M"); break; default: Console.WriteLine("Class: Unknown"); break; } Console.Write("Organ Donor? "); if( strOrganDonor.Equals("y") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("Y") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("n") ) Console.WriteLine("No"); else if( strOrganDonor.Equals("N") ) Console.WriteLine("No"); else Console.WriteLine("Can't Decide"); Console.WriteLine(); } } |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 6 Please enter a valid number as 1, 2, or 3 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 3 First Name: Larry Last Name: Edmonston Sex(F=Female/M=Male): g Invalid Answer - Try Again Sex(F=Female/M=Male): m - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: b Are you willing to be an Organ Donor(1=Yes/0=No)? 8 Invalid Answer Are you willing to be an Organ Donor(1=Yes/0=No)? 1 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: Transfer From Another State Full Name: Larry Edmonston Sex: Male Class: B Organ Donor? Yes Press any key to continue |
Imagine you are looking for a job and you come to an ad that states, "Programmer needed, an applicant should be a Microsoft Certified Application Developer (MCAD). If you are not an MCAD, you must have at least a bachelor's degree". This announcement can be resumed to the following statement: "The applicant must either be an MCAD or must have a bachelor's degree". It can be further segmented in two sub-statements as follows:
The program to process an application can appear as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int MCAD; int degree; Console.WriteLine("Enter the following pieces of information"); Console.Write("Applicant's Name: "); fullName = Console.ReadLine(); Console.Write("Are you an MCAD (1=Yes/0=No)? "); MCAD = Integer.parseInt(Console.ReadLine()); Console.Write("Do you hold a bachelor's degree (1=Yes/0=No)? "); degree = Integer.parseInt(Console.ReadLine()); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Applicant's Name: Paul Brownies Are you an MCAD (1=Yes/0=No)? 4 Do you hold a bachelor's degree (1=Yes/0=No)? 6 When a new applicant applies for a job, his or her information is evaluated:
If an applicant indicates in the first question that he or she is an MCAD, we wouldn't care about the second question. This resulting statement can be represented as follows:
Here is an example of processing and validating the first question: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int MCAD; int degree; Console.WriteLine("Enter the following pieces of information"); Console.Write("Applicant's Name: "); fullName = Console.ReadLine(); Console.Write("Are you an MCAD (1=Yes/0=No)? "); MCAD = Integer.parseInt(Console.ReadLine()); Console.Write("Do you hold a bachelor's degree (1=Yes/0=No)? "); degree = Integer.parseInt(Console.ReadLine()); if( MCAD == 1 ) Console.WriteLine("Since you are an MCAD, you qualify"); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Applicant's Name: Saul Kemmel Are you an MCAD (1=Yes/0=No)? 4 Here is another example of running the same program: Enter the following pieces of information Applicant's Name: Saul Kemmel Are you an MCAD (1=Yes/0=No)? 1 Since you are an MCAD, you qualify If the answer to the first question indicates that an applicant is not an MCAD, then we would be interested in the answer to the second question. If the second answers shows that the applicant has a bachelor's degree, then he or she qualifies. In fact in this case, the answer to the first question would not be important:
The second question can be addressed as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int MCAD; int degree; Console.WriteLine("Enter the following pieces of information"); Console.Write("Applicant's Name: "); fullName = Console.ReadLine(); Console.Write("Are you an MCAD (1=Yes/0=No)? "); MCAD = Integer.parseInt(Console.ReadLine()); Console.Write("Do you hold a bachelor's degree (1=Yes/0=No)? "); degree = Integer.parseInt(Console.ReadLine()); if( MCAD == 1 ) Console.WriteLine("Since you are an MCAD, you qualify"); if( degree == 1 ) Console.WriteLine("Since you have the necessary degree, you qualify"); Console.WriteLine(); } } Here is an example of running the program: Enter the following pieces of information Applicant's Name: Annie Baugh Are you an MCAD (1=Yes/0=No)? 8 Do you hold a bachelor's degree (1=Yes/0=No)? 1 Since you have the necessary degree, you qualify In the same way, if an applicant is an MCAD and holds a bachelor's degree, he or she still qualifies. This produce the following table:
Based on this, here is an example of running the program: Enter the following pieces of information Applicant's Name: Jamie Konlo Are you an MCAD (1=Yes/0=No)? 1 Do you hold a bachelor's degree (1=Yes/0=No)? 1 Since you are an MCAD, you qualify Since you have the necessary degree, you qualify Therefore, if an application either is an MCAD or has a degree or fulfills both criteria, he or she qualifies. If a candidate neither is an MCAD nor has the degree, he or she cannot have the job. This can be resumed as follows:
Writing both statements separately can appear redundant. Instead, if you are evaluating two statements but the truthfulness of only one is enough to render both as true, you can perform a Boolean disjunction operation. This is also called an OR operator. Using this operator, our two statements can be combined as "The applicant is an MCAD" OR "The applicant has a bachelor's degree". In C#, the logical disjunction is performed using the || operator. A combination of A || B can be represented as follows:
The expression that evaluates this combined statement can be written as follows: package Exercise; import System.*; public class Exercise { public static void main() { String fullName; int MCAD; int degree; Console.WriteLine("Enter the following pieces of information"); Console.Write("Applicant's Name: "); fullName = Console.ReadLine(); Console.Write("Are you an MCAD (1=Yes/0=No)? "); MCAD = Integer.parseInt(Console.ReadLine()); Console.Write("Do you hold a bachelor's degree (1=Yes/0=No)? "); degree = Integer.parseInt(Console.ReadLine()); if( MCAD == 1 || degree == 1 ) Console.WriteLine("Since you are an MCAD OR you have the necessary degree, you qualify"); else Console.WriteLine("We will get back to you"); Console.WriteLine(); } } Once again, based on the rules of operators precedence, the "MCAD == 1 || Degree == 1" expression will work fine. If it appears difficult to read, you can include each part in its parentheses as (MCAD == 1) || (Degree == 1). Here is an example of running the program: |
Enter the following pieces of information Applicant's Name: Sally Kirkfield Are you an MCAD (1=Yes/0=No)? 1 Do you hold a bachelor's degree (1=Yes/0=No)? 8 Since you are an MCAD OR you have the necessary degree, you qualify
Here is another example of running the same program:
Enter the following pieces of information Applicant's Name: Leslie Stanislaw Are you an MCAD (1=Yes/0=No)? 0 Do you hold a bachelor's degree (1=Yes/0=No)? 0 We will get back to you
Practical Learning: Using the Logical OR Operator |
package MVA; import System.*; public class Exercise { public static void main() { final int NewDriversLicense = 1; final int UpgradeFromIDCard = 2; final int TransferFromAnotherState = 3; int typeOfApplication; String firstName, lastName; String strOrganDonor; char gender; char DLClass; Console.WriteLine(" -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Application ---"); do { Console.WriteLine(" - Select the type of application -"); Console.WriteLine("1 - Applying for a brand new Driver's License"); Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License"); Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state"); Console.Write("Your Choice: "); typeOfApplication = Integer.parseInt(Console.ReadLine()); Console.WriteLine(""); if( typeOfApplication < 1 || typeOfApplication > 3 ) Console.WriteLine("Please enter a valid number as 1, 2, or 3"); } while(typeOfApplication < 1 || typeOfApplication > 3); Console.Write("First Name: "); firstName = Console.ReadLine(); Console.Write("Last Name: "); lastName = Console.ReadLine(); do { Console.Write("Gender(F=Female/M=Male): "); gender = Char.Parse(Console.ReadLine()); if( (gender != 'f') && (gender != 'F') && (gender != 'm') && (gender != 'M') ) Console.WriteLine("\nInvalid Answer - Try Again"); } while( (gender != 'f') && (gender != 'F') && (gender != 'm') && (gender != 'M') ); Console.WriteLine(" - Driver's License Classes -"); Console.WriteLine("A - All Non-commercial vehicles except motorcycles"); Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs."); Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs."); Console.WriteLine("K - Mopeds"); Console.WriteLine("M - Motorcycles"); Console.Write("Your Choice: "); DLClass = Char.Parse(Console.ReadLine()); do { Console.Write("Are you willing to be an Organ Donor(y=Yes/n=No)? "); strOrganDonor = Console.ReadLine(); if( !(strOrganDonor.Equals("y")) && !(strOrganDonor.Equals("Y")) && !(strOrganDonor.Equals("n")) && !(strOrganDonor.Equals("N")) ) Console.WriteLine("\nInvalid Answer"); } while( !(strOrganDonor.Equals("y")) && !(strOrganDonor.Equals("Y")) && !(strOrganDonor.Equals("n")) && !(strOrganDonor.Equals("N")) ); Console.WriteLine("\n -=- Motor Vehicle Administration -=-"); Console.WriteLine(" --- Driver's License Information ---"); Console.Write("Type of Application: "); switch(typeOfApplication) { case NewDriversLicense: Console.WriteLine("New Driver's License"); break; case UpgradeFromIDCard: Console.WriteLine("Upgrade From Identity Card"); break; case TransferFromAnotherState: Console.WriteLine("Transfer From Another State"); break; default: Console.WriteLine("Not Specified"); break; } Console.WriteLine("Full Name: {0} {1}", firstName, lastName); Console.Write("Gender: "); if( gender == 'f' ) Console.WriteLine("Female"); else if( gender == 'F' ) Console.WriteLine("Female"); else if( gender == 'm' ) Console.WriteLine("Male"); else if( gender == 'M' ) Console.WriteLine("Male"); else Console.WriteLine("Unknown"); switch(DLClass) { case 'a': case 'A': Console.WriteLine("Class: A"); break; case 'b': case 'B': Console.WriteLine("Class: B"); break; case 'c': case 'C': Console.WriteLine("Class: C"); break; case 'k': case 'K': Console.WriteLine("Class: K"); break; case 'm': case 'M': Console.WriteLine("Class: M"); break; default: Console.WriteLine("Class: Unknown"); break; } Console.Write("Organ Donor? "); if( strOrganDonor.Equals("y") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("Y") ) Console.WriteLine("Yes"); else if( strOrganDonor.Equals("n") ) Console.WriteLine("No"); else if( strOrganDonor.Equals("N") ) Console.WriteLine("No"); else Console.WriteLine("Can't Decide"); Console.WriteLine(); } } |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 0 Please enter a valid number as 1, 2, or 3 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 4 Please enter a valid number as 1, 2, or 3 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 1 First Name: Jocelyne Last Name: Aladiere Sex(F=Female/M=Male): D Invalid Answer - Try Again Sex(F=Female/M=Male): g Invalid Answer - Try Again Sex(F=Female/M=Male): f - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: m Are you willing to be an Organ Donor(y=Yes/n=No)? d Invalid Answer Are you willing to be an Organ Donor(y=Yes/n=No)? p Invalid Answer Are you willing to be an Organ Donor(y=Yes/n=No)? Y ======================================= -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: New Driver's License Full Name: Jocelyne Aladiere Sex: Female Class: M Organ Donor? Yes ======================================= |
|
||
Previous | Copyright © 2005-2016, FunctionX | Next |
|