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

Slides:



Advertisements
Similar presentations
Decisions If statements in C.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
Loops – While, Do, For Repetition Statements Introduction to Arrays
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
1 ICS103 Programming in C Lecture 6: Selection Structures.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 5: Structured Programming
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Chapter 4: Control Structures II
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Lecture 4: C/C++ Control Structures Computer Programming Control Structures Lecture No. 4.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
COMP Loop Statements Yi Hong May 21, 2015.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Control Statements: Part1  if, if…else, switch 1.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 4 – C Program Control
The if…else Selection Statement
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
- Standard C Statements
Week 4 – Repetition Structures / Loops
Ch 7: JavaScript Control Statements I.
Arrays, For loop While loop Do while loop
CS1100 Computational Engineering
Structured Program
3 Control Statements:.
Chapter 4 - Program Control
The while Looping Structure
Presentation transcript:

CC213 Programming Applications Week #2

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

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

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.

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

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

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)

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

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

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

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.

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

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 if purchase is over  Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

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

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).

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 “);}

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 , , otherwise0

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 “ );}

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?

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

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

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

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

24 Computing Sum If we want to compute, we need to go #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;}

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

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]

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]

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

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

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.

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

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.

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.

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

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.

36 Arrays An array is an ordered list of values 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

37 The Scores Array

38 Declaring and Defining Arrays

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

40 Initializing Arrays

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

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