fundamentals of programming procedural...

21
Procedural Programming/Lab2 1 Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Session Two: Boolean expressions, Conditional Executions: Chains and Nested Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Name: Matriculation-Number: First Name: Group-Number: Tutor: Date: Fundamentals of Programming & Procedural Programming

Upload: buingoc

Post on 31-Aug-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     1 

Universität Duisburg-Essen  

 

 

PRACTICAL TRAINING TO THE LECTURE 

 

 

 

 

Session Two: Boolean expressions, Conditional Executions:

Chains and Nested

 

 

 

 

 

 

 

 

 

 Prof. Dr.Ing. Axel Hunger

Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen

Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering

Name: Matriculation-Number:

First Name: Group-Number:

Tutor: Date:

Fundamentals of Programming & Procedural Programming 

Page 2: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     2 

Decision Making Calculations and expressions are merely a small fraction of computer programming.  Till now, we concentrated on the linear programming, in which programs were being executed in a straight line, statement after statement, or as it is called officially as “sequential”. But as programs become more and more complex, they need to be equipped with decision making (selection) in order to specify which statements are to be executed in which order.  

In this session, we will focus on the control flow of a program with the help of branching statements. Branching statements allow a particular section of the code to be executed or not, depending on the given conditional clauses.  

 

RelationalOperatorsPrograms compare values by using relational operators. In C, supported relational operators are:  

Operator  Meaning >  Greater than <  Less than >=  Greater than or equal to <=  Less than or equal to ==  Equal to !=  Not equal to 

 A relational expression consists of operands and a relational operator between them. The result of a relational expression is a Boolean value, represented as either true or false. 

Note: The bool data type did not exist in C before C 99 came up. Since then we have the bool type. Before it was 1 seen as true and false seen as a 0. If you want to use the data type bool then you have to include the header file stdbool.h with the statement: “#include <stdbool.h”. 

Example:           Expression        Value            8 == 8           true           8 != 8           false           8 < 8           false           8 > 8           false                    8 <= 8           true 

 The above expressions use operands having literal values, but operands can also be variables, like shown in the following example.     

Page 3: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     3 

Example:  /* example: using relational operators */ #include <stdio.h> int main() { int x = 8, y = 9; printf("%d < %d is %d", x, y, x < y); printf("\n%d > %d is %d", x, y, x > y); printf("\n%d >= %d is %d", x, y, x >= y); printf("\n%d <= %d is %d", x, y, x <= y); printf("\n%d == %d is %d", x, y, x == y); return 0; }

 Exercise 2.1: Please trace the result of each of the output statements in the above program and write down the results below. Note:  In Boolean expressions, 0 (zero) is the integer value of false, while 1 (one) is the integer value of true             Exercise 2.2:  Write a program which calculates whether the following expressions are true or false and will print accordingly: 3  >  4;      ‘x’  <  ‘y’;       6 = = 7;   

 

 

Page 4: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     4 

LogicalOperatorsLogical operators in C enable you to combine comparisons in one if statement or else‐if statement.  

The && Operator Also known as the And Operator, the && Operator connects two relational expressions. Both of the expressions should be true for the overall expression to return a true. For example:   

 if (age >= 13 && gender == 1) femaleTeenager = femaleTeenager + 1;

In the above example, the combined condition becomes true only and if only both conditions are true and the combined condition is false if either or both of the conditions are false.  

Expression 1  Expression 2  Expression 1 && Expression 2 

False  False  False 

False  True  False 

True  False  False 

True  True  True 

Truth table for the && operator 

The || Operator Also known as the Or Operator, the || Operator connects two relational expressions. If either value of the expressions is true, the overall expression returns a true. For example:   

 if (termAverage >= 80 || finalAverage >= 80) printf("Grade is A");

  In the above example, the combined condition becomes true if either or both of the conditions are true and the combined condition is false only if both of the conditions are false.  

Expression 1  Expression 2  Expression 1 || Expression 2 

False  False  False 

False  True  True 

True  False  True 

True  True  True 

          Truth table for the || operator 

The ! Operator Also known as the Not Operator, the ! Operator reverses the value of an expression, making the value of a true expression false and the value of a false expression true. 

Page 5: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     5 

Example:   /* using the not operator */ #include <stdio.h> int main() { int marks; printf("Please enter your marks:"); scanf("%d",&marks); if ( ! (marks <= 30) ) printf("You have passed the exam!"); else printf("Sorry, You failed the exam!"); return 0; }

  

Expression  ! Expression 

False  True 

True  False 

Truth table for the ! operator  

Exercise 2.3:  Determine whether the following expressions return a value true or false: Considering the given declarations:  int cutoff=0, count=5, I=0, j=1; a.  (cutoff ==0) && (count <=5) 

 

b.  (cutoff ==0) && (count< 10) 

 

c.  (count <20) || (cutoff >5) 

 

d.  (  !(  ( (cutoff < 100) || (i <j) )  && (count <=10) )  ) 

 

e.  ((cutoff < 20) || (j< i)) 

 

 

Page 6: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     6 

TheifStatementThe if statement executes the subsequent code (either one statement or a block of statements embraced witch {}) when the value of a relational expression is true. The relational expression should be contained within parentheses, and should not be terminated with a semicolon.  Syntax:  if (relational expression) statement;//executed if the relation expression is true

if (relational expression) { // the statements in this block are executed // if the relational expression is true statement1; statement2; }

The statement respectively the block of statements are only executed if the value of the relational expression is true, otherwise it’s skipped.  

Example: 

/* example: using the if statement */ #include <stdio.h> int main() { int num; printf("Enter an integer number:"); scanf("%d",&num); if (num > 0) printf("Your given number is positive"); return 0; }

Page 7: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     7 

Exercise 2.4: Draw a flowchart for the above example program.                                       

 

Page 8: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     8 

Theif‐elseStatementConsidering the previous example, what if we want to have an output if the entered number is ‘odd’ instead of ‘even’.  There’s no consequent statement if the condition is false. For this purpose, we can use the if/else statement. 

Syntax: 

if (relational expression)

statement;

else

statement;

 

Example:  /* example: using the if-else statement */ #include <stdio.h> int main() { int num; printf("Please enter an integer number:"); scanf("%d",&num); if (num > 0) { printf("Your given number is a positive number"); } else { printf("Your given number is a negative number or zero"); } return 0; }

 

Page 9: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     9 

The following figure shows the flowchart for the above program:                                           

   Display the number is negative 

True

False

    Prompt user to input number 

(num) 

num > 0

   Input num 

   Display the number is positive 

End 

Start

Page 10: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     10 

 Exercise 2.5: Write a program which prompts the user to enter two numbers of type double. The program then should decide which number is smaller of the two, and then displays an appropriate message.                                

 

  

 

 

Page 11: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     11 

Exercise 2.6: Write a program which asks the user to enter a number of type integer, decides whether the integer number is an even or an odd number, and then displays an appropriate message. 

 

   

 

 

 

 

 

 

 

 

 

Exercise 2.7: Find the final value of the variable result in the following code: 

float x = 52.5, y = 37.6; int result = 0; if ( (x > 40.0) && (y <= 40.0) ) result = result + 1; else result = result - 1;

Page 12: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     12 

The Conditional Operator  There is another short way to express a form of if‐else statement. C uses a special type of operator called the conditional operator ?: to do this in a conditional expression. 

This conditional operator takes three operands, each as an expression. 

Syntax: 

expression1 ? expression2 : expression3

If expression1 is true, the value of the whole expression equals the value of expression2. Else, it will equals the value of expression3. 

For example: 

(8 > 4) ? 1 : 2 has a value of 1. 

(2 > 6) ? 1 : 2 has the value 2. 

(i > j) ? i : j has the value of the larger of i or j.  

Theif‐else‐if‐elseStatementScenarios where there are more than two options, you need another expression for each additional alternative. That expression is known as the ‘else if’ statement.  Syntax: 

if (relational expression) statement; else if statement; else statement;

 Example:  /* example: using the if-else-if-else statement */ #include <stdio.h> int main() { int a, b, c; printf("Enter the first num: "); scanf("%d",&a); printf("Enter the second num: "); scanf("%d",&b); printf("Enter the third num: "); scanf("%d",&c);

Page 13: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     13 

if (a > b && a > c) { printf("%d \t is greater\n", a); } else { printf("%d \t is smaller\n", a); } if(b > a && b > c) { printf("%d \t is greater\n", b); } else { printf("%d \t is smaller\n", b); } if(c > a && c > b) { printf("%d \t is greater\n", c); } else { printf("%d \t is smaller\n", c); } return 0; }

 Exercise 2.8: Please trace the result of each of the output statements in the above program and write down the results below.                   

Page 14: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     14 

Exercise 2.9: The following flowchart is an example of the if‐else‐if‐else statement. Translate the flowchart into C code:                                              

Start 

End 

num > 0  True 

False 

num < 0  True 

False 

    Prompt user to input number 

    input number 

 

   Display the number is positive

   Display the number is negative

    Display the number is a zero 

 

Page 15: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     15 

Place here the C‐Code for Exercise 2.9!                     

NestedifStatementsA nested if statement is an if statement which appears inside another if statement. They are used to resolve if either one of them of the expressions is true or whether both of the relational expressions hold true. 

Example: /* example: using the nested if-else statement */ #include <stdio.h> int main() { int num; printf("Please enter a positive integer number: "); scanf("%d",&num); if (num > 0) { if (num%2 ==0) printf("The entered number is positive and even"); else printf("The entered number is positive and odd"); } else printf("The entered number is negative. Please try again."); return 0; }

Page 16: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     16 

Exercise 2.10: Rewrite the above code without using the nested if‐else statement. Modify it so that it shows whether an entered number is negative, and whether it is even or odd in all cases. 

                                      

Page 17: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     17 

MistakestobeAvoided• An ‘else’ keyword always comes with the ‘if’ keyword. You can’t use an ‘else’ without the ‘if’ 

keyword. 

• A Relational Expression is not supposed to be used after the ‘else’ keyword. 

• A Semicolon is not used after the ‘else’ keyword 

 Exercise 2.11: Find and correct the errors in the following program segments:  a)  if (code == 'y') tax = pay * 0.07; else; tax = pay * 0.045; }

         b)  if (percentage >= 75); printf("Percentage is greater than or equal to 75"); else printf("Percentage is less than 75");

           

 

 

Page 18: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     18 

Exercise 2.12: State whether the following nested‐if‐else statement is correct or not. If not, then rewrite it using proper indentation.  

if (a > b) if (j == k) {x = y; t = s;} else u = t; else if (f > e) h=h+1;

           

Exercise 2.13: Translate the following pseudocode into a valid C program: 

Set count to 1 If (balance >= 0) begin Set current_balance to balance Display balance end Else Set count to 0 End if

 

 

Page 19: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     19 

TheSwitchStatementThe switch statement allows a particular set of statements to be selected from several available choices. The selection is done based upon the current value of an expression, which is included within the switch statement. 

 Syntax: 

The general form of a switch statement is  

Switch (expression) statement

where expression results in an integer value.  

Note that expression can also be of type char, since individual characters have equivalent integer values. 

The switch statement body is made up of a set of cases. Each case is identified with a case label. A case label starts with a case keyword, then a case value, followed with a colon. The case labels identify the different group of the statement (i.e. the different alternatives) and distinguish them from one another. 

The case label is followed by the body for that case. If the expression equals the case value that is in the case label, the program then executes the statements in the statement body.  

 

Example: /* example: using the switch statement */ #include <stdio.h> int main() { int a, b; int choice; printf("Please enter first number: "); scanf("%d",&a); printf("Please enter second number: "); scanf("%d",&b); printf("Please enter your choice: "); printf("\n1 - Addition: "); printf("\n2 - Multiplication: "); printf("\n3 - Subtraction: "); printf("\n4 - Division: "); scanf("%d", &choice);

Page 20: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     20 

switch(choice) { case (1): printf("The sum is of the two numbers %d", a + b); break; case (2): printf("The multiplication of the two numbers is %d", a * b); break; case (3): printf("The subtraction of the two numbers is %d", a - b); break; case (4): printf("The division is of the two numbers %d", a / b); break; default: printf("Incorrect choice! Please try again."); return 0; }

  Note that each of the groups is end with the break statement. The break statement causes control to be transferred out of the switch statement, thus preventing more than one group of statement from being executed.  One of the  labeled groups of the statement within the switch statement may be  labeled default. This is executed if none of the case labels match the value of the expression. The default case label is optional and doesn’t need to be included at the end of the body of the switch statement. 

Page 21: Fundamentals of Programming Procedural Programmingti.uni-due.de/ti/en/education/teaching/ss18/foppp/lab/Session2... · Procedural Programming/Lab2 2 Decision Making Calculations and

 

   

Procedural Programming/Lab2     21 

Exercise 2.14: What output would the following piece of code give? 

int const choice = 1; switch(choice + 1) { case '1': printf("Tea\n"); break; case '2': printf("Coffee\n"); break; case '3': printf("Milkshake\n"); break; default: printf("Bon appétit!\n"); return 0; }

            

Note:  

bon appétit, originated in French, basically means good appetite or enjoy your meal.