Chapter. Solving Problems that Require Decisions. Objectives: At the end of the chapter students should be able to:

Size: px
Start display at page:

Download "Chapter. Solving Problems that Require Decisions. Objectives: At the end of the chapter students should be able to:"

Transcription

1 Chapter 13 Solving Problems that Require Decisions Objectives: At the end of the chapter students should be able to: Design programs that correctly use decision logic Correctly write and evaluate simple Boolean expressions. Correctly use logical AND and OR to create Boolean expressions. Describe the precedence rules for C# operators. Explain how short-circuit evaluation of a Boolean expression works. Correctly use the if conditional statement in a C# program. Correctly use the if- statement in a C# program. Correctly use nested if- statements in a C# program. Correctly use a switch statement in a C# program. Correctly use a conditional (?:) statement in a C# program. Describe and correctly use enumerations in a C# program. Contents of This Chapter 13.1 Branches and Conditions 13.2 Designing Programs that use Conditional Statements 13.3 The switch statement 13.3B The conditional (?:) statement 13.4 Enumerations 13.5 Using Logical Operators to Combine Conditions 13.6 Comparing Characters 13.7 Comparing Real Numbers 13.8 Designing Decision Logic 13.9 Syntax pages Good Programming Practice Beyond the Basics Programming Projects

2 Chapter 13: Solving Problems that Require Decisions The term flow of control refers to the path that is taken through a program as it executes. Unless told to do otherwise, a program starts executing with the first executable statement in Main( ), and continues sequentially, line by line until the end of the program is reached. However, most computing problems you will deal with in real The term flow of control refers to the path that is taken through a life cannot be solved with programs that execute in this simple, linear program as it executes. fashion. It is more common to find programs that take different paths through the code, based on conditions that may exist within the program at the time. For example, a chess playing program may take many different paths through the same code, based on where the pieces on the chessboard are located at the given time BRANCHES AND CONDITIONS Branches occur in a program when the flow of control changes based on some condition being true or false. When reading through a problem statement, such conditions are often prefixed with the word if. For example, if the balance in this account is less than $1,000, if the king is in check, if the triangle has a right angle. A branch occurs when the flow of control changes because some condition is tested. Sometimes the word when is used to signal a condition instead, as in these examples, when the balance in this account is less than $1,000, when the king is in check, when the triangle has a right angle CONDITIONS AND ACTIVITY DIAGRAMS How do you show a condition in an activity diagram? A condition is shown by drawing a diamond shape, and writing the condition inside of the diamond, as shown in the Figure Here we are testing to see if a person s age is less than 21. Since this condition can only be true or false, two paths exit the diamond shape. FIGURE 13.1 IF DIAGRAM - 2 -

3 One of these paths is taken when the condition is true. The other is taken when the condition is false THE IF STATEMENT Conditions are tested with an if statement. An if statement allows a single statement to be executed when a condition is true. If the condition is false, that statement is skipped. Let s illustrate this by using the condition (age < 21) in an if statement: if ( age < 21) WriteLine( Youth is a wonderful thing ); Conditions are tested with an if statement When the value of age is less than 21, the expression WriteLine( Youth is a wonderful thing ); gets executed. However, if the value of age is not less than 21, this expression is skipped and execution moves on to the next line in the program. Let s write a small program that uses the if statement we just described. We want this program to ask the user their age. When the user responds, the program will prompt user to enter in their age store the user s response in the variable age and then print out the message Youth is a wonderful thing enjoy it, if the value stored in age is less than 21. Otherwise, we want this statement to be skipped and the get user input and save in age program to print a goodbye message and exit. The activity diagram for this program is shown on the right in figure is age < 21? true print Youth is... false print goodbye end FIGURE 13.2 IF ACTIVITY DIAGRAM

4 Chapter 13: Solving Problems that Require Decisions Writing the code shown in this activity diagram gives the program shown in Code Listing // code listing 13.1 using System; using static System.Console; static public class Program // use this constant to test the user's age const int MINOR = 21; static public void Main() int age = 0; // prompt the user and get the input Write("How old are you? "); age = int.parse(readline()); // Here is the if statement if (age < MINOR) WriteLine("Youth is a wonderful thing... enjoy it."); WriteLIne( Goodbye ); ReadKey(true); //End Main() //End class Program BOOLEAN EXPRESSIONS AND RELATIONAL OPERATORS The expression (age < MINOR) is called a Boolean expression., When it is evaluated, the expression will only yield the value true or false. When a Boolean expression is We call these Boolean values. When writing a Boolean expression, evaluated, the result will either relational operators are used to express a relationship between two be true or false. values. In this example, the relational operator < has been used. The operator has the conventional mathematical meaning of less than. Table 13.1 describes the standard relational operators

5 Operator Meaning Example == equal a == b!= not equal a!= b < less than a < b <= less than or equal a <= b > greater than a > b >= greater than or equal a >= b TABLE 13.1 THE RELATIONAL OPERATORS Note that the precedence of the relational operator is less than that of the arithmetic operators, so arithmetic operations are done first. So, for example, in the expression if ( a < b + c) b and c are added together first, then the result is compared with a. If you re not sure, you can always use an extra pair of parentheses to clarify the expression. if ( a < ( b + c ) ) THE IF-ELSE STATEMENT Sometimes you want to do one thing if a condition is true, but do something totally different when the condition is false. The if- statement provides a convenient way to do this. The if- statement is similar to the if statement. The difference is that the if- statement contains an clause that defines what is to be done when the Boolean expression that is being evaluated is false. This makes it possible for the program to take one course of action when the condition is true, but take an entirely different course of action when the condition is false FIGURE 13.3 DIAGRAM OF IF/ELSE

6 Chapter 13: Solving Problems that Require Decisions Let s use the if- statement in our age example. In this case, we want the message Youth is a wonderful thing enjoy it to be displayed when the value entered for age is less than 21. However, we want to display the message Old age is a state of mind when the value entered in is not less than 21. Study the activity diagram in Figure 13.3 to see how the flow of control changes, based on this condition. The code for this example is shown in Code Listing USING BLOCKS WITH CONDITIONAL CODE In the examples shown thus far, only one statement has been executed when a Boolean expression was evaluated as true. It is possible to write a program so that many statements can be executed when a condition is true. This is done by wrapping the statements to be executed in a block. A block in C# is any code that lies between an opening brace and a closing brace. A block of code enclosed in braces can be placed anywhere in a C# program where a single statement might otherwise be used. // code listing 13.2 using System; using static System.Console; static public class Program // use this constant to test the user's age const int MINOR = 21; static public void Main() int age = 0; // prompt the user and get the input Write("How old are you? "); age = int.parse(readline()); // Here is the if statement if (age < MINOR) WriteLine("Youth is a wondeful thing... enjoy it."); WriteLine("Old age is a state of mind...!"); ReadKey(true); //End Main() //End class Program - 6 -

7 In the following example the code will be similar to the code in listing 13.2, but will output slightly more complex messages after it determines the user s age. When the age entered by the user is less than 21, the program should display the message ******************************* * Youth is a wonderful thing * * Enjoy it * ******************************* When the age entered by the user is greater than or equal to 21, the program should display the message ******************************* * Old age is a * * State of mind * ******************************* The activity diagram for this program will be very nearly identical to that of Figure In fact, the logic will be identical. Only the text of the messages will be different. The program itself will look different because of the addition of blocks. The code is shown in Code Listing

8 Chapter 13: Solving Problems that Require Decisions // code listing 13.3 using System; using static System.Console; static public class Program // use this constant to test the user's age const int MINOR = 21; static public void Main() int age = 0; // prompt the user and get the input Write("How old are you? "); age = int.parse(console.readline()); // Here is the if statement if (age < MINOR) WriteLine("*****************************"); WriteLine("* Youth is a wondeful thing *"); WriteLine("* enjoy it. *"); WriteLine("*****************************"); WriteLine("*****************************"); WriteLine("* Old Age is *"); WriteLine("* a state of mind *"); WriteLine("*****************************"); ReadKey(true); //End Main() //End class Program - 8 -

9 NESTED IF/ELSE STATEMENTS Now let s consider the following problem. Suppose that we want to write a program that takes three integer values as its input (the values must all be different). We will store these values in the variables a, b, and c. We want the program to determine which of the three values is the smallest and display this value for the user. The logic to determine which of a, b, and c is the smallest might look something like that shown in figure Because we are dealing with multiple decisions, some of which depend on others, this logic is more complex than anything we have seen in the previous examples. FIGURE 13.4 NESTED IF/ELSE STATEMENTS Notice that the true path out of the first decision block in the diagram leads directly to another decision block, as does the false path. This kind of logic requires that the if- statements be nested. An if- statement is nested when the statement to be executed after the if part (or the part) is another if statement. To illustrate this, let s study Figure 13.4 carefully. We first test to see if a is less than b. If a is smaller than b we know for sure that b cannot be the smallest value. So we don t need to compare b and c. However, we are not sure at this point if a or c is the smallest. Therefore we must compare those two values. If a is also less than c, then a is clearly the smallest value and so that s what we will report to the user. However, if a is not less than c, then c must be the smallest value. The expressions that reflect this logic are if ( a < b) if (a < c) min = a; min = c; statements are always matched with the closest unmatched if. Now, what if a is not less than b? If a is not less than b, it cannot possibly be the smallest value. The smallest value must either be b or c. To figure out which of these is the smallest, we must compare them

10 Chapter 13: Solving Problems that Require Decisions Adding this step results in the code if ( a < b) if (a < c) min = a; min = c; if (b < c) min = b; min = c; Now, let s add parentheses to really make the code clear: if ( a < b) if (a < c) min = a; min = c; if (b < c) min = b; min = c;

11 The complete program that implements this logic is shown in code listing // Code Listing 13.4 using System; using static System.Console; static public class Program static public void Main() int a = 0, b = 0, c = 0; int min = 0; WriteLine("Enter three integer values: "); a = int.parse(readline( ) ); b = int.parse(readline( ) ); c = int.parse(readline( ) ); if ( a < b) if (a < c) min = a; min = c; if (b < c) min = b; min = c; WriteLine("The minimum value is min"); ReadKey(true); //End Main() //End class Program

12 Chapter 13: Solving Problems that Require Decisions When using nested if- statements, an clause is always matched to the closest unmatched if above it. The use of curly braces and indentation makes it easy to see which clause goes with which if. In Code Listing 13.5 without curly braces and indentation this is much more difficult to see. // Code Listing 13.5 using System; using static System.Console; static public class Program static public void Main() int a = 0, b = 0, c = 0; int min = 0;.WriteLine("Enter three integer values: "); a = int.parse(console.readline( ) ); b = int.parse(console.readline( ) ); c = int.parse(console.readline( ) ); if (a < b) if (a < c) min = a; min = c; if (b < c) min = b; min = c; WriteLine("The minimum value is 0", min); ReadKey(true); //End Main() //End class Program

13 When there is an if statement nested within an clause, such as is the case in our example... if ( b < c ) min = b; It is common to place the nested if statement on the same line as the, as if ( b < c ) min = b; NESTED IF/ELSE STATEMENTS VS. WRITING MANY IF STATEMENTS In the following program fragment, the user enters a value of N, S, E, or W to indicate a direction. The program then responds by telling the user what direction he or she is going. char direction = N ; Write( Enter N, S, E, or W to indicate a direction: ); direction = char.parse(readline( ) ); if (direction == N ) WriteLine( \n going North. ); if (direction == S ) WriteLine( \n going South. ); if (direction == E ) WriteLine( \n going East. ); if (direction == W ) WriteLine( \n going West. ); WriteLine( \n going nowhere ); How do you think that this code differs in execution from the following? char direction = Z ; Write( Enter N, S, E, or W to indicate a direction: ); direction = char.parse(readline( ) ); if (direction == N ) WriteLine( \n going North. );

14 Chapter 13: Solving Problems that Require Decisions if (direction == S ) WriteLine( \n going South. ); if (direction == E ) WriteLine( \n going East. ); if (direction == W ) WriteLine( \n going West. ); WriteLine( \n going nowhere ); Let s run through each code fragment with an example. Assume that the user types in the letter N. In the first code fragment, the if statement is executed and the condition is found to be true. The program prints the message going North.. Since all of the statements following the if statement are clauses, they are all skipped. No additional code gets executed. In the second code fragment, the if statement is executed and the condition is found to be true. The program prints the message going North. The second if condition is then evaluated. It is false. Then the third if condition is evaluated. It is also false. Finally the last if condition is evaluated. It is also false. The results of executing this code fragment are identical to what happens when the first code fragment is executed. The difference is that with the second code fragment, many lines of code get executed that don t have to be DANGLING ELSE CLAUSES Keep in mind the rule that unmatched clauses get matched to the closest unmatched if statement above it. To illustrate this, consider the following code fragment which purports to let the user know when overtime has exceeded some pre-determined limit: const int LIMIT = 40;... if (regtime > LIMIT) if (overtime > LIMIT) WriteLine( \novertime hours exceed the limit. ); WriteLine( \nno overtime worked. ); Visually, the clause has been matched with the first if statement. This would lead one to believe that this clause only gets executed when the value of regtime is less than the value of

15 LIMIT. However, the compiler matches the clause with the closest unmatched if, which is the second one. The compiler sees the code as if it had been written const int LIMIT = 40;... if (regtime > LIMIT) if (overtime > LIMIT) WriteLine( \novertime hours exceed the limit. ); WriteLine( \nno overtime worked. ); To match the clause with the first if statement, use braces as shown here: const int LIMIT = 40;... if (regtime > LIMIT) if (overtime > LIMIT) WriteLine( \novertime hours exceed the limit. ); WriteLine( \nno overtime worked. ); 13.2 DESIGNING PROGRAMS THAT USE CONDITIONAL STATEMENTS The following steps should prove useful when designing a solution to problems that contain conditional statements. Carefully read through the problem statement. If the problem description contains the words if or when, it is very likely that the program will require the use of conditional statements. Sometimes the use of if is not explicit, and must be inferred. Consider for example, the following problem statement:

16 Chapter 13: Solving Problems that Require Decisions A triangle whose sides are all of equal length is called an equilateral triangle. A triangle with two equal sides is called an isosceles triangle. A triangle whose sides are all of different lengths is called a scalene triangle. Write a program that asks for the lengths of the three sides of a triangle, and then tells the user what kind of triangle it is. Although it is not stated explicitly, this program must determine if a triangle has two equal sides or if it has three equal sides. If it is clear that a problem will require the use of conditional statements, write down the various conditions that can occur. Decide what it is that makes each condition unique. In the above example, there are three conditions that can occur: All sides of the triangle are equal. Only two sides of the triangle are equal. Each side of the triangle is of a different in length. For each condition, write down what the program should do differently. Begin each sentence with the word if. In the triangle problem, these statements would be If all sides of the triangle are equal, display Equilateral. If only two sides of the triangle are equal, display Isosceles. If no sides of the triangle are the same length, display Scalene. Now formulate the if/ statements that reflect this set of conditions. If there are multiple conditions, then nested if/ statements may be required. In the triangle problem the required statements can be derived by considering each pair of sides in turn. Let the length of the sides be a, b, and c:

17 if (a == b) if (b == c) WriteLine( \nequilateral ); WriteLine( \nisosceles ); if (b == c a == c) WriteLine( \nisosceles ); WriteLine( \Scalene ); Be careful that each statement is properly formed, and that each matches the correct if THE?: STATEMENT The Conditional operator?: is the only ternary operator in the C# programming language. An example using this statement is string stg = (a > b)? I m true : I m false ; The first operand (a > b)? asks the question, is a greater than b? and if it is true, the second operand expression immediately following it, I m true is returned. If the result of the question is false the third operand expression, I m false is executed and the result is returned. Note the data-type of the second operand expression and the third operand expression must be the same. In the case of the Conditional statement above the data-type returned is string. An example of a conditional statement that returns a double: double a = 5.5, b = 3.5, c = 7.5; double data = (a > b && a < c)? a : -1.0;

18 Chapter 13: Solving Problems that Require Decisions 13.4 THE SWITCH STATEMENT A problem contains many different conditions, usually involving multiple if- statements that could occur, C# provides an easy way of expressing these conditions and the actions to take for each. Consider the problem given previously where the user enters a character to indicate a direction. The code fragment that dealt with this situation looked like if (direction == N ) WriteLine( \n going North. ); if (direction == S ) WriteLine( \n going South. ); if (direction == E ) WriteLine( \n going East. ); if (direction == W ) WriteLine( \n going West. ); WriteLine( \n going nowhere ); In C# this code could also be written using a switch statement instead of the complex if- statements. switch (direction) case 'N': WriteLine("... going North."); break; case 'S': WriteLine("... going South."); break; case 'E': WriteLine("... going East."); break; case 'W': WriteLine("... going West."); break; default: WriteLine("... going nowhere."); break; //End switch

19 The switch keyword is followed by an expression enclosed in parenthesis and a statement containing a block delimited by opening and closing braces. Within the block each possible value of the variable direction is stated as a separate case. The code to be executed for each case follows the case statement. Note that brackets are not required here to define the block of code to be executed for each case. However, braces can be used if desired. Each block of code must end with a break statement. The break statement causes control to flow to the end of the switch, skipping the other cases. The expression following the switch must return a value that is of type integer, character, enumeration or string. Other types of data are not allowed. A case statement followed by one or more statements and not terminated by a break is a compiler error. This is called a fall through condition. The switch expression and case statements must be of the integral types, char types, enumerations, bool or strings case operands be literals or constants. You may also have one case immediately followed by another case as long as there is no intervening code statements between them ENUMERATIONS Enumerations are user defined named constant data types that contain set of valid values defined by a comma delimited list of identifiers, such as enum DayOfWeek, MON=0, TUE=1, WED=2, THU=3, FRI=4, SAT=5, SUN=6; The name of this enumeration type is DayOfWeek. A variable of this data-type can only have one of the values SUN, MON, TUE, WED, THU, FRI, or SAT. Internally, these values are represented by the integer values 0 through 6. Each value need not be explicitly mentioned when declaring an enumeration. When one value is specified, the remaining values are just increments of one. For example, in the declaration enum DayOfWeek MON=1, TUE, WED, THU, FRI, SAT, SUN; the value for MON is 1, the value for TUE is 2, and so on. If no values are explicitly given, then the first assigned value is zero, and each value after that is incremented by one, and we can write enum DayOfWeek MON, TUE, WED, THU, FRI, SAT, SUN ; Unless there is a good reason for explicitly assigning values to each entry in the comma delimited list, it is best to just use this latter form of the enumeration

20 Chapter 13: Solving Problems that Require Decisions Enumerations are particularly useful in switch statements. Using an enumeration doesn t change the way that the switch works, but it often makes the code more readable. Consider, for example the enumeration enum DayOfWeek MON, TUE, WED, THU, FRI, SAT, SUN ; The values MON, TUE, and so on can now be used to label the cases in a switch statement, as shown in the following code. switch ( whichday ) case DayOfWeek.MON: WriteLine( Today is Monday ); break; case DayOfWeek.TUE: WriteLine( Today is Tuesday ); break;... By placing the using static DayOfWeek; in the using statements the data-type DayOfWeek can be omitted as shown below: switch ( whichday ) case MON: WriteLine( Today is Monday ); break; case TUE: WriteLine( Today is Tuesday ); break; USING LOGICAL OPERATORS TO COMBINE CONDITIONS Oftentimes a problem statement will contain multiple conditions that have to be true at the same time. For example, consider the statement If it is Friday night and I have no homework then I can go to the movies. In order to go to the movies two conditions must be true. It must be a Friday night, and I must not have any homework. It is possible to combine both of these conditions into a single statement by using logical operators

21 The logical operators in C# are written as! (NOT), && (AND), and (OR). The result of using each logical operator is defined in a Truth Table. The truth table for the NOT operator (!) is shown in Figure 13.5, below.! Truth Table a true! a false false true FIGURE 13.5 NOT TRUTH TABLE As shown in the table, the NOT operator! reverses the value of a Boolean. For example, the following expression tests for a not less than b: if! (a < b). Note that you cannot write if (a!< b), this is not valid C# syntax. However, you can write if ( a >= b) which has the same meaning in this case. That is, if a is not less than b, it must be equal to or greater than b

22 Chapter 13: Solving Problems that Require Decisions The truth table for the && operator is shown in Figure When two conditions are joined together by an AND operation, the result is true if and only if when both of the conditions are true. In all other cases, the result of ANDing the two conditions together is false. The AND operator is perfect for the going to the Movies case discussed at the beginning of this section, which might be written something like if ( today == FRIDAY && homework == NO) gotomovies( ); && Truth Table a b a && b true true true true false false false true false false false false FIGURE 13.6 AND TRUTH TABLE Notice that the expression on either side of the && operator must be valid Boolean expressions. For example, the expression to test the value of a to see if it lies between 10 and 25 cannot be written as if ( a > 10 && < 25). The syntax of this statement is incorrect, since < 25 is not a valid Boolean expression. The correct way to write this would be if (a > 10 && a < 25). The truth table for the operator is shown in Figure When two conditions are joined together by an OR operation, the result is true when one or the other, or both of the joined conditions are true. When both conditions are false, the OR of those two conditions is also false

23 Truth Table a b a b true true true true false false false true false true true false FIGURE 13.7 OR TRUTH TABLE Multiple conditions can be combined using the logical operators. For example, consider the statement If it is a Friday Night or a Saturday night and I have no homework, I ll go to the movies. Here there are three conditions to be met. The statement to test all three of these might be written as if (today == FRIDAY today == SATURDAY && homework == NO) GotoMovies( ); Using the conditional operator: String message = (today==friday today ==SATURDAY && homework==no)? GotoMovies( ) : DoHomeWork();

24 Chapter 13: Solving Problems that Require Decisions The && operation has higher precedence than the operation, so the test for today being Friday OR Saturday is done first. The result of this test is then ANDed with the test for homework. The relational operators all have higher precedence than the Boolean operators. Parentheses can always be used to change the order of evaluation SHORT CIRCUITING The && operator and the operator both use a short-circuiting technique to eliminate unnecessary computation. The shortcut technique for the && operator works as follows. Recall that the && operation requires both the left hand condition and the right hand condition be true in order for the result to be true. So, the && operator looks first at the left hand condition. If it is false, there is no way that the result can be true, so the right hand condition is never evaluated. This saves the computing time required to determine whether or not this condition is true. Only when the left hand condition is true is the right hand condition evaluated. The shorthand technique for the operator works in a similar fashion. Since only one of the conditions being combined with an OR must be true for the result to be true, the left hand condition is evaluated first. If it is true, then the right hand condition is never evaluated. Only when the left hand condition is false, is the right hand condition evaluated COMPARING CHARACTERS When characters are compared, they are compared in the order in which they appear in the ASCII code table. Unicode is a superset of When characters are ASCII and for our purposes the ASCII codes will suffice. Codes in the compared, they are compared ASCII code table are in alphabetical order, but note that all upper case in the order that they appear characters appear before the lower case characters in the table. Thus, in the ASCII code table. for example, the character A will be less than the character a. This condition occurred because in the earlier specification of the ASCII character set only allowed upper case characters and later the lower case characters were added and in order to maintain backward compatibility with the older ASCII characters sets the lower case characters had to be given a larger numeric value COMPARING REAL NUMBERS Remember that real numbers are only approximated in the computer s memory. Therefore, a test for equality might not always work correctly. For example, suppose that the value of b, a floating point number, has been calculated by executing a number of different steps in a program. The

25 resulting value may suffer from round-off error or loss of precision because of the way that floating point values are stored in computer memory. So, an expression such as if ( a == b) might not return a value of true, even though the values of a and b are very, very close. The solution to this problem is based on deciding how close the numbers must be to each other in the context of the problem being solved, in order for the two numbers to be considered equal. Call this value EPSILON. Now subtract a from b and see if the absolute value of this difference is less than EPSILON. If it is, you can consider a and b to be equal DESIGNING DECISION LOGIC Use the following steps to design code that requires decision logic: 1. Carefully inspect the problem statement. If the word if or the word when is used to describe different situations that might exist in the problem, then your program will need to use conditional statements. 2. After determining that several different situations might exist, try to identify each unique situation. Write down the condition that makes this situation unique. Carefully check to make sure that conditions do not overlap one another. Be sure boundary conditions are correctly stated. 3. Write down exactly what the program should do differently for each of the unique situations you have identified. 4. Formulate if/ statements that reflect the different situations you came up with. Make them as simple as possible. Watch for dangling s

26 Chapter 13: Solving Problems that Require Decisions 13.9 SYNTAX PAGES The if statement The if/ statement The?: (conditional) statement

27 The conditional statement must return the same data-type for both the true expression (expression after the?) and the false expression (expression after the : ), in the code snippet above this is a string that is passed to the WriteLine method The Switch statement

28 Chapter 13: Solving Problems that Require Decisions GOOD PROGRAMMING PRACTICE Carefully think through the end-points of a problem, so that you test for the proper condition in an if statement. It is easy to make the mistake of using <= when just < would be correct. When you are using an if- statement, put the code that you think should normally be executed after the if part of the statement, not the part. When you have a long list of conditions to test, use if- statements instead of plain if statements or even a switch statement. Order the conditions according to which you think will occur most frequently. When writing switch statements, keep the code within each case as simple as possible. Use braces to enclose the actions to take for an if or statement, even if you only have a single statement to enclose. Use the?: conditional operator for a concise way to provide a true or false return of a specific data-type. Code is generally clearer when a Boolean expression is stated in positive terms instead of negative terms. Use parenthesis liberally. Be sure that you understand the short circuiting rules for evaluating Boolean expressions

29 13.11 BEYOND THE BASICS With a simple sequential set of statements it is easy to trace the path taken as a program executes one statement just executes after the other. But now that we have added the ability to make decisions and execute different paths in a program based on a decision, it becomes more difficult to trace what is happening as our programs executes. One of the most powerful tools you can use to help you trace a program s execution is the debugger DEBUGGING WITH VISUAL C# COMMUNITY EDITION Visual C# Community Edition provides a very rich set of tools to help you locate and fix mistakes in your programs. In this section we will introduce you to some of those tools. To illustrate, consider the program shown in figure FIGURE 13.8: SAMPLE PROGRAM

30 Chapter 13: Solving Problems that Require Decisions Suppose that we wanted to trace the execution path through this program given some set of values for the variables a, b, and c. To do this, we will set a breakpoint in our program. A break point provides us with a way of stopping a program s execution at a selected statement. As shown in figure 13.9 the break point is set by moving the mouse pointer over the gray band to the left of the editor s text area and clicking on the gray band (called the gutter). When the break point is set, a round circle appears and the text on that line is highlighted. To remove the break point, click on the round circle. The circle and text highlighting will disappear. FIGURE 13.9: SETTING A BREAK POINT Once the break point is set start running the program be selecting Debug->Start Debugging. The program will now run until it reaches the line marked with the circle. There will now be a yellow arrow on top of the circle. The yellow arrow tells you that this is the line that will be executed next. This is illustrated in figure

31 FIGURE 13.10: THE YELLOW ARROW MARKS THE NEXT LINE TO BE EXECUTED To tell the computer to go ahead and execute that line, press F10 on your keyboard, or select Debug->Step Over. This causes the computer to execute the next instruction and stop. You can continue to press F10 to step through your program one line at a time. This makes it easy to follow the path of execution through your program. If at some point you want to see the value of a variable in your program, you can move the mouse cursor over the variables name and the value will pop up in small window as shown in Figure FIGURE 13.11: INSPECTING THE VALUE OF A VARIABLE

32 Chapter 13: Solving Problems that Require Decisions PROGRAMMING PROJECTS 1. Obe Wan Kenobi is in charge of reviewing the applications of this month s candidates for Jedi Knight School. Candidates must be at least 3 feet tall, but can be no higher than 8 feet. Tall. However, an exception has been made for Federation pilots, who can be of any height. Candidates under 3 feet tall can go to Jr. Jedi Knight School. Using the ideas taught in this chapter, design and write a program that does the following: It asks for a candidate s height, which is saves in an integer variable. It asks if the candidate is a federation pilot. The program than prints out one of the following messages, as appropriate: o This candidate is accepted into Jedi Knight School o This candidate is accepted into Jr. Jedi Knight School o This candidate is not accepted. 2. The Deep Pockets Savings Bank computes the monthly interest on an account based on the following table. Write a program that asks the user to enter in the type of account and the current balance. It will then calculate and display the interest to be paid on that account. SuperSaver Account StandardSaver Account 5% interest on the balance as long Always pays 3% interest on the balance as it is more than $5, If the balance is not greater than $5, the bank pays 3% interest on the balance

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 2 Flow of Control Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Boolean Expressions Building, Evaluating & Precedence Rules Branching Mechanisms if-else switch Nesting if-else

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2016 February 2, 2016 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 15 Branching : IF ELSE Statement We are looking

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

Decisions. Arizona State University 1

Decisions. Arizona State University 1 Decisions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 4 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer April 20, 2015 OOPP / C++ Lecture 3... 1/23 New Things in C++ Object vs. Pointer to Object Optional Parameters Enumerations Using an enum

More information

Conditional Programming

Conditional Programming COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control 1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

The four laws of programs

The four laws of programs Statements 1 2 The four laws of programs 3 These are like Isaac Asimov's 4 laws of robotics: 0: programs must work properly 1: programs must be readable, provided this does not conflict with the previous

More information

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.

More information

Chapter 6 Reacting to Player Input

Chapter 6 Reacting to Player Input Chapter 6 Reacting to Player Input 6.1 Introduction In this chapter, we will show you how your game program can react to mouse clicks and button presses. In order to do this, we need a instruction called

More information

5 The Control Structure Diagram (CSD)

5 The Control Structure Diagram (CSD) 5 The Control Structure Diagram (CSD) The Control Structure Diagram (CSD) is an algorithmic level diagram intended to improve the comprehensibility of source code by clearly depicting control constructs,

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

UEE1302(1102) F10: Introduction to Computers and Programming

UEE1302(1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU UEE1302(1102) F10: Introduction to Computers and Programming Programming Lecture 02 Flow of Control (I): Boolean Expression and Selection Learning Objectives

More information

Object Oriented Programming with Java

Object Oriented Programming with Java Object Oriented Programming with Java What is Object Oriented Programming? Object Oriented Programming consists of creating outline structures that are easily reused over and over again. There are four

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept. EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 4 Making

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

More information

Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops Chapter 4: Conditionals and Loops CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 4: Conditionals and Loops CS 121 1 / 69 Chapter 4 Topics Flow

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Decisions Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To be able to implement decisions using if statements To learn

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen Other conditional and loop constructs Fundamentals of Computer Science Keith Vertanen Overview Current loop constructs: for, while, do-while New loop constructs Get out of loop early: break Skip rest of

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi... Contents 1 Introduction 3 1.1 Java, the beginning.......................... 3 1.2 Java Virtual Machine........................ 4 1.3 A First Program........................... 4 1.4 BlueJ.................................

More information

QUIZ: What value is stored in a after this

QUIZ: What value is stored in a after this QUIZ: What value is stored in a after this statement is executed? Why? a = 23/7; QUIZ evaluates to 16. Lesson 4 Statements, Expressions, Operators Statement = complete instruction that directs the computer

More information

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax

More information

Conditional Statement

Conditional Statement Conditional Statement 1 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition Also called Branching How do we specify conditions?

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at http://handin.cs.clemson.edu.

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic. Coding Workshop Learning to Program with an Arduino Lecture Notes Table of Contents Programming ntroduction Values Assignment Arithmetic Control Tests f Blocks For Blocks Functions Arduino Main Functions

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

PIC 10A Flow control. Ernest Ryu UCLA Mathematics PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

Expressions and Casting

Expressions and Casting Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

More information

C++ Support Classes (Data and Variables)

C++ Support Classes (Data and Variables) C++ Support Classes (Data and Variables) School of Mathematics 2018 Today s lecture Topics: Computers and Programs; Syntax and Structure of a Program; Data and Variables; Aims: Understand the idea of programming

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=

More information

Logic & program control part 3: Compound selection structures

Logic & program control part 3: Compound selection structures Logic & program control part 3: Compound selection structures Multi-way selection Many algorithms involve several possible pathways to a solution A simple if/else structure provides two alternate paths;

More information

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference

More information

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni Dept. of Computer Science, UCSB Administrative This class is currently FULL and

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016 CS 31: Intro to Systems Binary Arithmetic Martin Gagné Swarthmore College January 24, 2016 Unsigned Integers Suppose we had one byte Can represent 2 8 (256) values If unsigned (strictly non-negative):

More information