Presentation is loading. Please wait.

Presentation is loading. Please wait.

CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.

Similar presentations


Presentation on theme: "CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control."— Presentation transcript:

1

2 CC213 Programming Applications Week #2

3 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control structures:  Sequential Flow - this is written as a group of statements bracketed by { and }where one statement follows another.  Selection control structure - this chooses between multiple statements to execute based on some condition.  Repetition – this structure executes a block of code multiple times. C Y N C Y N

4 3 C control structures Selection if if... else switch Repetition for loop whileloop do... whileloop

5 4 Conditions A program chooses among alternative statements by testing the values of variables.  0 means false  Any non-zero integer means true, Usually, we’ll use 1 as true. if (a>=b) printf(“a is larger”); else printf(“b is larger”); Condition - an expression that establishes a criterion for either executing or skipping a group of statements  a>=b is a condition that determines which printf statement we execute.

6 5 Relational and Equality Operators Most conditions that we use to perform comparisons will have one of these forms:  variable relational-operator variable e.g. a < b  variable relational-operator constant e.g. a > 3  variable equality-operator variable e.g. a = = b  variable equality-operator constant e.g. a != 10

7 6 Relational and Equality Operators OperatorMeaningType <less thanrelational >greater thanrelational <=less than or equal torelational >=greater than or equal torelational == equal toequality !=not equal toequality

8 7 Logical Operators logical expressions - expressions that use conditional statements and logical operators.  && (and) A && B is true if and only if both A and B are true  || (or) A || B is true if either A or B are true  ! (not) !(condition) is true if condition is false, and false if condition is true This is called the logical complement or negation Example  (salary 5)  (temperature > 30.0) && (humidity > 90)  !(temperature > 90.0)

9 8 Truth Table && Operator ABA && B False (zero) True (non-zero)False (zero) True (non-zero)False (zero) True (non-zero)

10 9 Truth Table || Operator ABA || B False (zero) True (non-zero) False (zero)True (non-zero)

11 10 Operator Table ! Operator A!A False (zero)True (non-zero) False (zero)

12 11 Remember! && operator yields a true result only when both its operands are true. || operator yields a false result only when both its operands are false.

13 12 if ( Expression ) StatementA else StatementB NOTE: StatementA and StatementB each can be a single statement, a null statement, or a block. If-Else Syntax

14 13 Example: mail order Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost:  The discount rate is 25% and the shipping is 10.00 if purchase is over 100.00.  Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

15 14 Note: These braces cannot be omitted if ( purchase > 100.00 ) { discountRate =.25 ; discountRate =.25 ; shipCost = 10.00 ; shipCost = 10.00 ;}else{ discountRate =.15 ; discountRate =.15 ; shipCost = 5.00 ; shipCost = 5.00 ;} totalBill = purchase * (1.0 - discountRate) + shipCost ;

16 15 Switch statement l Used to select one of several alternatives l BASED on the value of a single variable. l This variable may be an int or a char but NOT a float ( or double).

17 16 Example char grade ; printf(“Enter your letter grade: “); scanf(“%c”, &grade); switch ( grade ) { case ‘A’ : printf(“ Excellent Job”); case ‘A’ : printf(“ Excellent Job”); break; break; case ‘B’ : printf ( “ Very Good “); case ‘B’ : printf ( “ Very Good “); break; break; case ‘C’ : printf(“ Not bad “); case ‘C’ : printf(“ Not bad “); break; break; case ‘F’ : printf(“Failing”); case ‘F’ : printf(“Failing”); break; break; default : printf(“ Wrong Input “); default : printf(“ Wrong Input “);}

18 17 Example: Light bulbs Write a program to ask the user for the brightness of a light bulb (in Watts), and print out the expected lifetime: BrightnessLifetime in hours 252500 40, 601000 75, 100750 otherwise0

19 18 int bright ; printf( “ Enter the bulb brightness: “ ); scanf( “ %d ”, &bright); switch ( bright ) { case 25 : printf( “ Expected Lifetime is 2500 hours ” ); case 25 : printf( “ Expected Lifetime is 2500 hours ” ); break; break; case 40 : case 40 : case 60 : printf ( “ Expected Lifetime is 1000 hours “ ); case 60 : printf ( “ Expected Lifetime is 1000 hours “ ); break; break; case 75 : case 75 : case 100 : printf( “ Expected Lifetime is 750 hours “ ); case 100 : printf( “ Expected Lifetime is 750 hours “ ); break; break; default : printf( “ Wrong Input “ ); default : printf( “ Wrong Input “ );} int bright ; printf( “ Enter the bulb brightness: “ ); scanf( “ %d ”, &bright); switch ( bright ) { case 25 : printf( “ Expected Lifetime is 2500 hours ” ); case 25 : printf( “ Expected Lifetime is 2500 hours ” ); break; break; case 40 : case 40 : case 60 : printf ( “ Expected Lifetime is 1000 hours “ ); case 60 : printf ( “ Expected Lifetime is 1000 hours “ ); break; break; case 75 : case 75 : case 100 : printf( “ Expected Lifetime is 750 hours “ ); case 100 : printf( “ Expected Lifetime is 750 hours “ ); break; break; default : printf( “ Wrong Input “ ); default : printf( “ Wrong Input “ );}

20 19 A loop is to execute a set of instructions repeatedly until a particular condition is being satisfied. That is, you can execute particular statements more than once in a controlled fashion Statements are executed as long as some condition remains true What is a loop?

21 20 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop body changes and this causes the repetetion to stop

22 21 While Statement SYNTAX while ( Expression ) {.. /*loop body */. } NOTE: Loop body can be a single statement, a null statement, or a block.

23 22 Every while loop will always contain three main elements: – Priming: initialize your variables. – Testing: test against some known condition. – Updating: update the variable that is tested. Parts of a While Loop

24 23 int count ; count = 4; /* initialize loop variable */ while (count > 0) /* test expression */ { printf( “ %d \n ”,count ) ; /* repeated action */ count -- ; /*update loop variable */ } printf( “ Done ” ) ; Count-controlled Loop 1. Priming 2. Test Condition 3. Update

25 24 Computing Sum If we want to compute, we need to go 1+2+3+...+100 #include int main(void) { int sum =0, i = 1; while (i <= 100) { sum = sum + i; i = i + 1; } printf("Sum is %d\n", sum); return 0;}

26 25 A loop that never ends. Generally, you want to avoid these! There are special cases, however, when you do want to create infinite loops on purpose. Infinite loop

27 26 #include #define MAX 10 main () { int index =1; while (index <= MAX) { printf ("Index: %d\n", index); } Infinite While Loop 1. Priming 2. Test Condition 3. Where is the update part Index: 1 … [forever]

28 27 #include /* no MAX here */ main () { int index =1; while (index > 0) { printf ("Index: %d\n", index); index = index + 1; } Infinite While Loop 1. Priming 2. Test Condition 3. Update Index: 1 Index: 2 Index: 3 Index: 4 Index: 5 … [forever]

29 28 Event controlled loop Signals the end of data entry Also known as signal value, dummy value, or flag value Also known as indefinite repetition because the number of repetitions the code will perform is unknown before the loop

30 29 Event controlled loop Flag-controlled Loops How are they used? – Programmer picks a value that would never be encountered for normal data – User enters normal data and then when done, enters the unusual value – The loop would stop when seeing the unusual value

31 30 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statements } while ( Expression ) ; Loop body statement can be a single statement or a block.

32 31 Computing Sum If we want to compute, we need to go 1+2+3+...+100 /* computes the sum: 1 + 2 + 3 +....+ 100 */ #include int main(void) { ….. …… printf("Sum is %d\n", sum); return 0; }

33 32 Do-While Loop vs. While Loop POST-TEST loop (exit- condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entry- condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all.

34 33 Basic For Loop Syntax For loops are good for creating definite loops. int counter; for (counter =1;counter <= 10;counter++) printf ("%d\n", counter); 1. Priming: Set the start value. 2. Test Condition: Set the stop value. 3. Update: Update the value. Note that each section is separated by a semicolon.

35 34 Computing Sum If we want to compute, we need to go 1+2+3+...+100 /* computes the sum: 1 + 2 + 3 +....+ 100 */ #include int main(void) { …….. ……….. printf("Sum is %d\n", sum); return 0;}

36 35 What is an Array?  It ’ s a collection of variables (the same type) grouped into one name. More specifically, it ’ s a group of memory locations for variables of the same type and specified by the same name. It makes dealing with related variables much easier.

37 36 Arrays An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

38 37 The Scores Array

39 38 Declaring and Defining Arrays

40 39 Only fixed-length arrays can be initialized when they are defined. Variable length arrays must be initialized by inputting or assigning the values. Note

41 40 Initializing Arrays

42 41 One array cannot be copied to another using assignment. Note

43 Write a program to get the average of 10 integers in an array.


Download ppt "CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control."

Similar presentations


Ads by Google