C++ Reference NYU Digital Electronics Lab Fall 2016

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

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Intro. Scheme Basics. scm> 5 5. scm>

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

Fundamentals of Programming Session 4

T H E I N T E R A C T I V E S H E L L

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

Intro. Speed V Growth

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

4. Java Project Design, Input Methods

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

Divisibility Rules and Their Explanations

Chapter 1 Operations With Numbers

Memory Addressing, Binary, and Hexadecimal Review

Skill 1: Multiplying Polynomials

Programming for Engineers Introduction to C

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

Introduction to TURING

CS50 Supersection (for those less comfortable)

QUIZ: What value is stored in a after this

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Pre-Algebra Notes Unit One: Variables, Expressions, and Integers

Full file at

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

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

3 The L oop Control Structure

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

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Introduction. C provides two styles of flow control:

Part II Composition of Functions

MITOCW watch?v=0jljzrnhwoi

Math 25 and Maple 3 + 4;

STUDENT LESSON A12 Iterations

Introduction to the C++ Programming Language

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

(Refer Slide Time: 00:26)

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

PLT Fall Shoo. Language Reference Manual

Boolean Expressions. Is Equal and Is Not Equal

12. Pointers Address-of operator (&)

COMP 110 Project 1 Programming Project Warm-Up Exercise

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Java Bytecode (binary file)

The Very Basics of the R Interpreter

C: How to Program. Week /Mar/05

6.096 Introduction to C++

UNIT- 3 Introduction to C++

Language Reference Manual

Boolean Expressions. Is Equal and Is Not Equal

2 nd Week Lecture Notes

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

The for Loop. Lesson 11

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

Unit. Programming Fundamentals. School of Science and Technology INTRODUCTION

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Bits, Words, and Integers

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Chapter 17. Fundamental Concepts Expressed in JavaScript

Lesson Plan. Preparation

First Java Program - Output to the Screen

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Computer Programming : C++

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Chapter 2 - Introduction to C Programming

Simple Java Programming Constructs 4

C++ Support Classes (Data and Variables)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

JQuery and Javascript

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Visual C# Instructor s Manual Table of Contents

Section 0.3 The Order of Operations

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

If Statements, For Loops, Functions

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Maciej Sobieraj. Lecture 1

The C++ Language. Arizona State University 1

Chapter 2, Part I Introduction to C Programming

C++ Programming Lecture 1 Software Engineering Group

C# Programming Tutorial Lesson 1: Introduction to Programming

Unit E Step-by-Step: Programming with Python

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

LOOPS. Repetition using the while statement

BASIC ELEMENTS OF A COMPUTER PROGRAM

Add Subtract Multiply Divide

Learn Ninja-Like Spreadsheet Skills with LESSON 9. Math, Step by Step

Transcription:

C++ Reference NYU Digital Electronics Lab Fall 2016 Updated on August 24, 2016 This document outlines important information about the C++ programming language as it relates to NYU s Digital Electronics lab. In this class, you ll be using the Teensy 3.2 microcontroller, an Arduino-compatible device that can be programmed using C++. Your instructor will cover different programming concepts throughout the semester as they become relevant, however this supplemental guide is a great way to refresh yourself on old material or to get a leg up on newer material if you choose to do so. C++ is one of the most commonly used programming languages in the world, and it is very popular for audio processing because of its flexibility and fast performance. This document does not cover everything you could ever know about C++, but it does provide a solid foundation upon which you can build and use to create some really cool programs! If you have further questions or encounter problems with this document (including typos or inaccuracies), please contact your instructor.

CONTENTS 2 Contents 1 Programming in Arduino 3 2 Variables 5 3 Basic Math 8 3.1 Addition & Subtraction.......................... 8 3.2 Multiplication & Division........................ 8 3.3 Exponents................................. 9 3.4 Parentheses................................ 9 3.5 Example.................................. 9 4 Conditional Statements 10 4.1 Condition true or false...................... 10 4.2 if Statements............................... 11 4.3 if-else Statements........................... 12 4.4 if-else if Statements........................ 13 4.5 AND & OR Operators.......................... 15 5 Loops 18 5.1 for Loops................................. 18 5.2 while Loops............................... 21 6 Functions 23 6.1 Creating a Function - Example................... 23 6.2 Using a Function - Example..................... 25 7 Further Topics 26

1 PROGRAMMING IN ARDUINO 3 1 Programming in Arduino Throughout this class, you ll be writing your code in Arduino s interactive development environment (IDE). Simply put, an IDE is a piece of software that allows you to both write code in a text editor and to run or deploy the code to the hardware that will run it for us (in this case, the Teensy). When you first create a new program in Arduino (called a sketch), you will see two functions: setup and loop. As the image indicates, setup contains a block of code that will run just once. This happens at the very beginning of your program. After the code within setup finishes, the code within loop will then execute. Unlike setup, the code within

1 PROGRAMMING IN ARDUINO 4 loop will run indefinitely. The code will execute line-by-line until it reaches the end, and then repeat from the beginning again. This will continue happening until you manually stop the program. The setup and loop functions are specific to Arduino. That is, if you try to use the above C++ code for any purpose other than for Arduino or Teensy, your code will not compile. In other words, your computer will basically say, What is this thing called setup and this other thing called loop? I have never heard of these, and I refuse to run your program until you tell me what these words mean!" You know, if computers could talk...

2 VARIABLES 5 2 Variables Think of a variable as a container that holds a specific value. Remember this from math class? y = x + 2 In this case, x and y are both variables. x is a container into which you can store any numeric value. The variable y then takes on a value that is two greater than x. The same concept applies to programming. 1 i n t num = 4 ; 2 double anothernum = 1 0. 4 ; 3 char myletter = ' b ' ; 4 S t r i n g myword = " Hello, World! " ; 5 bool sampleboolval = true ; There are several things to note from the above: A variable can have one of many data types. In the above code, we have: int: a numeric integer value double: a numeric decimal value char: a single character for display or naming purposes. Must be enclosed by single quotes String: a collection or group of characters. Must be enclosed by double quotes bool: either true or false. Shorthand for boolean.

2 VARIABLES 6 You must specify the data type of a variable when you create it You can name a variable whatever you d like with a few exceptions: The name must begin with an alphabetic character (no numbers or other symbols) You may not use words that are reserved by C++ or by Arduino (e.g. you cannot name a variable loop since Arduino already has a function by that name) You can also change a variable s value throughout your code. For example, the following code is completely valid: 1 // I n i t i a l i z e a v a r i a b l e with a value o f 0 2 i n t currentvalue = 0 ; 3 // I n i t i a l i z e another v a r i a b l e with a value o f 3 4 i n t addthisval = 3 ; 5 / Add the two t o g e t h e r and s t o r e the r e s u l t 6 back i n t o the f i r s t v a r i a b l e / 7 currentvalue = currentvalue + addthisval ; Here are several more takeaways: Once you create a variable (line 2), you do not need to specify its type again when referencing it later (line 7) You can add comments to your code (lines 1, 3, 5, 6). These lines are not executed by the program and exist solely to help the reader better understand what the code is doing. Consider this how a programmer takes notes directly

2 VARIABLES 7 in her code. Comment a single line using // or multiple lines by enclosing them by /* */ When assigning a value to a variable, the expression(s) to the right of the equals sign gets evaluated first. The value of the right side is then stored into the variable on the left side. In line 7, the variable currentvalue is updated by adding its own value to that of addthisval. Thus, the old value of 0 gets replaced by a new value of 3.

3 BASIC MATH 8 3 Basic Math C++ can perform many arithmetic and complex mathematical operations and follows the standard order of operations, a.k.a. PEMDAS: 1. Parentheses 2. Exponents 3. Multiplication & Division 4. Addition & Subtraction 3.1 Addition & Subtraction C++ performs these with the standard + and - operator, e.g. 1 i n t mynum1 = 5 ; 2 i n t mynum2 = 3 ; 3 i n t r e s u l t = mynum1 + mynum2; // the r e s u l t i s 8 4 i n t r e s u l t 2 = mynum1 mynum2; // the r e s u l t i s 2 3.2 Multiplication & Division C++ uses an asterisk * for multiplication and a forward slash / for division, e.g. 1 double mynum1 = 1 0 ; 2 double mynum2 = 4 ; 3 double r e s u l t = mynum1 mynum2; // the r e s u l t i s 40.0 4 double r e s u l t 2 = mynum1 / mynum2; // the r e s u l t i s 2. 5

3 BASIC MATH 9 3.3 Exponents We use the pow()* function in C++ to perform exponential operations, e.g. 1 double mynum1 = 2 ; 2 double mynum2 = 3 ; 3 double r e s u l t = pow(mynum1, mynum2) ; //2^3 = 8 4 double r e s u l t 2 = pow(mynum2, mynum1) ; // 3^2 = 9 *If you re programming in C++ outside of Arduino, you may have to perform an additional step in order to make the pow() function available for use. However, this extra step will not be required in this class. See the Functions section of this document for more information on how functions work in general. 3.4 Parentheses Not surprisingly, parentheses in C++ serve the purpose you d expect, i.e. to group numbers & and expressions together, e.g.: 1 double mynum1 = 6 ; 2 double mynum2 = 2 ; 3 double r e s u l t = mynum + mynum2 7 ; // 6+2 7 = 20 4 double r e s u l t = (mynum + mynum2) 7 ; // (6+2) 7 = 56 3.5 Example Here s an example that uses all of the above operations. 1 double r e s u l t = 2 (4 + 2 5. 1 ) / pow (9, 2 ) ; 2 //The value o f r e s u l t as above i s roughly 1.849

4 CONDITIONAL STATEMENTS 10 4 Conditional Statements 4.1 Condition true or false A conditional expression in programming basically asks (and answers) the question, "Is this thing true?" For example: 1 bool myresult = (9 < 1 4 ) ; Here, we are asking the question, "Is it true that 9 is less than 14?" Since the answer is yes, the boolean variable myresult will have the value of true. 1 bool anotherresult = (3 >= 1 7 ) ; Here, we are asking the question, "Is it true that 3 is greater than or equal to 17?" Since the answer is no, the variable anotherresult will have the value of false. The < and >= used above are relational operators, meaning that they define relationships between two values. Here are the such operators we ll be using in this class: > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to*

4 CONDITIONAL STATEMENTS 11!= Not equal to *Note that == is used to compare two values, whereas a single = is used to assign a value. For example, myvar = 5 gives a value of 5 to the variable myvar, whereas myvar == 5 asks the question "does myvar contain the value 5?" 4.2 if Statements In many situations, you ll want to take a specific action only if a certain condition is true. For example, imagine you want to display a message if someone presses a button. Here, the word if is followed by a conditional expression within parentheses. If this condition evaluates to true, then the code within the curly braces will execute. In this particular case, we are asking the question, "Is the buttonispressed variable equal to true?" or in simpler terms, "Has the button been pressed?" If the answer to this question is yes (i.e. true), then the program will display the message on line 18. If the answer to that question is no (i.e. false), then lines 17-19 do not execute, meaning that we ll just skip ahead to line 20 and resume the rest of the program from there.

4 CONDITIONAL STATEMENTS 12 4.3 if-else Statements Now, suppose that we still want to display a message if the button is pressed, however we also want to display a different message if the button is not pressed. Here, we use an if-else statement. The above example shows us that we can execute one of two different pieces of code depending on what has happened in the program so far. Here, we use the same if to specify a condition and a block of code that executes if that condition is true. In addition, we append an else with another block of code to the end of the previous block of code. The else is basically telling the program to do something if that previous condition is not true. In other words, we will always execute ONE of those two blocks of code. Not both. Not neither. Table 1 below shows a more detailed breakdown of what this is doing.

4 CONDITIONAL STATEMENTS 13 C++ Jargon if the condition in parentheses is true...then, execute the code within the curly braces else...execute the code within the next set of curly braces Our Example (Line 16) If someone pressed the button (Lines 17-19)...then, display a message that the button has been pressed (Line 20) Otherwise (i.e. if the button has not been pressed) (Lines 21-23)...Display a waiting message Table 1: What the above if-else statement is doing 4.4 if-else if Statements In an if-else statement, we always execute one of two mutually exclusive blocks of code. This makes the assumption that we have two different states, i.e. there are only 2 possibilities for what can happen. However, what if there are more than two possible states? For instance, instead of a button (states: pushed and not pushed), what if we had a knob that controls volume, and we want to display a message depending on whether the volume is too soft (0 40), too loud (80 100) or just right (41 79)? In this case, we have three different states and could therefore use an if-else statement with multiple conditions. For example:

4 CONDITIONAL STATEMENTS 14 In non-coding terms, the program is doing this: You can add as many else ifs to your if statements as you d like. This allows you to work with as many different scenarios as you need. For example:

4 CONDITIONAL STATEMENTS 15 4.5 AND & OR Operators Section 4.4 basically showed us how C++ allows us to do things like this: If the music is soft Complain - "I can t hear!" Otherwise, if the music is at a comfortable volume Relax and listen Otherwise, if the music is too loud Yell at those damn kids to turn down their jukebox

4 CONDITIONAL STATEMENTS 16 However, sometimes we want to be able to do something only if multiple, simultaneous conditions are true. Consider the following example: If the music is soft Complain - "I can t hear!" Otherwise, if the music is loud AND the station is set to 103.2 $ummer Hitz Start partying! Otherwise Turn the radio off The keyword in this case is AND, meaning that we would only start partying if both conditions (the music is loud as well as the radio being set to a specific station) are true. In C++, we use double ampersands && to indicate an AND operator. Let s make this more applicable to us music tech people. Here s a simple example of how this concept might be applied to using a limiter plugin on an audio track in our favorite DAW. 1 i f ( ( pluginisenabled == true ) && ( trackvolume >= 1. 0 ) ) 2 { 3 trackvolume = 1. 0 ; 4 } Here, we see whether our plugin is enabled and whether the audio track is at a volume we deem to be too loud. In the case that both and ONLY both of those things are

4 CONDITIONAL STATEMENTS 17 true, we set the volume to a maximum value of 1.0. Again, this is an oversimplified example that nevertheless illustrates the concept. Let s consider a different case. Suppose that we want to make sure that a clarinet player is playing notes within a certain frequency range. Frequencies between 220 Hertz and 440 Hertz are okay with us. Anything else is unacceptable, and we want to yell at the musician if we hear anything outside of this range. This situation lends itself well to using an OR operator, which C++ performs with double pipes. 1 i f ( ( c l a r i n e t F r e q u e n c y < 220) ( c l a r i n e t F r e q u e n c y > 440) ) 2 { 3 S e r i a l. p r i n t l n ( "You ' re not playing the r i g h t notes! " ) ; 4 } Here, either condition can be true in order for the angry computer to yell at the clarinet player. If a note falls below 220 Hertz, you get an angry message. If a note goes above 440 Hertz, you get the same angry message.

5 LOOPS 18 5 Loops It s common to find yourself wanting your program to do more or less the same thing a bunch of times. Consider the simple case of printing the numbers 1 through 10. Sure, we technically could do something like this: However, this is horribly inefficient. We could instead do this with one of two types of loops that are very common in C++ as well as in many other languages. These types are the for loop and the while loop. 5.1 for Loops Take the example of printing the numbers 1 through 10. Rather than printing each line individually, we can use a for loop to do this more efficiently. The construction of this type of of loop is shown below.

5 LOOPS 19 1. Use the word for to indicate that this is a for loop. 2. Within parentheses, we initialize a variable to a certain value. Here, we create an integer variable i and set it equal to 1. We end this section with a semicolon. 3. This is the condition under which the content of the loop will execute. Here, as long as i is less than or equal to 10, we will do all the "stuff" within the curly braces below. The condition is followed by another semicolon. 4. Everything within curly braces is the "stuff" that will happen repeatedly. 5. In this case, the stuff to happen is that the current value of i will be displayed to the user. 6. After the stuff in step 5 happens, this statement is executed. Here, after the value of i is printed to the user, the value of i will increase by 1 (i++ is a shorthand way to say i = i + 1). 7. Repeat steps 3 6 until the condition in step 3 is no longer true.

5 LOOPS 20 Still confused? Let s take this example through a few iterations of the loop. 1. We create a variable called i and set it equal to 1. 2. Check the condition. What s the value of i? 1. Is that less than or equal to 10? Yes? Okay then - let s do the stuff in the curly braces. 3. The value of i is 1. Display 1 to the user. 4. Increment i by 1. i is now 2. 5. Check the condition. What s the value of i? 2. Is that less than or equal to 10? Yes? Okay then - let s do the stuff in the curly braces. 6. The value of i is 2. Display 2 to the user. 7. Increment i by 1. i is now 3. 8. Check the condition. What s the value of i? 3. Is that less than or equal to 10? Yes? Okay then - let s do the stuff in the curly braces. 9. The value of i is 3. Display 3 to the user. 10. Increment i by 1. i is now 4. 11. Skip ahead a bit for brevity... 12....i is now 9. 13. Check the condition. What s the value of i? 9. Is that less than or equal to 10? Yes? Okay then - let s do the stuff in the curly braces. 14. The value of i is 9. Display 9 to the user.

5 LOOPS 21 15. Increment i by 1. i is now 10. 16. Check the condition. What s the value of i? 10. Is that less than or equal to 10? Yes? Okay then - let s do the stuff in the curly braces. 17. The value of i is 10. Display 10 to the user. 18. Increment i by 1. i is now 11. 19. Check the condition. What s the value of i? 11. Is that less than or equal to 10? NO! STOP THE PRESSES! THE CONDITION IS FALSE! WE ARE EXITING THE LOOP! This may all seem daunting at first, but with a little bit of practice and repetition, the structure of a for loop will start to make sense. 5.2 while Loops Compared to its aforementioned cousin, the while loop is probably simpler to understand yet requires more setup in order to execute. Here s one way to use a while loop to do our same 1 10 printing example.

5 LOOPS 22 1. Remember how the for loop s structure includes creating a variable? Well, when using a while loop, we have to do that part beforehand. Here, we create an integer variable i and set it equal to 1, just like in the previous example. 2. Here, we specify the word while followed by a condition. In this case, we are checking whether the value of i is less than or equal to 10. 3. Again, curly braces surround the "stuff" we do within the loop. 4. Just like in the for loop, we print the current value of i to the user. 5. After we show i to the user, we then increment i by 1. 6. Keep doing everything within the curly braces (3) until the condition specified in (2) is no longer true. The for loop and while loop examples are two different ways of doing the exact same thing. In fact, many things that can be done using a for loop can also be done using a while loop. In many cases, the type of loop to use is based purely on the programmer s preference.

6 FUNCTIONS 23 6 Functions Functions are self-contained modules of code that exist for very specific purposes. For example, C++ comes with a function called abs() that takes the absolute value of a number. This is useful because it saves us the trouble of having to write out very specific instructions to manually calculate the absolute value every time we want to do so. For example, if we need to do 100 absolute value calculations, having a function lets us go from this: "Hey computer: take this number and give me the same number if it s positive, but give me that number multiplied by negative one if it s negative. Also, do this 100 times." to this: "Hey computer: use the abs() function on this number. Do this 100 times." Clearly, the second option is easier, and this becomes even more useful when we have functions that do tasks much more complex than computing an absolute value. 6.1 Creating a Function - Example Here s a simple, working example of a function in C++:

6 FUNCTIONS 24 1. The function s name is addtwonumbers(). The parentheses after the name indicate that this is a function. 2. A function can have as many or as few parameters as you d like. Each parameter s data type must be specified. This particular function has two parameters, both of which are integers. 3. A function s contents, i.e. everything that the function actually does, must be enclosed by curly braces. 4. The return type indicates what type of value the function will give back to the user. A type of void indicates no return value. This particular function returns a single integer to the user. 5. We use the C++ return keyword to tell the function to give the value stored in the variable result back to the user. In this case, the variable result stores the sum of the two arguments entered by the user.

6 FUNCTIONS 25 6.2 Using a Function - Example In the above example, we create two variables, each of them storing a different integer value. On line 14, we create a variable called result and set its value equal to the result of running our function on our other two numbers. The variables myfirstnumber and mysecondnumber are passed to the function, the function adds the two variables values together (because we told it to when we defined it), and the return value is stored in the variable result. By the time line 14 is finished running, the value of result will be 8. By the time line 15 is finished running, the value of result will be...?

7 FURTHER TOPICS 26 7 Further Topics As mentioned earlier, this document does not discuss every single aspect of C++ programming. Other topics covered throughout the class may include things like: Arrays Variable and Function Scope Libraries...and much more! If you re interested in pursuing more with C++, there are many available, free resources at your disposal. In particular, your NYU tuition pays for a membership to Lynda.com, which contains video lessons on C++ and plenty of other topics. Your instructors are always here to help. Reach out to them with any questions you have about this material.