Control Statements. If Statement if statement tests a particular condition

Similar documents
Decision Making -Branching. Class Incharge: S. Sasirekha

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

COMP 208 Computers in Engineering

MODULE 2: Branching and Looping

Computers Programming Course 7. Iulian Năstac

REPETITION CONTROL STRUCTURE LOGO

Flow Control. CSC215 Lecture

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

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

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

Add Subtract Multiply Divide

CHAPTER : 9 FLOW OF CONTROL

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4: Making Decisions

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

Conditional Statement

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

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

Lecture 3 Tao Wang 1

Chapter 3 Selection Statements

Chapter 4 - Notes Control Structures I (Selection)

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

Introduction to Programming

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;

Chapter 5: Control Structures

Other Loop Options EXAMPLE

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

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

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

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

Introduction. C provides two styles of flow control:

CS1100 Introduction to Programming

Loops / Repetition Statements

Chapter 2 - Introduction to C Programming

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

LECTURE 5 Control Structures Part 2

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

BRANCHING if-else statements

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Selection Statements. Pseudocode

conditional statements

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

Repetition and Loop Statements Chapter 5

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

Relational Operators EXAMPLE. C++ By

3 The L oop Control Structure

C: How to Program. Week /Mar/05

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

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

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

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

Lecture 7 Tao Wang 1

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Lecture 10. Daily Puzzle

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

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

Chapter 4: Control Structures I (Selection)

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

Lecture 6. Statements

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lab ACN : C++ Programming Exercises

Control Structures in Java if-else and switch

Module 4: Decision-making and forming loops

CHAPTER 4 CONTROL STRUCTURES

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

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

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Computer Programming. Decision Making (2) Loops

Chapter 2, Part III Arithmetic Operators and Decision Making

Chapter 3 Problem Solving and the Computer

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

Chapter 8 Statement-Level Control Structure

Problem Solving and 'C' Programming

Chapter 7 Arithmetic

Loops and Files. of do-while loop

Accelerating Information Technology Innovation

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

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

Topics. Chapter 5. Equality Operators

LAB 4.1 Relational Operators and the if Statement

Software Design & Programming I

Control Structures in Java if-else and switch

Lecture 8. Daily Puzzle

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

Computer Programming : C++

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

The C++ Language. Arizona State University 1

Chapter 4. Flow of Control

Dept. of CSE, IIT KGP

5. Selection: If and Switch Controls

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

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

Score score < score < score < 65 Score < 50

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

Loops / Repetition Statements

Theory of control structures

Transcription:

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;

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

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.

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.

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 ;

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;

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;

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

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.

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