Lab 10: Alternate Controls

Similar documents
Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

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

REPETITION CONTROL STRUCTURE LOGO

Chapter 4 - Notes Control Structures I (Selection)

To become familiar with array manipulation, searching, and sorting.

Lab 4: Introduction to Programming

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

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

In this chapter you will learn:

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

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Increment and the While. Class 15

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

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

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Lab # 02. Basic Elements of C++ _ Part1

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

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

5. Control Statements

Department of Computer and Mathematical Sciences

Computer Programming : C++

Introduction to Programming using C++

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Loops and Files. of do-while loop

Chapter 5: Loops and Files

C++ for Python Programmers

Problem Solving: Storyboards for User Interaction

STUDENT LESSON A12 Iterations

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Why Is Repetition Needed?

VARIABLES & ASSIGNMENTS

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Exceptions, Case Study-Exception handling in C++.

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

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Chapter 3. More Flow of Control

CS 007A Midterm 1 Practice Chapters 1 5

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

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

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

CSI33 Data Structures

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

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Chapter Four: Loops II

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 2 - Control Structures

Scientific Computing

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

If Control Construct

CSCE 206: Structured Programming in C++

do { statements } while (condition);

Programming Language. Functions. Eng. Anis Nazer First Semester

Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

PIC 10A. Review for Midterm I

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Introduction. C provides two styles of flow control:

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

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Repetition Structures

What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

A SHORT COURSE ON C++

PROGRAMMING EXAMPLE: Checking Account Balance

CSCI 1061U Programming Workshop 2. C++ Basics

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

DELHI PUBLIC SCHOOL TAPI

Programming Fundamentals

BITG 1113: Array (Part 1) LECTURE 8

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Chapter 4: Control structures. Repetition

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Flow Control. CSC215 Lecture

C++ Support Classes (Data and Variables)

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

INTRODUCTION TO COMPUTER SCIENCE - LAB

CS110D: PROGRAMMING LANGUAGE I

Unit 3 Decision making, Looping and Arrays

C/C++ Programming Lecture 7 Name:

Chapter 1 - What s in a program?

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Lab Instructor : Jean Lai

Transcription:

_ Unit 2: Programming in C++, pages 1 of 8 Department of Computer and Mathematical Sciences CS 1410 Intro to Computer Science with C++ 9 Objectives: Lab 10: Alternate Controls The objective of this lab is to demonstrate some of the ALTERNATIVE CONTROL STATEMENTS available in C++ and many other high-level programming languages. The basic control statements we have studied so far are the IF-ELSE statement and the WHILE statement (or loop). In this lab we will examine the SWITCH statement, along with the FOR and DO-WHILE statements. The SWITCH statement is closely related to the IF-ELSE statement, and the FOR and DO-WHILE statements are types of loops and therefore similar to the WHILELOOP. Task 1: DO-WHILE loop statement The purpose of this task is to demonstrate the DO-WHILE loop. Recall that in a standard WHILE-LOOP, the loop condition comes before the loop body and is evaluated each time BEFORE the loop body executes. Thus a standard WHILE-LOOP is called a PRE-TEST loop. In some instances it is convenient to delay the evaluation of the loop condition until after the loop body is executed. This is called a POST-TEST loop. In C++, a DO-WHILE statement is used to implement a post-test loop. The general syntax for a DO-WHILE loop is shown below: do list of statements [loop body] while ( loop condition ) The token "do" is a reserved word, as is "while" of course. A DO-WHLE statement executes very much as one would expect. First, the loop body executes. Then the loop condition is evaluated. If it is TRUE, the loop body executes again, the loop condition is evaluated again, and so forth. If the loop condition is FALSE, the program proceeds to the next statement. Therefore, the loop body must execute at least one time, which is not the case for a standard WHILELOOP. Another new feature introduced in this program is the use of the data type " bool ", which is a reserved word. This data type has only two data values associated with it, " true " and " false ", both of which are also reserved words. The data value true is stored in memory as the integer value 1 while false is stored as 0. Statement of the Problem: Create a C++ program called Decoder that will read an encoded string/word from and an input file. Then decode the string and output the decoded message. Assume that we know how to decode the coded strings/words.

Unit 2: Programming in C++, pages 2 of 8 After analyzing the above given problem, the steps and the chart of the algorithm can be designed as follows: 1. Declare necessary variables. 2. Setup necessary values for decoding. 3. Open the file to read. 4. Read a charter. 5. Comparison of the character and the character set to be the end of line 6. Determine if it is the end of the word a. If not, decode the character b. If yes, do nothing. 7. Determine if it is the end of the word a. If not, repeat step 4, 5, and 6. b. If yes, exit. Start Declare necessary variables Setup necessary values for decoding Open the file to read Begin the Loop Read a character Comparison of the character and character set to be the end of line Check if comparison is true False False True Check if comparison is true True End Decode the character Activity 1.1: Each step of the above algorithm and the programming flowchart can be converted to C++ code as follows. 1. Declare necessary variables. fstream InFile; int Shift; bool StopFlag; char C; 2. Setup necessary values for decoding. const int Inverse = 19, Intercept = 21, SizeAlpha = 26; 3. Open the file to read. InFile.open("E:\\InLab91.txt", ios::in); 4. Read a charter. InFile>>C; 5. Comparison of the character and the character set to be the end of line StopFlag = (C == '#');

Lab 10: Functions, page 3 of 8 6. Determine if it is the end of the word a. If not, decode the character b. If yes, do nothing. if (!StopFlag) Shift = C - 'A'; C = char(inverse * (Shift+Intercept) % SizeAlpha + 'A'); cout<<c; 7. Determine if it is the end of the word a. If not, repeat step 4, 5, and 6. b.if yes, exit. while (!StopFlag ); InFile.close(); cin.get(); cin.get(); return 0; Activity 1.2: Predict the output from the program Decoder if the contains the data shown in the Input box. NOTE: You need the ASCII table from Lab 2 to determine the ASCII value for each character. Input: XYBXWWXSG# Predicted Output: Activity 1.3: Start MS Visual Studio and create a new C++ project or use the previous project and add a new cpp file called Decoder to the project. Then add the code in Activity 1.1 to complete the program. Create an input file named InLab91.txt Then run the program Decoder and observe the output. Explain any discrepancies with your predicted output. Obeserved Outut: Activity 1.4: Modify the Decoder program contained in this file by replacing the DO-WHILE loop with a WHILE-LOOP. The modified program should give the same output as with the DO- WHILE loop. Test your program for correctness. Task 2: For-Loop The purpose of this task is to demonstrate the FOR-loop. Because count-controlled loops are used so frequently in programming, a type of statement has been included in the C++ language that makes it easy to set up count-controlled loops. This is a FOR statement. The loop condition initialization and loop condition update are included as part of the syntax of the FOR-loop statement. The outline of the basic syntax for a standard FOR-loop is shown below: for (loop counter = inital value; loop counter <= terminal value; loop counter++)

Unit 2: Programming in C++, pages 4 of 8 list of statements [loop body] There are lots of variations permitted on this basic outline. The token "for" is a reserved word. Since a FOR-loop is a count-controlled loop, a loop counter variable of type int is used to "count" the number of times the loop body executes. As the first part of the FOR-loop syntax, this counter is initialized to some initial value (often 1 or 0). This initialization happens only once. Following a semicolon is the loop condition, which checks to see if the counter is no more than some fixed terminal value. If this condition is true, the loop body will execute, otherwise the loop terminates and execution proceeds to the next statement in the program. Next is the update of the loop condition, which for a count-controlled loop usually consists of adding 1 to the loop counter. This is often accomplished by using the INCREMENT operator ++, which adds 1 to an integer variable. The loop condition is not updated until the loop body is executed. Here is a specific example of a FOR-loop: int i; for ( i = 1; i <= 10; i++ ) cout<<i<<endl; This loop prints the integers 1 to 10 on the screen, one per line. The loop counter is the variable i. The initial value is 1 and the terminal value is 10. The loop body consists of one output statement and executes 10 times altogether. It is possible to write a FOR-loop so that the loop counter is DECREMENTED after each execution of the loop body, rather than incremented. For instance, this FOR loop also prints the integers 1 to 10 on the screen, but in reverse order: int i; for ( i = 10; i >= 1; i-- ) cout<<i<<endl; Activity 2.1: The following program is the Extrema program from Lab8 Task3. Make sure you understand what the program does. #include <iostream> #include <iomanip> #include <fstream> using namespace std; //Program name: Extrema int main(void) int Size, I; double Extremum1, Extremum2, Number; fstream InLab83; InLab83.open("g:\\inlab83.txt", ios::in); InLab83>>Size; InLab83>>Number; Extremum1 = Number; Extremum2 = Number; I = 1; while (I <= Size-1) InLab83>>Number; if (Number < Extremum1) Extremum1 = Number; if (Number > Extremum2) Extremum2 = Number; I++; // while I cout<<"the extrema are " <<fixed<<showpoint<<setprecision(2) <<Extremum1<<" and "<<Extremum2; InLab83.close(); cin.get(); cin.get(); return 0; // main

Lab 10: Functions, page 5 of 8 Activity 2.2: If you don t have Lab8Tsk3.cpp file from Lab8, create a new Lab8Tsk3.cpp file. Then copy the program in Activity 2.1 to Lab8Tsk3.cpp. Don t forget to create data file Inlab83.txt Then run the program and observe the output. InLab83.txt 7 89.25 89-1.75 150-1.8 10 59.3 Observed Output: Activity 2.3: Modify the program Extrema by replacing the WHILE-LOOP with a FOR- LOOP. The modified program should give the same output as with WHILE-LOOP. Test your program for correctness. Task 3: For-Loop The purpose of this task is to give experience with writing FOR loops. As you probably have learned by now, one of the trickiest aspects of writing or tracing a program with loops is when one looping statement is NESTED inside the loop body of another looping statement. Nevertheless, nested loops are a necessary and quite useful tool in programming. In this task, you will complete a program that requires nested FOR-loops. A general syntax outline for nested FOR-loops is shown below: for (counter1 = initial value1; counter <= terminal value1; counter1++) for (counter2 = initial value2; counter2 <= terminal value2; counter2++) inner loop body The first of these FOR-loops (controlled by the variable counter1) is usually called the OUTER loop. As part of its loop body it contains the FOR loop controlled by the variable counter2. This is usually called the INNER loop. With nested loops, the body of the inner loop may execute many times. Here is a specific example: int M, N; for ( M=1; M <= 5; M++ ) for ( N=1; N <= 10; N++ ) cout<<"this is a test"<<endl; In this example, the outer loop is controlled by the variable M and the inner loop is controlled by the variable N. The inner loop body is the output statement. How many times does this statement execute? In other words, how many lines of output does this program fragment produce? Each time the inner loop executes, the output statement executes 10 times. But the inner loop executes 5 different times since it contained within the outer loop. Thus this code fragment produces 5*10 = 50 lines of output. That is quite a lot for such few statements, which is evidence of the power of nested loops. Here is a syntax question: Why are no braces required in this code fragment?

Unit 2: Programming in C++, pages 6 of 8 Activity 3.1: The following program is the skeleton of a program which is supposed to output to a file called MultFile the multiplication table for integers from 0 to 9. This program will require two FOR-loops, one nested inside the other. The control variables for these loops should be I and J, which have already been declared. You will be asked to complete this program in the next activity. #include <iostream> #include <iomanip> #include <fstream> using namespace std; //Program name: MultiplicationTable int main(void) int I, J; fstream MultFile; MultFile.open("g:\\multfile.txt", ios::out); // begin outer for-loop (for rows) // begin inner for-loop (for columns) MultFile<<"Insert proper output here"; MultFile<<endl; cin.get(); cin.get(); return 0; // MultiplicationTable Activity 3.2: Delete cpp file from the Source folder, then add a new cpp file to Lab9 project called Lab9Tsk3.cpp and copy the program MultiplicationTable in Activity 3.1 to Lab9Tsk3.cpp. Then modify the program MultiplicationTable by completing the given partial program. The following is how MultiFile.text looks. MultiFile: 0*0=0 0*1=0 0*2=0 0*3=0 0*4=0 0*5=0 0*6=0 0*7=0 0*8=0 0*9=0 1*0=0 1*1=1 1*2=0 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 * * * 9*0=0 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=64 9*8=72 9*9=81 Task 4: Switch Statement The purpose of this task is to demonstrate the SWITCH statement. Recall that an IF-ELSE statement is used in programming to select between alternative lists of statments to execute. Because IF-ELSE statements are built around Boolean expressions, which can be either true or false, then an IF-ELSE statement can only be used to select between TWO alternative lists of statements. If a programming problem requires multiple alternatives (more than two), then NESTED IF-ELSE statements must be used. This can sometimes lead to confused or "messy" program structure. Therefore in C++, another type of selection statement can be used to select between any numbers of alternative lists of statements to execute. This is called a SWITCH statement. The general syntax outline for a SWITCH statement is given below: switch ( expression ) case expression value: list of statements; break;

Lab 10: Functions, page 7 of 8 case expression value: list of statements; break;. case expression value: list of statements; break; default: list of statements; The reserved words in this statement are "switch", "case", "break", and "default". The expression within the parentheses can evaluate as any type, not just Boolean. When a SWITCH statement executes, first the expression is evaluated. Then from top to bottom, the list of cases is scanned to find the value that matches the actual value of the expression within the parentheses. If such a case is found, then the list of statements for that case is executed. Afterwards, the program proceeds to the next statement after the SWITCH statement. If no matching case is found, then the default list of statements is executed. The SWITCH statement is not a loop, and at most one of the cases executes when a SWITCH statement executes. The default case is optional. For example, any IF-ELSE statement can be rewritten as SWITCH statement in the following way: switch (Boolean expression) case true: list of statements; break; case false: list of statements; break; Note that the list of statements for each case does not need to be a block, that is, it doesn't require braces. But the reserved word "break" is essential. Activity 4.1: Study the following program carefully. #include <iostream> #include <iomanip> using namespace std; //Program name: TaskFour int main(void) char CapLetter; for (CapLetter = 'V'; CapLetter >= 'Q'; CapLetter--) switch (CapLetter) case 'R': cout << "Chuck is a ranger" << endl; break; case 'C': cout << "Carl is a carpenter" << endl; break; case 'V': cout << "Buffy is not a vampire" << endl; break; case 'S': case 'U': cout << "Sam is a student" << endl; break; case 'T': cout << "Tom is a teacher" << endl; break; default : cout<< "Out of range" << endl; cin.get(); cin.get(); return 0; // Task4 Activity 4.2: Predict the output from the program TaskFour. Predicted Output: Predicted Output:

Unit 2: Programming in C++, pages 8 of 8 Activity 4.3: Delete cpp file from the Source folder, then add a new file Lab9Tsk4.cpp to the project. Copy the program in Activity 4.1 to Lab9Tsk4.cpp. Then run the program TaskFour and observe the output. Observed Output: Activity 4.4: Modify the program so that the For loop initial value is 'R' and the terminal value is also 'R'. Again predict the output from this program, and then run and observe the output. Explain any discrepancies between your predicted and observed outputs. Predicted Output: Observed Output: Activity 4.5: Modify the program in Activity 4.4 by removing all " break; " statements. Again predict the output from this program, and then run and observe the output. Explain any discrepancies between your predicted and observed outputs. Predicted Output: Observed Output: