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

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

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

Chapter 2. C++ Basics

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

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3

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

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

File I/O CS 16: Solving Problems with Computers I Lecture #9

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

Programming with C++ as a Second Language

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

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Chapter 3. More Flow of Control

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

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

This watermark does not appear in the registered version - Slide 1

Increment and the While. Class 15

Fundamentals of Programming CS-110. Lecture 2

REPETITION CONTROL STRUCTURE LOGO

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Why Is Repetition Needed?

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Getting started with C++ (Part 2)

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Add Subtract Multiply Divide

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Programming in C++ PART 2

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

Computer Programming : C++

Introduction to Programming EC-105. Lecture 2

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

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

Repetition Structures

Fundamentals of Structured Programming

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

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

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

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

These are notes for the third lecture; if statements and loops.

CIS 130 Exam #2 Review Suggestions

2 nd Week Lecture Notes

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Introduction. C provides two styles of flow control:

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Unit 7. 'while' Loops

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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

BITG 1233: Introduction to C++

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

C++ Support Classes (Data and Variables)

CS16 Exam #1 7/17/ Minutes 100 Points total

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

A First Program - Greeting.cpp

CSCI 123 Introduction to Programming Concepts in C++

ECE 122. Engineering Problem Solving with Java

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Understanding main() function Input/Output Streams

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

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

Introduction to C ++

CMPS 221 Sample Final

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

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

Your First C++ Program. September 1, 2010

MIPS Assembly: More about MIPS Instructions Using Functions in MIPS CS 64: Computer Organization and Design Logic Lecture #8

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

CpSc 1111 Lab 4 Formatting and Flow Control

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Practice test for midterm 1

Transcription:

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB

Compiling Programs in C++ Input and Output Streams Simple Flow of Control IF/ELSE Statements Loops (While ; Do-While ; For) Lecture Outline Multiway Branching and the switch command 4/10/18 Matni, CS16, Sp18 2

Compile vs. Run Time Errors Compile Time Errors Errors that occur during compilation of a program. Run Time Errors Errors that occur during the execution of a program Runtime errors indicate bugs in the program (bad design) or unanticipated problems (like running out of memory) Examples: Dividing by zero Bad memory calls in the program (bad memory address) Segmentation errors (memory over-flow) 4/10/18 Matni, CS16, Sp18 3

Compiling Programs in C++ (on a UNIX/Linux OS Machine, like those in CSIL) Use the built-in compiler program g++ At the prompt, do the following: $ g++ <source code> -o <object code> Where: Source code = Your C++ program file. Always has the extension.cpp Object code = What the output executable file will be called. The default version of C++ used by our CSIL g++ is ver. 14. You can force the compiler to use another version with the std option (e.g. std=c++11) 4/10/18 Matni, CS16, Sp18 4

Compiling Programs in C++ (on a UNIX/Linux OS Machine, like those in CSIL) For example: $ g++ myprog.cpp -o myprog Now, to run your program, you run the executable (object file), like this: $./myprog The./ tells the Linux OS that the file myprog is found in the current directory Make sure that you are in the correct directory where your program is! For example, when you first log-in, you will be in your home directory If you program lies within a directory called myprograms, for example, do this before you compile anything: $ cd myprograms cd tells the Linux OS that you want to change directory to myprograms 4/10/18 Matni, CS16, Sp18 5

Can I Access These CSIL Machines Remotely? Yes! Know your username and password for CSIL before hand Let s say they re jimbo and i<3cs16, respectively You will now use that information to remotely log into a CSIL machine These are called csil-<number between 01 and 42> For example: csil-10 4/10/18 Matni, CS16, Sp18 6

Can I Access These CSIL Machines Remotely? Using a Mac it s easy: Open up Terminal and do the following: $ ssh jimbo@csil-10.cs.ucsb.edu Answer whatever questions come up, like your password, etc You are now logged into that CSIL machine! Do your work and then remember to exit using $ exit Using a Windows machine it s easy, but needs some initial setups: Download putty a free program ---OR--- set up you Windows 10 machine for bash-shell and run that instead Google how to do that it s akin to Mac s Terminal application Do the same exact steps as with the Mac instructions 4/10/18 Matni, CS16, Sp18 7

Inputs and Outputs 4/10/18 Matni, CS16, Sp18 8

Data Streams - Definitions Data stream: a sequence of data Typically in the form of characters or numbers Input stream: data for the program to use Typically (standard) originates at the keyboard, or from a file Output stream: the program s output Destination is typically (standard) the display, or other times to a file 4/10/18 Matni, CS16, Sp18 9

Examples of Use (cout) cout << number_of_bars << candy bars\n ; This sends two items to the monitor (display): The value of number_of_bars The quoted string of characters " candy bars\n (note the starting space) The \n causes a new line to be started following the s in bars A new insertion operator (<<) must be used for each item of output Note: do not use single quotes for the strings 4/10/18 Matni, CS16, Sp18 10

Escape Sequences Tell the compiler to treat certain characters in a special way \ (back-slash) is the escape character Example: To create a newline in the output, we use \n as in, cout << "\n"; An alternative: cout << endl; Other escape sequences: \t horizontal tab character \\ backslash character \ quote character \a audible bell character For a more complete list of escape sequences in C++, see: http://en.cppreference.com/ w/cpp/language/escape 4/10/18 Matni, CS16, Sp18 11

Formatting Decimal Places A common requirement when displaying numbers. EXAMPLE: Consider the following statements: double price = 78.5; cout << "The price is $" << price << endl; Do you want to print it out as: The price is $78.5 The price is $78.50 The price is $7.850000e01 Likely, you want the 2 nd option You have to DEFINE that format ahead of time Note: endl is the same as \n and is part of <iostream> 4/10/18 Matni, CS16, Sp18 12

Formatting Decimal Places with cout To specify fixed point notation, use: cout.setf(ios::fixed) To specify that the decimal point will always be shown cout.setf(ios::showpoint) To specify that n decimal places will always be shown cout.precision(n) --- where n can be 1, 2, 3, etc EXAMPLE: double price = 78.5; You usually only need to do this ONCE cout.setf(ios::fixed); in a program, unless you decide to cout.setf(ios::showpoint); change the format later on cout.precision(2); cout << The price is << price << endl; 4/10/18 Matni, CS16, Sp18 13

Inputs via cin cin is an input stream bringing data from the keyboard The extraction operator (>>) removes data to be used and can be used more than once EXAMPLE: cout << "Enter the number of bars in a package\n"; cout << " and the weight in ounces of one bar.\n"; cin >> number_of_bars; cin >> one_weight; Alternative: cin >> number_of_bars >> one_weight; This code prompts the user to enter data then reads 2 data items from cin The 1 st value read is stored in number_of_bars, the 2 nd value in one_weight Data entry can be separated by spaces OR by return key when entered 4/10/18 Matni, CS16, Sp18 14

Entering Multiple Data Input Items Multiple data items are best separated by spaces Data is not read until the Enter key is pressed This allows user to make corrections EXAMPLE: cin >> v1 >> v2 >> v3; Requires 3 whitespace separated values A whitespace = space OR tab OR return When you see this, it means I m demonstrating code in class AND will have it available on the class website! So, user might type: 34 45 12<enter key> or 34<enter key>45<enter key>12<enter key> etc Space chars. Matni, CS16, Sp18 15

4/10/18 Matni, CS16, Sp18 16

Flow of Control Another way to say: The order in which statements get executed Branch: (verb) How a program chooses between 2 alternatives Usual way is by using an if-else statement if (Boolean expression) true statement else false statement 4/10/18 Matni, CS16, Sp18 17

Implementing IF/ELSE Statements in C++ As simple as: if (income > 30000) { taxes_owed = 0.30 * 30000; } else { taxes_owed = 0.20 * 30000; } Where s the semicolon??!? Curly braces are optional if they contain only 1 statement 4/10/18 Matni, CS16, Sp18 18

IF/ELSE in C++ To do additional things in a branch, use the { } brackets to keep all the statements together if (income > 30000) { taxes_owed = 0.30 * 30000; category = RICH ; alert_irs = true; } // end IF part of the statement else { taxes_owed = 0.20 * 30000; category = POOR ; alert_irs = false; } // end ELSE part of the statement Groups of statements (sometimes called a block) kept together with { } 4/10/18 Matni, CS16, Sp18 19

Boolean Statements in IF/ELSE if ( (x >= 3) && (x < 6) ) y = 10; The variable y will be assigned 10 only if x is equal to 3, 4, or 5 if!(x > 5) y = 10; The variable y will be assigned 10 if x is NOT larger than 5 (i.e. if x is 4 or smaller) DESIGN PRO-TIP: Unless you really have to, avoid the NOT logic operator when designing conditional statements 4/10/18 Matni, CS16, Sp18 20

Beware: = vs == = is the assignment operator = = is the equality operator Used to assign values to variables Used to compare values Example: x = 3; Example: if ( x == 3) y = 0; The compiler will actually accept this logical error: if (x = 3) y = 0; Why? It s an error of logic, not of syntax But it stores 3 in x instead of comparing x and 3 Since the result is 3 (non-zero), the expression is true, so y becomes 0 4/10/18 Matni, CS16, Sp18 21

Simple Loops 1: while We use loops when an action must be repeated C++ includes several ways to create loops while, for, do while, etc The while loop example: Output is: Hello Hello Hello int count_down = 3; while (count_down > 0) { cout << "Hello "; count_down -= 1; } 4/10/18 22

Simple Loops 2: do-while Executes a block of code at least once, and then repeatedly executes the block depending on a given Boolean condition at the end of the block. So, unlike the while loop, the Boolean expression is checked after the statements have been executed Output is: Hello int flag = 1; do { cout << "Hello "; flag -= 1; } while (flag > 0); Why is there a semicolon here??!? 4/10/18 Matni, CS16, Sp18 23

Simple Loops 3: for Similar to a while loop, but presents parameters differently. Allows you to initiate a counting variable, a check condition, and a way to increment your counter all in one line. for (counter declaration; check condition statement; increment rule) { } Output is: Hello Hello Hello for (int count = 2; count < 5; count++) { cout << "Hello "; } 4/10/18 Matni, CS16, Sp18

Increments and Decrements by 1 In C++ you can increment-by-1 like this: more common à a++ or like this: ++a Similarly, you can decrement by: a-- or --a 4/10/18 Matni, CS16, Sp18 25

Some Cool Uses of x++ In a while loop, you always need to increment a counter var. Example: int max = 0; while (max < 4) { cout << hi << endl; max++; } What will this print out? 4/10/18 Matni, CS16, Sp18 26

Some Cool Uses of x++ You can make a slight change and save a line of code! Example: int max = 0; while (max++ < 4) { } cout << hi << endl; 4/10/18 Matni, CS16, Sp18 27

When to use x++ vs ++x x++ will assess x then increment it ++x will increment x first, then assess it 95% of the time, you will use the first one In while statements, it makes a difference In for statements, it won t make a difference 4/10/18 Matni, CS16, Sp18 28

Examples for (int c = 0; c < 4; c++) cout << hi << endl; Prints hi 4 times Prints hi 4 times int max = 0; while (max++ < 4) { cout << hi << endl; } for (int c = 0; c < 4; ++c) cout << hi << endl; Prints hi 3 times int max = 0; while (++max < 4) { cout << hi << endl; } 4/10/18 Matni, CS16, Sp18 29

Infinite Loops Loops that never stop must be avoided! Your program will either hang or just keep spewing outputs for ever The loop body should contain a line that will eventually cause the Boolean expression to become false (to make the loop to end) Example: Goal: Print all positive odd numbers less than 6 x = 1; What is the problem with this code? while (x!= 6) { cout << x << endl; while ( x < 6 ) x = x + 2; } x will never be 6! Infinite Loop! What simple fix can undo this bad design? 4/10/18 Matni, CS16, Sp18 30

Using for-loops For Sums To create an accumulated sum, in a for-loop: int sum = 0; for(int count = 0; count < 10; count++) { cin >> next; sum = sum + next; } Note that sum must be initialized prior to the loop body! Why? 4/10/18 Matni, CS16, Sp18 31

Using for-loops For Products Forming an accumulated product is very similar to the sum example seen earlier int product = 1; for(int count = 0; count < 10; count++) { cin >> next; product = product * next; } Note that product must be initialized prior to the loop body Product is initialized to 1, not 0! 4/10/18 Matni, CS16, Sp18 32

Ending a While Loop A for-loop is generally the choice when there is a predetermined number of iterations When you DON T have a predetermined number of iterations, you will want to use while loops The are 3 common methods to END a while loop: 1. List ended with a sentinel value: Using a particular value or calculation to signal the end 2. Ask before iterating: Ask if the user wants to continue before each iteration 3. Running out of input: Using the eof function to indicate the end of a file (more on this when we discuss file I/Os) 4/10/18 Matni, CS16, Sp18 9

1. List Ended With a Sentinel Value cout << "Enter a list of positive integers.\n" << "Place a negative integer after the list to quit.\n"; sum = 0; cin >> number; while (number > 0) { cout << The double of that is: << 2*number << endl; cin >> number; } Notice that the sentinel value is read, but not processed at the end 4/10/18 Matni, CS16, Sp18 34

2. Ask Before Iterating sum = 0; char ans; cout << "Are there numbers in the list (Y/N)?"; cin >> ans; while (( ans == 'Y') (ans == 'y')) { //statements to read and process the number cout << "Are there more numbers(y/n)? "; cin >> ans; } 4/10/18 Matni, CS16, Sp18 35

q Do HW3 for Thursday q New Lab on Wednesday! YOUR TO-DOs q Visit Prof s and TAs office hours if you need help! q Eat all your vegetables 4/10/18 Matni, CS16, Sp18 36

4/10/18 Matni, CS16, Sp18 37