6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

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

Object Oriented Software Design

Informatica e Sistemi in Tempo Reale

C++ Language Tutorial

Object Oriented Software Design

Lecture 2 Notes: Flow of Control

Chapter One Introduction to Programming

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

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

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

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Example of a Java program

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

Java Interview Questions and Answers

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:

An Incomplete C++ Primer. University of Wyoming MA 5310

The C Programming Language course syllabus associate level

PL / SQL Basics. Chapter 3

6.087 Lecture 2 January 12, 2010

Objective-C Tutorial

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

JavaScript: Control Statements 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 SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

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

I PUC - Computer Science. Practical s Syllabus. Contents

1 Description of The Simpletron

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

Chapter 2: Elements of Java

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

Introduction to Python

J a v a Quiz (Unit 3, Test 0 Practice)

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

A brief introduction to C++ and Interfacing with Excel

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Pemrograman Dasar. Basic Elements Of Java

Fundamentals of Programming

C++ INTERVIEW QUESTIONS

Basics of I/O Streams and File I/O

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

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

While Loop. 6. Iteration

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

Chapter 5. Selection 5-1

Syllabus OBJECT ORIENTED PROGRAMMING C++

Introduction to Visual C++.NET Programming. Using.NET Environment

Unit 6. Loop statements

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

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Comp151. Definitions & Declarations

Java Basics: Data Types, Variables, and Loops

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

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

PROBLEMS (Cap. 4 - Istruzioni macchina)

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Moving from CS 61A Scheme to CS 61B Java

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Chapter 3 Operators and Control Flow

Chapter 2 Elementary Programming

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

Member Functions of the istream Class

Statements and Control Flow

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Chapter 5 Names, Bindings, Type Checking, and Scopes

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

13 Classes & Objects with Constructors/Destructors

AP Computer Science Java Subset

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Two-way selection. Branching and Looping

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

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

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

The While Loop. Objectives. Textbook. WHILE Loops

C++ Input/Output: Streams

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

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

Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University

VHDL Test Bench Tutorial

Database Programming with PL/SQL: Learning Objectives

Computer Programming I

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

Introduction to Java

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

The programming language C. sws1 1

Conditions & Boolean Expressions

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Java Crash Course Part I

C PROGRAMMING FOR MATHEMATICAL COMPUTING

How to test and debug an ASP.NET application

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++ Programming Language

El Dorado Union High School District Educational Services

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

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

Transcription:

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values within the source code; can be integers (ex: 1, 0, -17), floating points (ex: 3.11596535897, 1., 6.096, 3), characters (ex: a,, \n ), strings (ex: 6.096, a ), booleans (ex: true, false) Defined constants (#define): user-defined named constants that do not require memoryconsuming variables. When the preprocessor sees the #define, it will replace every subsequent occurrance of the identifier in the source code. 1 # include < iostream > 3 using namespace std ; 5 # define PI 3.1159 6 # define NEWLINE \n 7 8 int main () 9 { 10 double r = 5.0; 11 double circle ; 1 13 circle = * PI * r; // circle = * 3.1159 * r; 1 cout << circle << NEWLINE ; // cout << circle << \n ; 15 16 return 0; 17 } Declared constants (const): user defined constants with const prefix with a specific type that are declared the same way as variables. The value of a const variable cannot be modified. 1

1 const int pathwidth = 100; // pathwidth = ; this will cause a compiler error! 3 const char tabulator = \ t ; cout << " tabulator =" << tabulator << \ n ; 1 3 5 6 1. L-values, R-values lvalue is short for left hand side value (of an assignment). Examples of non-lvalue expressions: 3+3 // you can t assign 3+3 to something "str" // the literal "str" can t take on another value const int i = 3 // can t change the value of const variable Examples of lvalue expressions: int var // var is an lvalue because we can assign it with some value float x rvalue is short for right hand side value because rvalues can appear on the right hand side of an assignment. Anything with a well-defined value can be an rvalue, including an assigment: (x = 5) can be used as an rvalue whose value is 5, e.g. y = (x=5);. 1.3 Increment, Decrement operators (++, --) a++ and ++a are shorthand for a = a + 1 with a big warning sign: ++a will increment a and then return the value (so it will return one greater than the original value) a++ will return the current value and then increment --a will decrement a and then return the value (so it will return one less than the original value) a-- will return the current value and then decrement // this code outputs 0 to 9 for ( int i = 0; i < 10;) { cout << i++ << "\n"; }

7 // this code outputs 1 to 10 8 for ( int i = 0; i < 10;) 9 { 10 cout << ++i << "\n"; 11 } 1. Assignment operators Assignment ops include +=, -=, *=, /=, %=, etc.; a += 5 is equivalent to a = a + 5, etc. 1.5 Type Conversions Used for changing between data types. Also called casts. Type conversions are implicit when changing from smaller data type to a bigger data type or data type of same size (e.g. float to double or int to float). Type conversions usually must be explicitly stated when changing from bigger datatype to smaller datatype or when there could be a loss of accuracy (e.g. int to short or float to int), but implicitly converting from a double to an int will not generate a compiler error (the compiler will give a warning, though). 1 int x = ( int ) 5.0; // float should be explicitly " cast " to int short s = 3; 3 long l = s; // does not need explicit cast, but // long l = ( long )s is also valid 5 float y = s + 3.; // compiler implicitly converts s 6 // to float for addition 1.6 Operator precedence Like arithmetic, C++ operators have a set order by which they are evaluated. The table of operators and their precedence is listed in the following table: 3

1 () [] ->. :: Grouping, scope, array/member access! * & sizeof (type cast) ++ (most) unary operations, sizeof and typecasts 3 * / % Multiplication, division, modulo + - Addition and subtraction 5 << >> Bitwise left and right shift 6 < <= > >= Comparisons: less than, etc. 7 ==!= Comparisons: equal and not equal 8 & Bitwise AND 9 ˆ Bitwise exclusive OR 10 Bitwise inclusive (normal) OR 11 && Logical AND 1 Logical OR 13?: Conditional expression (ternary operator) 1 = += -= *= /= %=, etc. Assignment operators 15, Comma operator 1.7 Ternary operator (?:) An operator that takes three arguments and defines a conditional statement. 1 if (a > b) result = x; 3 else result = y; is equivalent to 1 result = a > b? x : y; 1.8 switch statement A type of selection control statement. Its purpose is to allow the value of a variable or expression to control the flow of program execution via multiple possible branches. Omitting break keywords to causes the program execution to fall through from one block to the next, a trick used extensively. In the example below, if n =, the fifth case statement (line 10) will match the value of n, so the next line outputs n is an even number. Execution then continues through the next three case statements and to the next line, which outputs n is a prime number. This is a classic example of omitting the break line to allow for fall through. The break line after a case block causes the switch statement to conclude. The default block (line 1) is executed if no other cases match, in this case producing an error message if n has multiple digits or is negative. The default block is optional in a switch statement. 1 switch (n) {

case 0: 3 cout << " You typed zero.\ n"; break ; 5 case 1: 6 case : 7 case 9: 8 cout << "n is a perfect square.\ n"; 9 break ; 10 case : 11 cout << "n is an even number.\ n"; 1 case 3: 13 case 5: 1 case 7: 15 cout << "n is a prime number.\ n"; 16 break ; 17 case 6: 18 case 8: 19 cout << "n is an even number.\ n"; 0 break ; 1 default : cout << " Only single - digit positive numbers are allowed.\ n"; 3 break ; } 1.9 break Used for breaking out of a loop or switch statement. 1 // outputs first 10 positive integers int i = 1; 3 while ( true ) { 5 if (i > 10) 6 break ; 7 cout << i << "\n"; 8 ++i; 9 } 1.10 continue Used for skipping the rest of a loop body and continuing to the next iteration. 1 // print out even numbers in for ( int i = 0; i <= 10; ++ i) 3 { range 1 to 10 5

if (i %!= 0) 5 continue ; // skips all odd numbers 6 cout << i << "\n"; 7 } 1.11 References Wikipedia: http://en.wikipedia.org/ Cplusplus: http://www.cplusplus.com/ 6

Hello, World! This section is about writing the canonical Hello, World! program and its derivatives. Now is a good time to get used to your development environment. Submit each program in a separate source file named section. subsection.cpp..1 Hello World I Write a program that outputs Hello, World! by printing a const char * with value Hello, World!.. Hello World II Write a program that outputs Hello, World! n times (where n is a nonnegative integer that the user will input) with: a for loop. a while loop. a do...while loop. 7

3 More Programs Now that you have had some practice working in your development environment, here are some more challenging tasks. Again, submit your work (source code and answers to questions) in an appropriately named text file. 3.1 Scope For these questions, you are encouraged to use a computer. 1. Below is a sample program. Use it to answer the following question: What happens if we declare the same name twice within a block, giving it two different meanings? 1 # include < iostream > 3 using namespace std ; 5 int main () 6 { 7 int arg1 ; 8 arg1 = -1; 9 int x, y, z; 10 char mydouble = 5 ; 11 char arg1 = A ; 1 cout << arg1 << "\n"; 13 return 0; 1 } Hints: Did your program compile? If so, what does it print? If not, what error message do you get?. Below is a sample program. Use it to answer the following question: What happens if we declare an identifier in a block, and then redeclare that same identifier in a block nested within that block? 1 # include < iostream > 3 using namespace std ; 5 int main () 6 { 7 int arg1 ; 8 arg1 = -1; 9 { 10 char arg1 = A ; 11 cout << arg1 << "\n"; 8

1 } 13 return 0; 1 } Hints: Did your program compile? If it does, what does the program output? If not, what error message does it produce? 3. Below is a sample program. Use it to answer the following question: Suppose an identifier has two different declarations, one in an outer block and one in a nested inner block. If the name is accessed within the inner block, which declaration is used? 1 # include < iostream > 3 using namespace std ; 5 int main () 6 { 7 int arg1 ; 8 arg1 = -1; 9 { 10 char arg1 = A ; 11 cout << arg1 << "\n"; 1 } 13 return 0; 1 }. Below is a sample program. Use it to answer the following question: Suppose an identifier has two different declarations, one in an outer block and one in a nested inner block. If the name is accessed within the outer block, but after the inner block, which declaration is used? 1 # include < iostream > 3 using namespace std ; 5 int main () 6 { 7 int arg1 ; 8 arg1 = -1; 9 { 10 char arg1 = A ; 11 } 1 cout << arg1 << "\n"; 13 return 0; 1 } 9

5. Below is a sample program that will not compile. Why not? By moving which line can we get the code to compile? 1 using namespace std ; 3 int main () { 5 cout << " Hello, World!\n"; 6 return 0; 7 } 8 9 # include < iostream > 3. Basic Statistics Given a list of N integers, find its mean (as a double), maximum value, minimum value, and range. Your program will first ask for N, the number of integers in the list, which the user will input. Then the user will input N more numbers. Here is a sample input sequence: 3 <-- N 1 3 Three numbers are given:, 1, 3. The output should be as follows: Mean: Max: 3 Min: 1 Range: 3.3 Prime Numbers Write a program to read a number N from the user and then find the first N primes. A prime number is a number that only has two divisors, one and itself. 3. Multiples of numbers 3..1 Ternary operator Write a program that loops indefinitely. In each iteration of the loop, read in an integer N (declared as an int) that is inputted by a user, output N if N is nonnegative and divisible by 5 5, and -1 otherwise. Use the ternary operator (?:) to accomplish this. (Hint: the modulus operator may be useful.) 10

3.. continue Modify the code from 3..1 so that if the condition fails, nothing is printed. Use an if and a continue command (instead of the ternary operator) to accomplish this. 3..3 break Modify the code from 3.. to let the user break out of the loop by entering -1 or any negative number. Before the program exits, output the string Goodbye!. 3.5 What does this program do? Do these problems without the use of a computer! 1. What does this snippet do? Try doing out a few examples with small numbers on paper if you re stuck. (Hint: Think about numbers in binary notation in base. How would you express a number as a sum of powers of? You may also find it useful to note that multiplying by n is equivalent to multiplying by n times. You should also keep in mind the distributive property of multiplication: a(x + y) = ax + ay.) 1 // bob and dole are integers int accumulator = 0; 3 while ( true ) { 5 if ( dole == 0) break ; 6 accumulator += (( dole % == 1)? bob : 0); 7 dole /= ; 8 bob *= ; 9 } 10 cout << accumulator << "\n";. What does this program do? What would the operating system assume about the program s execution? 1 # define O 1 // That s an oh, not a zero int main () 3 { return O; 5 } 3. What does this program do? 1 // N is a nonnegative integer double acc = 0; 3 for ( int i = 1; i <= N; ++i) { 11

5 double term = (1.0/ i); 6 acc += term * term ; 7 for ( int j = 1; j < i; ++j) 8 { 9 acc *= -1; 10 } 11 } 1 cout << acc << "\n"; 1

Factorials Gone Wrong This section focuses on debugging programs. We will start off with a simple factorial program and do a step by step troubleshooting routine..1 Writing the factorial program Here is the code for a factorial program. Copy it into your IDE and verify that it compiles. 1 # include < iostream > 3 using namespace std ; 5 int main () 6 { 7 short number ; 8 cout << " Enter a number : "; 9 cin >> number ; 10 11 cout << " The factorial of " << number << " is "; 1 int accumulator = 1; 13 for (; number > 0; accumulator *= number - -); 1 cout << accumulator << ".\n"; 15 16 return 0; 17 } What do you get when you enter the following values: 0, 1,, 9, 10?. Breaking the program Run the program and enter 1. What happens? How can you change the code such that it won t exhibit this behavior?.3 Breaking the program II Try entering some larger numbers. What is the minimum number for which your modified program from. stops working properly? (You shouldn t have to go past about 5. You may find Google s built-in calculator useful in checking factorials.) Can you explain what has happened?. Rewriting Factorial Modify the given code such that negative inputs do not break the program and the smallest number that broke the program before now works. Do not hardcode answers. 13

.5 Rewriting Factorial II Since we know that only a small number of inputs produce valid outputs, we can alternatively hardcode the factorials of these inputs. Rewrite the program from the previous part ( Rewriting Factorial ) using a switch statement to demonstrate for inputs up to 10 how you would do this. (Of course, the code for inputs above 10 would basically be the same, but you do not need to go through the work of finding all those large factorials.).6 Further testing Are there any other inputs we have to consider? Why or why not? 1

MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 011 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.