CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

Similar documents
Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

Announcements. Homework 0 out! Coming soon: 1. remote access 2. programming instructions 3. lab 1 (graded!) this week

Announcements. Lab 1 this week! Homework posted Wednesday (late)

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

bool bool - either true or false

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

Add Subtract Multiply Divide

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

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

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

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++

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

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

Chapter 2. Outline. Simple C++ Programs

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

Chapter 2. C++ Basics

Objectives. In this chapter, you will:

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

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

C++ Support Classes (Data and Variables)

UNIT- 3 Introduction to C++

The C++ Language. Arizona State University 1

Creating a C++ Program

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

More loops Ch

Announcements. HW 0 due tonight (check that it compiles on CSE labs) (make sure you submit the code part)

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

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

Lecture 3 Tao Wang 1

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Fundamentals of Programming CS-110. Lecture 2

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Programming Language. Functions. Eng. Anis Nazer First Semester

Scientific Computing

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

Introduction Jan. 22, Ch 1

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

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

BITG 1233: Introduction to C++

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

Chapter 2 C++ Fundamentals

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Boolean Algebra Boolean Algebra

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

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

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

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

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

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

Fundamental of Programming (C)

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

A SHORT COURSE ON C++

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

Full file at

Computer Science II Lecture 1 Introduction and Background

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C: How to Program. Week /Mar/05

Visual C# Instructor s Manual Table of Contents

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

3.1. Chapter 3: The cin Object. Expressions and Interactivity

LECTURE 02 INTRODUCTION TO C++

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

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

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

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

Introduction to Programming using C++

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

Learning to Program with Haiku

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

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Chapter 2: Introduction to C++

6.096 Introduction to C++

Computing and Statistical Data Analysis Lecture 3

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Learning to Program with Haiku

Program Organization and Comments

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Programming. C++ Basics

Transcription:

C++ Basics

CSCI 1113 Wednesdays: 1:25-2:15 Keller 1-250 Thursdays: 4:00-4:50 Akerman 211 Peer-assisted Learning sessions - PAL Weekly practice with course concepts Work with peers to reinforce understanding of course material Practice extra problems, write code, review for quizzes No pressure of grades and great place to form a study group FREE - no need to register just show up

Announcements Lab 1 this week! Homework posted tonight/tomorrow -Due next Wednesday at 4pm

Types of errors Syntax error - code will not compile e.g. cout( hi ); Runtime error - code crashes after starting e.g. (0 input to runtimeerror.cpp) Logic error - code runs but doesn't return the correct answer (see: logicerror.cpp)

Syntax Syntax is a fancy word for the grammar of programming languages The basic English syntax is: (subject) (verb) (noun) I eat bananas not Bananas I eat The computer is VERY picky (and stubborn) about grammar, and will not understand you unless you are absolutely correct!

Avoid errors To remove your program of bugs, you should try to test your program on a wide range of inputs Typically it is useful to start with a small piece of code that works and build up rather than trying to program everything and then debug for hours

Variables Variables are objects in program To use variables two things must be done: - Declaration - Initialization See: uninitialized.cpp Example: I am 0 inches tall. I am -1094369310 inches tall.

Variables int x, y, z; x = 2; y = 3; z = 4; Initialization Declaration Same as: int x=2, y=3, z=4; Variables can be declared anywhere (preferably at start)

Assignment operator = is the assignment operator The object to the right of the equals sign is stored into the object in the left int x, y; y = 2; x = y+2; See: assignmentop.cpp

Assignment operator = is NOT a mathematic equals x=3; x=4; // computer is happy! This does not mean 3=4

Assignment operator To the left of = needs to be a valid object that can store the type of data on the right int x; x=2.6; // unhappy, 2.6 is not an integer x+2 = 6; // x+2 not an object 2 = x; // 2 is a constant, cannot store x

Assignment operator What does this code do? int x = 2, y = 3; y=x; x=y; What was the intention of this code?

Increment operators What does this code do? int x = 2; x=x+1; x+=1; or x++; Same as:

Increment operators Two types of increment operators: x++; // increments after command vs ++x; // increments before command

Complex assignments The following format is general for common operations: variable (operator)= expression variable = variable (operator) expression Examples: x+=2 x = x + 2 x*=y+2 x = x * (y + 2)

Order of operations Order of precedence (higher operations first): -, +, ++, -- and! (unary operators) *, / and % (binary operators) + and - (binary operators) % is remainder operator (example later in simpledivision.cpp)

Order of operations Binary operators need two arguments Examples: 2+3, 5/2 and 6%2 Unary operators require only one argument: Examples: (see binaryvsunaryops.cpp) +x, x++,!x (! is the logical inversion operator for bool)

Order of operations When multiple operations have the same precedence level: Binary operations go from left to right Unary operations go right to left

Identifiers

Identifiers An identifier is the name of a variable (or object, class, method, etc.) type int sum; identifier - Case sensitive - Must use only letters, numbers or _ - Cannot start with a number - (Some reserved identifiers, like main)

Identifiers Already did this in week 1! See: number.cpp

Identifiers Which identifiers are valid? 1) james parker 2) BoByBoY 3) x3 4) 3x 5) x 6) x 7) Home.Class 8) Five% 9) x-1

Identifiers Which identifiers are valid? 1) james parker 2) BoByBoY 3) x3 4) 3x 5) x 6) x 7) Home.Class 8) Five% 9) x-1

(See: float.cpp) Identifiers

Types

Variables We (hopefully) know that if you say: You ask the computer for a variable called x Each variable actually has an associated type describing what information it holds (i.e. what can you put in the box, how big is it, etc.)

Fundamental Types bool - true or false char - (character) A letter or number int - (integer) Whole numbers long - (long integers) Larger whole numbers float - Decimal numbers double - Larger decimal numbers See: intvslong.cpp

int vs long? int - Whole numbers in the approximate range: -2.14 billion to 2.14 billions (10 9 ) long - Whole numbers in the approximate range: -9.22 quintillion to 9.22 quintillion (10 18 ) Using int is standard (unless you really need more space, for example scientific computing)

float vs double?

float vs double? float is now pretty much obsolete. double takes twice as much space in the computer and 1) has wider range and 2) is more precise Bottom line: use double (unless for a joke)

float and double Both stored in scientific notation double x = 2858291; Computer's perspective: x = 2.858291e6 or x = 2.858291 * 10 6

Welcome to binary Decimal: Binary: 1/2 = 0.5 0.1 1/3 = 0.3333333 0.010101010101 1/10 = 0.1 0.0001100110011 double is often just an approximation!

Numerical analysis Field of study for (reducing) computer error See: subtractionerror.cpp Can happen frequently when solving system of linear equations

bool You can use integers to represent bool also. false = 0 true = anything else (You probably won't need to do this)

int or double? If you are counting something (money), use int If you are dealing with abstract concepts (physics), use double int doesn't make rounding mistakes

Primitive type hierarchy bool < int < long < float < double If multiple primitive types are mixed together in a statement, it will convert to the largest type present Otherwise it will not convert type

Primitive type hierarchy int x; double y; int x; int y; x+y x/y Converted to double Not converted (still int)

Integer division See: simpledivision.cpp Can be fixed by making one a double: 1/2.0 or static_cast<double>(1)/2

New lazy types There are a few new lazy types: auto guesses what type you want auto x = 7.5; double x = 7.5; dcltype - declare type uses the expression dcltype('a') x; char x;

Constants You can also make a constant by adding const before the type This will only let you set the value once const double mypi = 3.14; mypi = 7.23; // unhappy computer!

Functions Functions allow you to reuse pieces of code (either your own or someone else's) Every function has a return type, specifically the type of object returned sqrt(2) returns a double, as the number will probably have a fractional part The 2 is an argument to the sqrt function

Functions Functions can return void, to imply they return nothing (you should not use this in an assignment operation) The return type is found right before the functions name/identifier. int main() {... means main returns an int type, which is why we always write return 0 and not return 'a' (there is no char main())

Functions A wide range of math functions are inside <cmath> (get it by #include <cmath>; at top) We can use these functions to compute Snell's Law for refraction angle (See: math.cpp)

Input and output

Strings and input char can only hold a single letter/number, but one way to hold multiple is a string string str; cin >> str; The above will only pull one word, to get all words (until enter key) use: getline(cin, str); (See: stringinput.cpp)

More Output When showing doubles with cout, you can change how they are shown For example, to show a number as dollars and cents, you would type (before cout): cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

More Output There are two ways to get output to move down a line: endl and \n cout << endl;... is the same as... cout << \n I will use both when coding

Madlibs (see: madlibs.cpp)

bool bool - either true or false We will use the following today: > (greater than), e.g. 7 > 2.5 is true == (equals), e.g. 5 == 4 is false <= (less than or eq), e.g. 1 <= 1 is true

if statement Code inside an if statement is only run if the condition is true. Need parenthesis (no semi-colon) Indent (See: numberguessing.cpp)

if/else statement Immediately after an if statement, you can make an else statement If the if statement does not run, then the else statement will If you do not surround your code with braces only one line will be in the if (and/or else) statement

Complex expressions If statements for when x...... is between 10 and 20 (inclusive) Cannot say: 10 <= x <= 20 (why?)... is a vowel (x is type char)

Double trouble! (See: doublecompare.cpp)

Double trouble! When comparing doubles, you should use check to see if relative error is small: fabs((x-y)/x) < 10E-10 (double has about 16 digits of accuracy so you could go to 10E-15 if you want) For comparing Strings, use: (0 if same) string1.compare(string2)

Short-circuit evaluation Short-circuit evaluation is when you have a complex bool expression (&& or ) but you don't need to compute all parts. If this is false, then it will not check next (See: shortcircuit.cpp)

Short-circuit evaluation Simple cases of short-circuit: When you have a bunch of ORs if( expression exp exp exp ) Once it finds any true expression, if statement will be true When you have a bunch of ANDs if( expression && exp && exp && exp ) Once it finds any false expression, if statement will be false

Loop Often we want to do a (similar) command more than once Computer programmers call this code a loop Loops are quite powerful and are very commonly used

while loop A while loop tests a bool expression and will run until that expression is false bool exp. (See: whileloop.cpp)

while loop The bool expression is tested when first entering the while loop And! When the end of the loop code is reached (the } to close the loop)

while loop 3 parts to any (good) loop: - Test variable initialized - bool expression - Test variable updated inside loop

do-while loop A do-while loop is similar to a normal while loop, except the bool expression is only tested at the end of the loop (not at the start) (See: dowhile.cpp) Note semicolon!

do-while loop Q: Why would I ever want a do-while loop? A: When the first time the variable is set is inside the loop. You can initialize the variable correctly and use a normal while loop, but this makes the logic harder

Semi-colons When to put semi-colons? You put semi colons after every statement, except if you (should) start a block Blocks should start after functions, if-statements and loops, thus these should not have semi colons after them