Control Statements. If Statement if statement tests a particular condition

Size: px
Start display at page:

Download "Control Statements. If Statement if statement tests a particular condition"

Transcription

1 Control Statements Control Statements Define the way of flow in which the program statements should take place. Implement decisions and repetitions. There are four types of controls in C: Bi-directional control (if ) Multidirectional conditional control (switch) Loop controls for loop while loop do while loop Unconditional control (goto) If Statement Use, when there are two possibilities (alternatives) could happen. 1 Did the user enter a zero or not? Program should take different actions in the zero case and non-zero case. 2 = b 2 4ac of a quadratic equation is non-negative or negative. Program should give real-valued sol ns for non-negative values of and complex-valued sol ns for negative values of. The if comes in two forms: if if If Statement if statement tests a particular condition if the condition evaluates as true (or nonzero) an action or set of actions is executed Otherwise, the action(s) are ignored. Syntax of the if statement //Single Statement if ( test_expression ) statement; Note: The test_expression must be enclosed within parentheses. //Multiple Statements if ( test_expression ) { statement_1; statement_2;

2 Flow Chart if Test Exp n False True if If Statement if statement allows either-or condition by using an clause if the condition evaluates as true (or non-zero) action(s) in if clause is/are executed Otherwise, the action(s) in clause is/are executed Syntax of the if statement //Single Statement if (test_expression) statement_1; statement_2; //Multiple Statements if (test_expression) { { Flow Chart if Examples 1) //Single Statement if (x<0) printf( Error: Negative number ); Test Exp n True False 2) //Single Statement if (mark < 40) printf( Very Bad: You failed the examination ); printf( Congratulations: You passed the examination ); if 3) //Multiple Statements if (op = = e op = = E ) { printf( Bye: Use MyProg again ); exit(0);

3 4) //Multiple Statements if (delta >= 0) { Examples printf( Equation has real roots\n ); printf ( Root 1 = %f\n, -b + sqrt( delta ) / ( 2 * a )); printf ( Root 2 = %f\n, -b - sqrt( delta ) / ( 2 * a )); { // delta is negative printf( Equation has imaginary roots\n ); printf( Root 1 = ( %f, %f)\n, -b, sqrt( - delta ) / ( 2 * a )); printf( Root 2 = ( %f, %f)\n, -b, -sqrt( - delta ) / ( 2 * a )); More on if if statement can be nested within an another if. if ( op = = e op = = E ) { printf( Do you want to exit? (1 - Yes/0 N0) ); scanf( %d, doexit); //doexit is an int variable if ( doexit = = 1 ) { cout << Bye: Use MyProg again ; exit(0); Nested within an if statement Watch out the indentation in the inner if... statement. More on if Matching the clause More on if Matching the clause if ( a = = b ) //Correct Version if ( b = = c ) if ( a = = b ) { printf( a, b and c are the same ); if ( b = = c ) printf( a, b and c are the same ); printf( a and b are different ); If a = b = 3 and c = 2, what is the output? Output: a and b are different But a and b are same. Hmmm! Then, What s wrong with the code? The clause is matched with the inner if. How would we correct it? printf( a and b are different ); Now clause is matched with the outer if. Use braces { to match the clause correctly. Note: In cases like this, braces are compulsory even we have a single statement.

4 If Ladder Computer programs, like life, may present more than two selections. Can extend if to meet that need. //Compute student s grade //Revise format if ( mark >= 70 ) if ( mark >= 70 ) grade = A ; grade = A ; if ( mark >= 55 ) if ( mark >= 55 ) grade = B ; grade = B ; if ( mark >= 40 ) grade = C ; if ( mark >= 40 ) grade = C ; grade = F ; grade = F ; The Switch Statement Can use in C to select one of several alternatives. Screen menu that asks the user to select one of following four choices. 1: Add 2. Subtract 3: Multiply 4. Division 5. Exit Useful when the selection is based on a value of a single variable (controlling variable) a value of a simple expression (controlling expression). The Switch Statement General form: switch ( controlling variable/expression ) { case const_1: case const_2: case const_n default: break statement is not necessary after default statements The Switch Statement Switch statement works as follows: If the control variable/expression evaluated as const_1 statements under the case const_1 executed. const_2 statements under the case const_2 executed. const_n statements under the case const_n executed. other value statements under the default executed. break statement in each case causes exit from the switch statement.

5 Flow Chat - Switch Statement const_1 case const_1 const_2 case const_2 Control Variable const_n case const_n Other Value default The Switch Statement The value of this controlling variable or expression may be of type int or char or long But not double or float. The default statement is optional. If you omit it and there is no match, the program jumps to the next statement following the switch. What would happen if one of the break statements omit? When the program jumps to the particular case statement, it executes statements under it. Then it sequentially executes the following case statements until it reaches to a break statement. Switch and if Both the switch and if statements select a one from list of alternatives. if can handle ranges. But switch isn t designed to handle ranges. Each switch case label must be single valued. When switch statement? The case label value must be a constant. If all the alternatives can be identified with integer constants. Hmmm! We can use if with integer constants. Why then a switch statement? More efficient in terms of code size and execution speed. The Switch Statement Rule of thumb Use switch statement if you have three or more alternatives. 1 switch ( op ) { case 1: //Add result = num1 + num2; See the Indentation case 2: //Subtract result = num1 num2; case 3: //Multiply result = num1 * num2; case 4: // Division if ( num2!= 0 ) result = num1 / num2; case 5: // Exit exit(0); default: cout << Invalid key\n ;

6 The Switch Statement 2 switch (op) { case a : case A : result = num1 + num2; case s : case S : result = num1 num2; case m : case M : result = num1 * num2; case d : case D : if ( num2!= 0 ) result = num1 / num2; case e : case E : exit(0); default: cout << Invalid key\n ; Loops Many jobs that are required to be done with the help of a computer are repetitive in nature. Calculation of salary of different casual workers in a factory. The salary is calculated in the same manner for each worker (salary = no of hours worked * wage rate). Such type of repetitive calculations can easily be done using loops. C++ provides three kinds of loop controls for loop while loop do while loop For Loop Use to repeat a statement or a block of statements a specified number of times. Calculation of salary of 1000 workers. In advance, the programmer knows the loop must repeat 1000 times. The usual parts of a for loop handle these steps: Setting an initial value to loop control variable(s) Setting curworker (loop control variable) to 0. Performing a test to see if the loop should continue Testing curworker < 1000 Executing the loop actions Compute salary for the current worker Updating the loop control variable(s) Move to the next worker General form: For Loop //Single Statement for ( initialization; test_exp n ; update_exp n ) statement; //Multiple Statement for ( initialization; test_exp n ; update_exp n ) { statement_1; statement_2; statement_n;

7 Initialization For Loop Loop evaluates initialization just once (as soon as the loop is entered). Typically, programs use this expression to initialize the loop control variable ( curworker = 0;) This variable will also be used to count the loop cycles. Test expression If the test_exp n ( curworker < 1000) is true (or non-zero), the loop body will be executed. Otherwise the loop will be terminated. Update expression Initialization For Loop is evaluated at the end of the loop, after the body has been executed. Typically, it is used to increase or decrease the value of the loop control variable ( curworker++). for ( int curworker = 1; curworker < 1000; curworker++ ) salary[curworker] = hoursworked[curworker] * wagerate; Loop body Test expression Update expression Flow Chart For Loop Initialization Test Exp n True False for While Loop Use when we do not know the exact number of repetitions before the loop execution begins. 1 Withdraw money from your bank account as long as your bank balance is above Rs. 1000/-. General form: //Single Statement while ( test_expression ) statement; //Multiple Statements while ( test_expression ) { statement_1; statement_2; Update Exp n statement_n;

8 While Loop First a program evaluates the test_expression. If the test_expression evaluates to a non-zero value (true), the program executes the statement(s) in the body. After finishing with the body, the program returns to the test_expression and reevaluates it. If the test_expression is again non-zero, the program executes the body again. This cycle of testing and execution continues until the test_expression evaluates to 0 (false). Flow Chart While Loop Test Exp n False True while Note: While loop does not execute its body if the test_expression is initially 0 (false). While Loop Test expression while ( balance > 1000 ) { cout << Input your withdraw amount: ; cin >> withdrawamt; if ( balance withdrawamt <= 1000 ) cout << Sorry: Balance is not sufficient\n ; balance = balance withdrawamt; Loop body Do While Loop The While loop evaluates its test_expression at the beginning of the loop. Loop will not never execute if the test_expression is zero (false). But there are situations where you need to execute the body at least once. In such situations, you should use a do while. Do while loop executes its body first. Next, it evaluates the test_expression. If the test_expression is non-zero (true) executes the body again. This cycle of testing and execution continues until the test_expression evaluates to 0 (false).

9 Do while Loop (cont.) General form: do { //Single Statement do statement; while ( test_expression ); //Multiple Statements do { statement_1; statement_2; statement_n; while ( test_expression ) ; cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> den; cout << Quotient is << num / den << \n ; cout << Remainder is << num % den << \n ; cout << Do another? (y/n): ; cin >> doagain; while (ch!= n ); Flow Chart Do While Loop do while Test Exp n False True Break Statement Exits out of the current loop and transfers to the statement immediately following the loop. while ( i > 0 ) { cout << Count = << i++ << \n ; if ( i = = 5 ) // breaks out the loop when i = 5 cout << of program ; Output Count = 0 Count = 1 Count = 2 Count = 3 Count = 4 of program Continue Statement The break statement takes you out of the bottom of a loop. Sometimes you need to go back to top of the loop, when something happens unexpectedly. do { cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> den; cout << Quotient is << num / den << \n ; cout << Remainder is << num % den << \n ; cout << Do another? (y/n): ; cin >> doagain; while (ch!= n ); What is the output if the user keyed a zero (0) as den? Occurs an runtime error as num / den is not defined.

10 Continue Statement Use a continue statement to move to the top of the loop when the user inputs zero as den. do { cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> den; if ( den = = 0 ) { cout << Illegal denomenator\n ; continue; cout << Quotient is << num / den << \n ; cout << Remainder is << num % den << \n ; cout << Do another? (y/n): ; cin >> doagain; while (ch!= n );

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

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

COMP 208 Computers in Engineering

COMP 208 Computers in Engineering COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,

More information

MODULE 2: Branching and Looping

MODULE 2: Branching and Looping MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

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

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

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

More information

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake Assigning Values // Example 2.3(Mathematical operations in C++) float a; cout > a; cout

More information

Add Subtract Multiply Divide

Add Subtract Multiply Divide ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient

More information

CHAPTER : 9 FLOW OF CONTROL

CHAPTER : 9 FLOW OF CONTROL CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language

More information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

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

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

n Group of statements that are executed repeatedly while some condition remains true

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

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

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

LECTURE 04 MAKING DECISIONS

LECTURE 04 MAKING DECISIONS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 04 MAKING DECISIONS

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 08: Control Statements Readings: Chapter 6 Control Statements and Their Types A control

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

Chapter 3 Selection Statements

Chapter 3 Selection Statements Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are

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

Review. Relational Operators. The if Statement. CS 151 Review #4

Review. Relational Operators. The if Statement. CS 151 Review #4 Review Relational Operators You have already seen that the statement total=5 is an assignment statement; that is, the integer 5 is placed in the variable called total. Nothing relevant to our everyday

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

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true; Programming in C++ If Statements If the sun is shining Choice Statements if (the sun is shining) go to the beach; True Beach False Class go to class; End If 2 1 Boolean Data Type (false, ) i.e. bool bflag;

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

More information

Other Loop Options EXAMPLE

Other Loop Options EXAMPLE C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you

More information

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement

More information

Outline. Review Choice Statements. Review Sequential Flow. Review Choice Before Loops. Review Choice After Loops

Outline. Review Choice Statements. Review Sequential Flow. Review Choice Before Loops. Review Choice After Loops Programming with If Statements using Multiple Conditions Larry Caretto Computer Science 106 Computing in Engineering and Science February 23, 2006 Outline Review last class Program flow controls if s Exercises

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018. Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming Decisions with Variables CS1100 Introduction to Programming Selection Statements Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB,

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

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

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); } C Program Output #include main () { printf ( Hi everyone\n ); Hi everyone #include main () { printf ( Hi everyone\n ); #include and main are Keywords (or Reserved Words) Reserved Words

More information

BRANCHING if-else statements

BRANCHING if-else statements BRANCHING if-else statements Conditional Statements A conditional statement lets us choose which statement t t will be executed next Therefore they are sometimes called selection statements Conditional

More information

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING MULTIPLE SELECTION To solve a problem that has several selection, use either of the following method: Multiple selection nested

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

Selection Statements. Pseudocode

Selection Statements. Pseudocode Selection Statements Pseudocode Natural language mixed with programming code Ex: if the radius is negative the program display a message indicating wrong input; the program compute the area and display

More information

conditional statements

conditional statements L E S S O N S E T 4 Conditional Statements PU RPOSE PROCE DU RE 1. To work with relational operators 2. To work with conditional statements 3. To learn and use nested if statements 4. To learn and use

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter p 1 Introduction to Computers, p, Programs, g, and Java Chapter 2 Primitive Data Types and Operations Chapter

More information

Repetition and Loop Statements Chapter 5

Repetition and Loop Statements Chapter 5 Repetition and Loop Statements Chapter 5 1 Chapter Objectives To understand why repetition is an important control structure in programming To learn about loop control variables and the three steps needed

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Relational Operators EXAMPLE. C++ By

Relational Operators EXAMPLE. C++ By C++ By 9 EXAMPLE Relational Operators Sometimes you won t want every statement in your C++ program to execute every time the program runs. So far, every program in this book has executed from the top and

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

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation: Control Structures Sequence Statements execute in sequence, one after the other, such as the following solution for a quadratic equation: double desc, x1, x2; desc = b * b 4 * a * c; desc = sqrt(desc);

More information

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

More information

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each. I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK 70. a) What is the difference between Hardware and Software? Give one example for each. b) Give two differences between primary and secondary memory.

More information

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++ Comp Sci 1570 Introduction to C++ Outline 1 Outline 1 Outline 1 switch ( e x p r e s s i o n ) { case c o n s t a n t 1 : group of statements 1; break ; case c o n s t a n t 2 : group of statements 2;

More information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

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

Lecture 10. Daily Puzzle

Lecture 10. Daily Puzzle Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch. Daily

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection) Control Structures A computer can proceed: In sequence Selectively (branch) - making

More information

Chapter 4: Control Structures I (Selection)

Chapter 4: Control Structures I (Selection) Chapter 4: Control Structures I (Selection) 1 Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover

More information

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions. 1. C++ Overview 1. C++ Overview C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions. Interactive Mode, Batch Mode and Data Files. Common Programming

More information

Lecture 6. Statements

Lecture 6. Statements Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

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

Lab ACN : C++ Programming Exercises

Lab ACN : C++ Programming Exercises Lab ACN : C++ Programming Exercises ------------------------------------------------------------------------------------------------------------------- Exercise 1 Write a temperature conversion program

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

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

CHAPTER 4 CONTROL STRUCTURES

CHAPTER 4 CONTROL STRUCTURES CHAPTER 4 CONTROL STRUCTURES 1 Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may deviate, repeat code or take decisions. For that purpose,

More information

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14 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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

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

Computer Programming. Decision Making (2) Loops

Computer Programming. Decision Making (2) Loops Computer Programming Decision Making (2) Loops Topics The Conditional Execution of C Statements (review) Making a Decision (review) If Statement (review) Switch-case Repeating Statements while loop Examples

More information

Chapter 2, Part III Arithmetic Operators and Decision Making

Chapter 2, Part III Arithmetic Operators and Decision Making Chapter 2, Part III Arithmetic Operators and Decision Making C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

Chapter 8 Statement-Level Control Structure

Chapter 8 Statement-Level Control Structure Chapter 8 Statement-Level Control Structure To make programs more flexible and powerful: Some means of selecting among alternative control flow paths. Selection statement (conditional statements) Unconditional

More information

Problem Solving and 'C' Programming

Problem Solving and 'C' Programming Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein

More information

Chapter 7 Arithmetic

Chapter 7 Arithmetic Chapter 7 Arithmetic 7-1 Arithmetic in C++ Arithmetic expressions are made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition) - (subtraction)

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control

More information

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Chapter 6 : (Control Structure- Repetition) Using Decrement or Increment While Loop Do-While Loop FOR Loop Nested Loop

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Objectives By the end of this section you should be able to:

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

LAB 4.1 Relational Operators and the if Statement

LAB 4.1 Relational Operators and the if Statement LAB 4.1 Relational Operators and the if Statement // This program tests whether or not an initialized value of num2 // is equal to a value of num1 input by the user. int main( ) int num1, // num1 is not

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

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

Lecture 8. Daily Puzzle

Lecture 8. Daily Puzzle Lecture 8 if and switch Statements Daily Puzzle If a bottle, partly filled with liquid, has a round, square or rectangular bottom which is flat, can you find its volume using only a ruler? You may not

More information

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement Module3 Program Control Statements CRITICAL SKILLS 3.1 Know the complete form of the if statement 3.2 Use the switch statement 3.3 Know the complete form of the for loop 3.4 Use the while loop 3.5 Use

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Chapter 4. Flow of Control

Chapter 4. Flow of Control Chapter 4. Flow of Control Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr Sequential flow of control

More information

Dept. of CSE, IIT KGP

Dept. of CSE, IIT KGP Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

Chapter 6. Section 6.4 Altering the Flow of Control. CS 50 Hathairat Rattanasook

Chapter 6. Section 6.4 Altering the Flow of Control. CS 50 Hathairat Rattanasook Chapter 6 Section 6.4 Altering the Flow of Control CS 50 Hathairat Rattanasook continue; The continue statement will skip the current iteration of a loop and jump to the next iteration. // continue in

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Score score < score < score < 65 Score < 50

Score score < score < score < 65 Score < 50 What if we need to write a code segment to assign letter grades based on exam scores according to the following rules. Write this using if-only. How to use if-else correctly in this example? score Score

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

Theory of control structures

Theory of control structures Theory of control structures Paper written by Bohm and Jacopini in 1966 proposed that all programs can be written using 3 types of control structures. Theory of control structures sequential structures

More information