Controlling Execution - Selection and Iteration

Similar documents
QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

6. Control Structures

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Lecture 2 Notes: Flow of Control

Chapter 5. Selection 5-1

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Chapter One Introduction to Programming

While Loop. 6. Iteration

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Basics of I/O Streams and File I/O

Chapter 8 Selection 8-1

Two-way selection. Branching and Looping

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Object Oriented Software Design

Sources: On the Web: Slides will be available on:

I PUC - Computer Science. Practical s Syllabus. Contents

Object Oriented Software Design

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

JavaScript: Control Statements I

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Syllabus OBJECT ORIENTED PROGRAMMING C++

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Introduction to Java

Chapter 2: Elements of Java

Chapter 5 Functions. Introducing Functions

C++ Language Tutorial

Passing 1D arrays to functions.

ALGORITHMS AND FLOWCHARTS

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Programming and Software Development CTAG Alignments

El Dorado Union High School District Educational Services

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

C++ Input/Output: Streams

The While Loop. Objectives. Textbook. WHILE Loops

1 Description of The Simpletron

Informatica e Sistemi in Tempo Reale

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Introduction to Python

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Algorithm & Flowchart & Pseudo code. Staff Incharge: S.Sasirekha

Visual Logic Instructions and Assignments

UEE1302 (1102) F10 Introduction to Computers and Programming

Curriculum Map. Discipline: Computer Science Course: C++

Statements and Control Flow

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Selection Statements

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

7.7 Case Study: Calculating Depreciation

Moving from C++ to VBA

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computer Programming I

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Fundamentals of Programming and Software Development Lesson Objectives

Lecture 1 Introduction to Java

EKT150 Introduction to Computer Programming. Wk1-Introduction to Computer and Computer Program

Appendix K Introduction to Microsoft Visual C++ 6.0

CSC 221: Computer Programming I. Fall 2011

Conditions & Boolean Expressions

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

VB.NET Programming Fundamentals

Java Basics: Data Types, Variables, and Loops

The C Programming Language course syllabus associate level

Boolean Expressions & the if Statement

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

Comp151. Definitions & Declarations

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Basic Programming and PC Skills: Basic Programming and PC Skills:

arrays C Programming Language - Arrays

A brief introduction to C++ and Interfacing with Excel

C++ INTERVIEW QUESTIONS

13 Classes & Objects with Constructors/Destructors

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Answers to Selected Exercises

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

TIP: To access the WinRunner help system at any time, press the F1 key.

Tutorial on C Language Programming

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Java Application Developer Certificate Program Competencies

Computer Programming I

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Problem Solving Basics and Computer Programming

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Transcription:

Controlling Execution - Selection and Iteration Until now, statements were all simple statements. Here we will introduce structured statements. First of all, a compound statement is a sequence of 2 or more consecutive statements (simple, compound, and/or structured) enclosed within and }. I. Selection Constructs if if/else nested if switch/case if statement In pseudocode (structured English) we might express a decision as: If student s grade is greater than or equal to 60 Print Passed In C++ this would be coded as: if (grade >= 60) cout << Passed ; Syntax for if statement: if <boolean expression > <statement1> ; A boolean expression represents a condition that is either true or false. It is formed using operands (constants, variables) and operators (arithmetic operators, relational operators, logical operators). Arithmetic Relational Logical + - < less than > greater than or * / % == equal to && and!= not equal to arithmetic functions <= less than or equal to >= greater than or equal to! not Ex. if ((x > 0) && (a == b)) n_controlstructures.doc.doc 1 of 15

if/else statement Operator Precedence Operator Associativity Type ( ) L R parenthesis ++ +! R L unary operators *? % L R multiplicative + L R additive << >> L R insertion < <= > >= L R relational = =!= L R equality && L R and L R or?: R L conditional = += = *= /= %= R L assignment In pseudocode: If student s grade is greater than or equal to 60 Print Passed else Print Failed In C++ if (grade >= 60) cout << Passed ; else cout << Failed ; syntax for if/else statement: if <boolean expression > <statement1> [else <statement2>]; The C++ conditional operator -?: Same as the if/else structure but more compact. This is the only ternary operator in C++. Example: grade>=60? cout << Passed : cout << Failed ; This is the same as: cout << (grade >=60? Passed : Failed ); n_controlstructures.doc.doc 2 of 15

In this case, the conditional expression evaluates to Passed if the condition is true and to Failed if the condition is false. ==FLOWCHARTING== //maximum.cpp // Finding the largest of 3 values int A, B, C, max; cout << "Enter 3 values, and I will tell you which is largest.\n"; cin >> A >> B >> C; //really should have user prompts here if (A > B) max = A; else max = B; if (C > max) max = C; cout << "The maximum is " << max << endl; RUN #1: RUN#2: n_controlstructures.doc.doc 3 of 15

Nested-if //nestedif.cpp // modified from Hubbard Ex. 2.14 // This program converts a test score into // its equivalent letter grade. int score; cout << "Enter the test score: "; cin >> score; if (score > 100) cout << "Error: score is out of range." ; else if (score >= 90) cout << 'A'; else if (score >= 80) cout << 'B'; else if (score >= 70) cout << 'C'; else if (score >= 60) cout << 'D'; else if (score >= 0) cout << 'F'; else cout << "Error: score is out of range."; return 0; //successful termination Why does this work? EXPLAIN. n_controlstructures.doc.doc 4 of 15

Switch //switch.cpp // modified from Hubbard Ex. 2.15 // This program converts a test score into // its equivalent letter grade, using a switch statement. int score; cout << "Enter the test score: "; cin >> score; switch (score/10) case 10: case 9: cout << 'A' << endl; break; case 8: cout << 'B' << endl; break; case 7: cout << 'C' << endl; break; case 6: cout << 'D' << endl; break; case 5: case 4: case 3: case 2: case 1: case 0: cout << 'F' << endl; break; default: cout << "Error: score is out of range.\n"; } How does this work? The computer "drops down" through the "empty" conditions. EXPLAIN. n_controlstructures.doc.doc 5 of 15

In the following example, the function rand() is defined in the header file <stdlib>. rand() generates pseudo-random unsigned integers in the range of 0 to RAND_MAX. RAND_MAX is a constant which is also defined in <stdlib>. II. Iteration (Repetition) Constructs In order to control iteration, we use one of three structured control statements. for while do/while A Counting Program: We would like to write a program that will print the integers between 1 and 20, say, like the following output: n_controlstructures.doc.doc 6 of 15

Here s one way: //counting2.cpp // A Counting Program // Using a FOR/DO Loop using namespace std; int count ; for (count=1; count<=20; count++) cout << count << endl; Here s another way: //counting.cpp // A Counting Program // Using a WHILE/DO Loop using namespace std; int count; count = 1; while (count <=20) cout << count << endl; count = count + 1; } n_controlstructures.doc.doc 7 of 15

And yet another way: //counting3.cpp // A Counting Program // Using a DO/WHILE Loop using namespace std; int count; count = 1; do cout << count << endl; count = count + 1; } while (count <=20); return 0; //successful termination A Summing Program We wish to write a program that will calculate the sum of the integers between 1 and 20. The program: //sum1.cpp // A Summing Program // Using a WHILE/DO Loop using namespace std; int sum, count ; sum = 0; count = 1; while (count <=20) sum = sum + count; count = count + 1; } cout << "The sum of the integers from 1 through 20 is "; cout << sum << endl; n_controlstructures.doc.doc 8 of 15

produces this output: and so does this program: //sum2.cpp // A Summing Program // Using a FOR Loop using namespace std; int sum, count ; sum = 0; for (count=1; count<=20; count++) sum = sum + count; cout << "The sum of the integers from 1 through 20 is "; cout << sum << endl; Just an Average Program ;-) //average1.cpp // This program calculates the average of any number of numbers. // Using the while/do structure int n, count; float x, sum, avg; count = 1; sum = 0; cout << "How many numbers? "; cin >> n; while (count <=n) cout << "? "; cin >> x; sum = sum + x; count++; } //end while avg = sum / n; n_controlstructures.doc.doc 9 of 15

cout << "The average is " << avg << endl; //average2.cpp // This program calculates the average of any number of numbers. // Using the for structure int n, count; float x, sum, avg; sum = 0; cout << "How many numbers? "; cin >> n; for (count=1; count<=n; count++) cout << "? "; cin >> x; sum = sum + x; } //end for avg = sum / n; cout << "The average is " << avg << endl; n_controlstructures.doc.doc 10 of 15

When to use the while construct? When to use for? Improving our Output Setw is a stream, insertion manipulator that sets the field width of the output. It requires the iomanip.h header file, i.e.,: #include <iomanip> The following program illustrates how it works. //columns.cpp // Some Calculations // Prettier output using stream manipulators #include <iomanip> int number, square, cube; cout << setw(6) << "NUMBER" << setw(8) << "SQUARE"; cout << setw(8) << "CUBE" << endl << endl; for (number=1; number <=20; number++) square = number * number; cube = square * number; cout << setw(6) << number << setw(8) << square; cout << setw(8) << cube << endl; } //end for of program n_controlstructures.doc.doc 11 of 15

n_controlstructures.doc.doc 12 of 15

Branching - Break and Continue Statements Conditional vs. unconditional branching. goto These statements should be used only when absolutely necessary. Break - to break out of a loop. Transfers control to the first statement after the end of the loop. Example. What is output? // Deitel2-26.cpp // This program is modified from the Deitel book, Figure 2.26, p.104. // Using the break statement in a for structure using namespace std; int x; for (x=1; x<=10; x++) if (x==5) break; //break loop only if x is 5 cout << x << " "; } //end for cout << "\nbroke out of loop at x = " << x << endl; cout<< endl << endl << endl; of program n_controlstructures.doc.doc 13 of 15

Continue - skips the remainder of the body of the loop, and continues the loop. Transfers control to loop again. Example. What is output? // Deitel2-26.cpp // This program is modified from the Deitel book, Figure 2.27, p.105. // Using the Continue statement in a for structure using namespace std; int x; for (x=1; x<=10; x++) if (x==5) continue; // skip remaining code in loop // only if x is 5 cout << x << " "; } //end for cout << "\nused continue to skip printing the value 5 " << endl; cout << endl << endl << endl; of program n_controlstructures.doc.doc 14 of 15

Random Numbers Using switch, break, for, mod //TestRandNums.cpp // This program gets 1000 random numbers and tests them #include <stdlib> int num0, num1, num2, num3, num4, num5, num6, num7, num8, num9; num0=num1=num2=num3=num4=num5=num6=num7=num8=num9=0; for (int i=0; i<1000; i++) int r = rand()%10; //remainder gives a one digit RN //between 0 and 9 switch (r) case 0: num0++; break; //Note: This program will be more case 1: num1++; break; //efficient when we learn arrays. case 2: num2++; break; case 3: num3++; break; case 4: num4++; break; case 5: num5++; break; case 6: num6++; break; case 7: num7++; break; case 8: num8++; break; case 9: num9++; break; default: cout << "Error: unexpected random number" << r <<endl; } //end switch } //end for cout << "number of 0 : " << num0 << endl; cout << "number of 1 : " << num1 << endl; cout << "number of 2 : " << num2 << endl; cout << "number of 3 : " << num3 << endl; cout << "number of 4 : " << num4 << endl; cout << "number of 5 : " << num5 << endl; cout << "number of 6 : " << num6 << endl; cout << "number of 7 : " << num7 << endl; cout << "number of 8 : " << num8 << endl; cout << "number of 9 : " << num9 << endl; n_controlstructures.doc.doc 15 of 15