CSCI 101 Fundamentals of Computer Programming Lab 6 Conditional Relational Operators Fall 2005 Introduction As of now the current programs written all have a common attribute which is that every line of command will be executed linearly This is a passive programming practice with severe limitations To increase a program s flexibility we will use conditional operators These operators provide options to the program and may produce different outputs when given different inputs So far we have learnt one basic structures which provides these options the if else statements It directs the program to choose one of the many options of tasks to perform depending on the condition it was subjected to These conditions are usually expressed using relational operators and logical operators The relational operators usually take in either one or two inputs and output an integer value The output value will indicate the state of the relationship 0 to indicate FALSE and anything else to indicate TRUE The compiler will return a 1 to indicate TRUE For example given the statement x 3 5 the compiler will assign 1 to the value of x if else statements have the following format if condition 1 task 1 else task 2 When the compiler reaches the line where it evaluates condition 1 if it is true it will perform task 1 and ignore task 2 If it is false it will perform task 2 and ignore task 1 The curly braces indicate the section of code which is under the if and else statements This is a particularly important observation as it is among the most common mistakes among programmers Example An example of if else statements is below It can be downloaded at scf usc edu csci101 labs lab6condition c include stdio h int main int num1 num2 printf Please enter two numbers scanf d d num1 num2 printf Using method 1 n Method 1 if num1 2 0 num2 2 0 printf Both d and d are even numbers n num1 num2 else if num1 2 0 printf d is an even number n num1 else if num2 2 0 printf d is an even number n num2 else printf Both d and d aren t even numbers n num1 num2 printf nUsing method 2 n Method 2 if num1 2 0 num2 2 0 printf Both d and d are even numbers n num1 num2 else if num1 2 0 printf d is an even number n num1 else if num2 2 0 printf d is an even number n num2 else printf Both d and d aren t even numbers n num1 num2 return 0 It will prompt the user to enter two numbers and evaluates them if they are even numbers Note that there are two methods above which are identical in execution Exercise Write a program using the if else statement that does the following a Prompt the user to enter three integer numbers b Prompt the user to enter whether he she wants the numbers sorted in ascending or descending order c Sort the numbers in the order prompted and print them out on the screen Show your completed program to your LA TA to receive lab credit
View Full Document