EEL3834 Review Session September 13

Similar documents
A First Program - Greeting.cpp

Chapter 2 Elementary Programming

CS102: Variables and Expressions

BITG 1233: Introduction to C++

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

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

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

CSCI 123 Introduction to Programming Concepts in C++

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

C: How to Program. Week /Mar/05

Chapter 2 Primitive Data Types and Operations. Objectives

5. Control Statements

Programming with Java

Data Types and Variables in C language

Chapter 2 - Introduction to C Programming

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

Basic Types, Variables, Literals, Constants

Chapter 2 Primitive Data Types and Operations

6.096 Introduction to C++ January (IAP) 2009

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

Information Science 1

Introduction to C# Applications

Chapter 2 Basic Elements of C++

Chapter 4: Making Decisions

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

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Chapter 4: Making Decisions

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Datatypes, Variables, and Operations

3. Simple Types, Variables, and Constants

Basics of Java Programming

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Numbers. John Perry. Spring 2017

Programming. C++ Basics

CS313D: ADVANCED PROGRAMMING LANGUAGE

2 nd Week Lecture Notes

Objectives. In this chapter, you will:

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

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

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

Programming in C++ 4. The lexical basis of C++

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

Chapter 2. C++ Basics

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

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

CS11 Java. Fall Lecture 1

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Computer Programming : C++

Data types, variables, constants

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

Chapter 2: Data and Expressions

Chapter 2: Using Data

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

Chapter 2. Elementary Programming

The following expression causes a divide by zero error:

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

CSc Introduction to Computing

Fundamental of C programming. - Ompal Singh

CSC Web Programming. Introduction to JavaScript

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

Information Science 1

COMP 202 Java in one week

Chapter 6 Primitive types

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

Introduction to Programming using C++

Data Types Literals, Variables & Constants

Introduction to Programming

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

CSCE 121 ENGR 112 List of Topics for Exam 1

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

CSCI 1061U Programming Workshop 2. C++ Basics

Computer System and programming in C

Types, Operators and Expressions

LECTURE 04 MAKING DECISIONS

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Program Fundamentals

Reserved Words and Identifiers

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 2 ELEMENTARY PROGRAMMING

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

file://j:\macmillancomputerpublishing\chapters\in100.html 3/22/01

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

1.1 Introduction to C Language. Department of CSE

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

Fundamental of Programming (C)

Maciej Sobieraj. Lecture 1

Chapter 1 & 2 Introduction to C Language

Transcription:

EEL3834 Review Session 2011 September 13

From the homework Cast variables to type, don t just assign them to type. It will confuse you later staic_cast<type>(variable) Turn in.cpp file, not.doc,.pdf, etc. Use CONSTANTS Programming Style sheet

Compiler C++ and many other high level languages require a compiler Converts/translates program into machine (object,.obj) code Looks for errors as it goes along Translates C++ into a format the system can understand. Compilers are hardware dependent C++ is playorm independent; it can be used on any operaing system (Windows, Mac, Linux, etc.) EEL3834 Fall 2011 3

Types of Errors Syntax Errors RunIme Errors Logic Errors EEL3834 Fall 2011 4

Syntax Errors ViolaIons of the programming language s grammar rules Misspelled words Forge_ng ; at the end of a line Detected by compiler Compiler tries to guess what you had intended Makes reporing someimes hard to understand EEL3834 Fall 2011 5

RunIme Errors Not caught by compiler Crash program during execuion May not crash it every Ime (very frustraing) Example: User enters 0 for a divisor Triggers divide by zero error Program crashes, someimes without obvious explanaion EEL3834 Fall 2011 6

Logic Errors Mistakes that compile Program doesn t necessarily crash Program produces incorrect results These are mistakes in the underlying algorithm Example: Using = instead of == in Boolean experessions Very hard to find EEL3834 Fall 2011 7

Algorithms A systemaic procedure for solving a problem A sequence of precise instrucions that leads to a soluion Describes what acions are required to solve a problem Examples on board EEL3834 Fall 2011 8

IdenIfiers Variable names, function names, etc Rules Consists of letter, digits, and underscores Must start with letter or underscore Must not start with a digit Do NOT start with _ because compiler uses names like that Must not be a keyword (see Appendix 1 in Savitch)

IdenIfiers cont. IdenIfiers are case sensiive (test is not the same as Test or TEST) No length limit, but best to keep under 32 characters Choose descripive variable names (radius not x, area not y) Use lowercase lehers for one- word variables Capitalize first leher of all words in variable name except first one. studentssleeping, numberofas, totalstudents

Keywords Reserved Words whose meanings cannot be redefined by the user Examples int, double, return, if, while Full list in Appendix 1 of Savitch

Constants const int HOWMANYSTUDENTS = 42; const double PI = 3.14159; const prevents you from accidentally changing the value in code It is used exactly like the number it replaces Always use all CAPS for constant names

Why use constants? Makes the code more understandable What does that number mean again? Where did it come from? Easier to modify code In the example above, if more students come or drop, I only have to change the code in one place Different occurances of the same number may have different meanings, i.e. 42

Simple Variable Types Name Memory Used Size Range Precision short (also called short int) 2 bytes - 32,768 to 32,768 N/A int 4 bytes - 2,147,483,648 to 2,147,483,647 long (also called long int) 4 bytes - 2,147,483,648 to 2,147,483,647 N/A N/A float 4 bytes Approx. 10-38 to 10 38 7 digits double 8 bytes Aprrox. 10-308 to 10 308 15 digits long double 10 bytes Aprrox. 10-4932 to 10 4932 19 digits char 1 byte All ASCII characters N/A bool 1 byte true, false N/A

chars Single byte used to represent an ASCII character ASCII: American Standard Code for InformaIon Interchange Savitch Appendix 3 shows most of the ASCII character set Represented by single quotes: F = 70, f = 102, + = 43, 3 = 51 Note last one!

Choosing Variable Types Always use int unless double required! FloaIng point math is computaionally expensive FloaIng point math has round- off error which can lead to undesirable comparison results On embedded systems, memory is also a major factor (although becoming less of one each day) Not all embedded processors have floaing point capability

Shorthand Operators Operators for self references += AddiIon Assignment i += 4; => i = i+4; - = SubtracIon Assignment i - = 4; => i = i- 4; *= MulIplicaIon Assignment i *= 4; => i = i*4; /= Division Assignment i /= 4; => i = i/4; %= Modulus Assignment i %= 4; => i = i%4;

Increment and Decrement Operators Unity self reference operators ++var Preincrement var++ PosIncrement - - var Predecrement var- - Postdecrement

Increment & Decrement in Subexpressions Don t do it! int n = 2; n = n + (++n); // Which evaluates first? // This is undefined so result can be either 5 or 6

Order of OperaIons Most are left-associative (evaluated left to right) a + b - c + d => ((a + b) - c) + d Exception: Assignment operators are right-associative (evaluated right to left) a = b += c /= 5 => a = (b += (c /= 5))

Escape Characters See Savitch pg 18 \a Alert (bell) \b Backspace \n New Line (Line Feed) \r Carriage return (return to line start) \t Tab \\ Backslash \ Single quote \ Double quote

Boolean Data Type Have two values: true (1) and false (0) Any non- zero value evaluates to true Examples: bool lightson = true; bool lightson = 1; bool lightson = - 300; All of the above set lightson to 1

RelaIonal Operators Return a Boolean value of 0 or 1 < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to!= Not equal to

RelaIonal Examples int x = 8; x!= 4 => true x < 7 => false x >= 8 => true

Logical Operators! NOT && AND OR (this symbol is typically above Enter on the keyboard)

Truth Tables Savitch pg. 48 Display 2.2 AND exp_1 exp_2 exp_1 && exp_2 true true true true false false false true false false false false OR exp_1 exp_2 exp_1 && exp_2 true true true true false true false true true false false false NOT exp!(exp) true false false true

Use Parentheses for Clarity Do NOT do this: m < x < n Is read as (m < x) < n Should be: (m < x) && (x < n)

if- else statements Execute an acion iff a condiion is true, otherwise, execute another acion. If(booleanExpression) { // MulIple lines of stuff } else { // Do something else }

EnumeraIon You can declare your own variable type Similar to int, char, bool, etc. Enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; Day day; day = TUESDAY; This is much like bool with true and false being 1 and 0, only with more states Capitalize the first leher of an enumerated type Capitalize the enirety of the valid values The values (e.g. MONDAY) are idenifiers, not strings

EnumeraIon ConInued Each value stored as a CONSTANT integer in memory Each idenifier is assigned a value staring at 0 In code above MONDAY = 0, TUESDAY = 1, WEDNESDAY = 2, THURSDAY = 3, FRIDAY = 4 You can assign different values if desired enum Day { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY = 15, FRIDAY}; MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 15, FRIDAY = 16 Comparing values MONDAY < TUESDAY returns true

switch DefiniIon: a slender, flexible shoot, rod, etc., used especially in whipping or disciplining [students] Actually, it is a handy way of implemening a long if- else string

switch layout switch(switch-expression) { case value1: statement(s); break; case value2: statement(s); break;... case valuen: statement(s); break; default: statement(s); } // Values cannot include variables // Values must be constants or literals // If no break, the code will continue on // default not required, but recommended to // at least catch errors

switch Example switch(day) { case MONDAY: cout << read for C++ class ; } break; case TUESDAY: cout << come to C++ class ; break; case WEDNESDAY: case 15: cout << Do C++ homework ; break; case FRIDAY: cout << The week is almost over! ; default: cout << It\ s the weekend!!! ;

Methods for creating program 1) What inputs will the program have? 2) What outputs will the program have? 3) What variables will the program need? a) Why it is very good to declare your variables at the top of your function 4) Flow chart the logic 5) Double check the logic 6) Write the program

while while(loopcontinuationcondition) { // Body of loop // Do stuff here } loopconinuaioncondiion is a Boolean expression that is evaluated before each cycle through the loop Each cycle through the loop is called an itera)on

while Example int count = 0; while(count < 3) { cout << \a ; count ++; } // Trace through on board

while Gotchas Beware of infinite loops! Make sure that your exit condiion exists Use ctrl+c to bail out while(count > -4) while(1) Forge_ng the count++; Avoid using == and!= when reasonable There are Imes to use them Generally beher ways than == or!=

do-while Loops Just like while loop except the Boolean condiion is evaluated a,er each cycle do { // Body: Do stuff here } while (loopcontinuationcondition); // Don t forget the trailing ;

The for loop Extremely useful Loops a fixed number of Imes Like while loop, but compacts control variable iniializaion and modificaion for(initialaction; loopcontinuationcondition; afteriterationaction) { } // Body: Do stuff here

Example: Sound alert 3 times for(int i=0; i < 3; i++) { cout << \a ; } // Note no ; after i++)

Which Loop to Use? while and for are pre- test loops Check condiion before first iteraion do- while is a post- test loop Check condiion aer first iteraion Generally can write any loop with any of the loops Use the most intuiive one The one that makes the program flow most clear

Which loop to use? for Best for loops with fixed number of iteraions Good for iniializing control variable while Best for loops with unknown number of iteraions do- while Like while Use where at least 1 iteraion of loop is required

Loop Keywords break Immediately ends ( breaks out of ) current loop or switch statement coninue Ends current iteraion of current loop Loop may coninue to run ConInuaIon condiion is then checked break and coninue are rarely absolutely necessary (some say never) Avoid them if possible coninue can be paricularly hard to read/understand

EXAM ON THURSDAY