int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Similar documents
The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Why Is Repetition Needed?

do { statements } while (condition);

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

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

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

Unit 7. 'while' Loops

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

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

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

1 Unit 8 'for' Loops

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

Chapter 1 INTRODUCTION

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

VARIABLES & ASSIGNMENTS

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

CS354 gdb Tutorial Written by Chris Feilbach

C++ Programming Language Lecture 2 Problem Analysis and Solution Representation

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

Chapter 2 Basic Elements of C++

How to approach a computational problem

Outline. Program development cycle. Algorithms development and representation. Examples.

Scientific Computing

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

The following expression causes a divide by zero error:

CSCE 121 ENGR 112 List of Topics for Exam 1

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

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

REVIEW. The C++ Programming Language. CS 151 Review #2

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

Introduction to Programming using C++

As an example using arrays, let s write some code to get started with the Upthrust game. We can use a 2D array to represent the game board.

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

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

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

EE 355 Lab 4 - Party Like A Char Star

Object Oriented Design

printf( Please enter another number: ); scanf( %d, &num2);

Perl Basics. Structure, Style, and Documentation

CSC 126 FINAL EXAMINATION FINAL Spring 2012 B. Name (last, First) Instructor. Total Possible. Received

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

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

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

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

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Fundamentals of Programming CS-110. Lecture 2

What we will learn about this week:

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

CS2141 Software Development using C/C++ C++ Basics

CS242 COMPUTER PROGRAMMING

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

C++ Support Classes (Data and Variables)

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

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

Chapter 3. More Flow of Control

Getting Started with Visual Studio

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

Chapter 17 - Notes Recursion

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

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

Introduction to Programming

Computer Programming : C++

CSc Introduction to Computing

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!

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

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

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Fundamentals of Programming Session 4

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

READ THIS NOW! Do not start the test until instructed to do so!

CS 103 Lab 6 - Party Like A Char Star

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

Introduction to Programming EC-105. Lecture 2

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

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

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

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

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

6.096 Introduction to C++ January (IAP) 2009

Lab 4: Introduction to Programming

Another Simple Program: Adding Two Integers

Using the Command Line

LECTURE 02 INTRODUCTION TO C++

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

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

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

Chapter 2. C++ Basics

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

Flow of Control: Loops

We first learn one useful option of gcc. Copy the following C source file to your

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

CSCE 206: Structured Programming in C++

Tutorial 2: Compiling and Running C++ Source Code

5. Control Statements

Transcription:

Debugging Some have said that any monkey can write a program the hard part is debugging it. While this is somewhat oversimplifying the difficult process of writing a program, it is sometimes more time consuming and frustrating to debug a program than it was to write it in the first place. However there are tools to help you! The purpose of this lecture is to introduce you to some of these tools. In general we have two methods of debugging: 1. Adding print statements, which has the benefit of working in any programming language and in any environment, but is very tedious and can sometimes actually lead to errors 2. Using the debugging utilities in NetBeans or DrJava or Visual Studio There is also a debugger in Unix called jdb for the Java environment and gdb for C/C++. We won t cover it here, but you should be aware that it exists if you plan to more development under Unix. Debugging with Print Statements You have probably already used this method for debugging. The basic idea is very simple. If your program is not working correctly, try inserting print statements (in C++ this would be cout statements) to narrow wn where the error is. The print statements could be used to locate the section of code that contains the problem, and they might output the values of some variables that would aid in debugging. As one example, consider the code below: int n = 10; int sum = 10; while (n > 1) sum = sum + n; n--; cout << "The sum of the integers 1 to 10 is " << sum << endl; Upon running this program, it esn t add the numbers from 1-10. You can probably eyeball what is wrong but if you n t see it then to find out what is wrong, you can trace the variables n and sum by inserting output statements as follows: int n = 10; int sum = 10; while (n > 1)

cout << "At the beginning of the loop: n = " << n << endl; cout << "At the beginning of the loop: sum = " << sum << endl; sum = sum + n; n--; cout << "At the end of the loop: n = " << n << endl; cout << "At the end of the loop: sum = " << sum << endl; cout << "The sum of the integers 1 to 10 is " << sum << endl; The first four lines of the execution are as follows: At the beginning of the loop: n = 10 At the beginning of the loop: sum = 10 At the end of the loop: n = 9 At the end of the loop: sum = 20 We can immediately see that something is wrong. The variable sum has been set to 20. Since it was initialized to 10, it is set to 10 + 10, which is incorrect if we want to sum the numbers from 1 to 10. Let s illustrate both good and bad debugging techniques with an example. Suppose our program is presenting a menu where the user can select A or B. The purpose of the following code is to validate user input from the keyboard and to make the user type a choice again if something other than A or B is entered. To be more user-friendly, the program should allow users to make their selections in either uppercase or lowercase. #include <iostream> using namespace std; int main() char c = ' '; cout << "" << endl; tolower(c); while ((c!= 'a') (c!= 'b')); return 0; The program runs but if we enter any letter we get the menu twice! f

If we employ the guessing technique we might try to input the character twice. After all, the prompt is showing up twice! Such a change will fix this error, but it may cause other problems. In this case, we re still stuck in the loop. We can add a print statement to see if we can figure out what is going wrong: cout << "c is " << c << endl; The output becomes: f c is This should jog our memory! c is blank. This is because it read in the newline after the character is entered. We can use the ignore function to discard it: cout << "" << endl; tolower(c); while ((c!= 'a') (c!= 'b')); At this point we have corrected the syntax error and our program will compile, but it will still not run correctly. A sample execution is shown below: C B A (Control-C)

The program is stuck in an infinite loop even when we type in a valid choice. The only way to stop it is to break out of the program (in the sample output by hitting Control-C, but you may have to use a different method depending on your computing environment). At this point we could employ tracing to try to locate the source of the error. Here is the code with output statements inserted: cout << "" << endl; tolower(c); cout << "c is: " << c << endl; while ((c!= 'a') (c!= 'b')); Sample output is as follows: A c is: A The cout statement makes it clear what is wrong the string s es not change to lowercase. A review of the tolower( ) cumentation reveals that this function es not change the calling char, but instead returns a new char converted to lowercase. The calling char remains unchanged. To fix the error, we can assign the lowercase char back to the original with However, we re not ne yet. Even after fixing the lowercase error, the program is still stuck in an infinite loop, even when we enter A or B. A novice programmer might patch the program like so to exit the loop: cout << "" << endl; if ( c == 'a') break; if (c == 'b') break; while ((c!= 'a') (c!= 'b')); This forces the loop to exit if a or b is entered, and it will make the program work. Unfortunately, the result is a coding atrocity that should be avoided at all costs. This quick fix es not address the root cause of the error only the symptoms. Moreover, such patches usually won t work for new cases. This particular fix also results in inconsistent code because the expression((c! = 'a') (c! = 'b')) becomes

meaningless when we already handle the a and b with the if and break statements. To really find the bug, we can turn again to tracing, this time focusing on the Boolean values that control the -while loop: cout << "" << endl; cout << "c!= 'a' is " << (c!= 'a') << endl; cout << "c!= 'b' is " << (c!= 'b') << endl; cout << "(c!= 'a') (c!= 'b')) is " << ((c!= 'a') (c!= 'b')) << endl; while ((c!= 'a') (c!= 'b')); The sample output is now as follows: A c!= 'a' is 0 c!= 'b' is 1 (c!= 'a') (c!= 'b')) is 1 Since c equals a, the statement (c!= 'a') evaluates to false and the statement (c!= 'b') evaluates to true. When combined, (false true) is true, which makes the loop repeat. In spoken English it sounds like c not equal to a or c not equal to b is a correct condition to repeat the loop. After all, if the character typed in is not a or the character typed in is not b, then the user should be prompted to try again. Logically however, if (c!= 'a') is false (i.e., the character is 'a'), then (c!= 'b') must be true. A character cannot make both expressions false, so the final Boolean condition will always be true. The solution is to replace the or with an and so that the loop repeats only if (c!= 'a') && (c!= 'b')). This makes the loop repeat as long as the input character is not a and it is not b. An even better solution is to declare a boolean variable to control the -while loop. Inside the body of the loop we can set this variable to false when the loop should exit. This technique has the benefit of making the code logic easier to follow, especially if we pick a meaningful name for the variable. In the following example it is easy to see that the loop repeats if invalidkey is true: bool invalidkey = true; cout << "" << endl;

if (c == 'a') invalidkey = false; else if (c == 'b') invalidkey = false; else invalidkey = true; while (invalidkey); The approach of adding print statements has the nice benefit that it works in any programming environment. As such, it is useful to know. However, there are definite drawbacks. First, it is very tedious. The programmer must first figure out where to add the print statements, and then add them and recompile the program. After running the program, more print statements may likely be needed, so they will need to be added and recompiled again. Finally, when the program works as intended, the programmer must go back and remove all of those print statements that were added. Sometimes the process of adding and removing print statements can mess up the program if the programmer deletes an actual line of text by mistake, or if the programmer adds new temporary variables or logic to aid in debugging! There must be a better way, and there is: the solution is to use an integrated debugger. Debugging in Visual Studio We ll give a short demo of the same program in class.