Problem Solving With C++ Ninth Edition

Similar documents
Computer Programming : C++

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

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

Chapter 2. C++ Basics

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

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Lecture 2 Tao Wang 1

The C++ Language. Arizona State University 1

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

LECTURE 02 INTRODUCTION TO C++

Fundamentals of Programming CS-110. Lecture 2

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

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

UEE1302 (1102) F10: Introduction to Computers and Programming

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

2 nd Week Lecture Notes

Introduction to Programming

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

Introduction to Programming EC-105. Lecture 2

Chapter 2: Introduction to C++

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

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

This watermark does not appear in the registered version - Slide 1

CSc Introduction to Computing

Programming with C++ as a Second Language

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

Basic Computer Programming for ISNE. Santi Phithakkitnukoon ผศ.ดร.ส นต พ ท กษ ก จน ก ร

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

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

UNIT- 3 Introduction to C++

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

BITG 1233: Introduction to C++

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

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 INTRODUCTION

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)

CSCI 1061U Programming Workshop 2. C++ Basics

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

CS242 COMPUTER PROGRAMMING

Computer Science II Lecture 1 Introduction and Background

CS 106 Introduction to Computer Science I

Linear execution of statements. CISC 1600/1610 Computer Science I. Alternatives to linear execution. Linear execution of statements

Maciej Sobieraj. Lecture 1

Visual C# Instructor s Manual Table of Contents

Professor Peter Cheung EEE, Imperial College

A First Program - Greeting.cpp

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

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

Scientific Computing

Full file at C How to Program, 6/e Multiple Choice Test Bank

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

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

Creating a C++ Program

CHAPTER 3 BASIC INSTRUCTION OF C++

Course Outline. Introduction to java

Chapter 2 Basic Elements of C++

CSI32 Object-Oriented Programming

Fundamentals of Structured Programming

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

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

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

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Objectives. In this chapter, you will:

Full file at

Fundamentals of Programming

6.096 Introduction to C++ January (IAP) 2009

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

CSI33 Data Structures

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

C: How to Program. Week /Mar/05

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

Programming. C++ Basics

Add Subtract Multiply Divide

C++ Support Classes (Data and Variables)

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS )

Topic 2: C++ Programming fundamentals

Your First C++ Program. September 1, 2010

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

Engineering Problem Solving with C++, Etter/Ingber

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter 2 - Introduction to C Programming

Introduction to Programming using C++

CSI33 Data Structures

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

Chapter 2: Overview of C++

Getting started with C++ (Part 2)

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

IS 0020 Program Design and Software Tools

Course Outline Introduction to C-Programming

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

COMP 202 Java in one week

Chapter 2: Using Data

Chapter 2. Lexical Elements & Operators

CSCE 110 PROGRAMMING FUNDAMENTALS

IT 1033: Fundamentals of Programming Data types & variables

Transcription:

CISC 1600/1610 Computer Science I Programming in C++ Professor Daniel Leeds dleeds@fordham.edu JMH 328A Introduction to programming with C++ Learn Fundamental programming concepts Key techniques Basic C++ facilities By the end of the course, you will be able to: Write small C++ programs Read much larger programs Learn the basics of many other languages Proceed to advanced C++ courses 2 Requirements Lectures and lab sessions Labs assignments roughly 5 across semester Final project Exams 1 midterm, 1 final Academic integrity discuss assignments with your classmates, but DO NOT copy assignments 3 How to succeed in class Ask questions In class In office hours, tutor room Study together and discuss assignments with each other (without plagiarizing!) Textbook Read and re-read the material Complete practice problems Start coding and studying early 4 Problem Solving With C++ Ninth Edition Walter Savitch Course textbook Course website http://storm.cis.fordham.edu/leeds/cisc1600 Go online for Lecture slides Assignments Course materials/handouts Announcements 5 6 1

Instructor Prof. Daniel Leeds dleeds@fordham.edu Office hours: Tues 2-3p, Wed 12-1p Office: JMH 328A A program provides a computer with a set of simple instructions to achieve a goal 7 8 Programs are everywhere On your computer: Web browser Request and display information from distant sites Word processor Record text, change appearance, save to disk Music player Organize mp3 s, select time in song, play, stop Programs are everywhere In the dining hall: Cashier Compute price of food purchase, charge payment to account, (if pay cash: compute change) HVAC Monitor temperature, adjust A/C or heating Electronic signs Display menus and prices, load and display university news 9 10 Programs are everywhere In humans: Sports When to run, where to run; when to pass, who to pass to; when to shoot The brain Neurons working together to combine information about an image to recognize a dog or a car Head detector Tail detector dog 11 Computer system structure Central processing unit (CPU) performs all the instructions Memory stores data and instructions for CPU Input collects information from the world Output provides information to the world Input Output CPU 12 2

C++ high-level language Why C++? High-level language Uses words to describe instructions More intuitive to people Computer-independent Machine-language Uses binary to describe instructions Less intuitive to people Computer-dependent C++ code balance=balance-charge; assembly code 10000000 10000100 00110010 01110100 machine code Compiler 13 Popular modern programming language In use since 1980 s Similar structure to many/most other popular languages (Java, C#, Perl, Python) 14 Why C++? Some programming history: C++ developed as improvement on C C developed as improvement on B B developed as improvement on BCPL Basic Computer Programming Language Various languages before BCPL ADA, COBOL, FORTRAN Course outline Programming basics, input/output, arithmetic Conditional statements Loops Modularity functions Complex data arrays, vectors strings, and classes Throughout the semester: Proper programming style 15 16 Programming basics Program structure and components Output text Variables Input information Perform arithmetic Type safety Our first program: Hello world! cout << "Hello world!\n"; // output "Hello world! 17 Hello world! > 18 3

The components of Hello world! Comments //, /* */ main function Preprocessor directives #include 19 Using comments cout << "Hello world!\n"; // output "Hello world!" Explain programs to other programmers Ignored by compiler Syntax: // single line comment /* multi-line comment */ 20 Preprocessor directives cout << "Hello world!\n"; // output "Hello world!" main function cout << "Hello world!\n"; // output "Hello world!" Lines beginning with # Executed before compiling the program 21 Every C++ program has the function maincontains the instructions to be executed by the program The instructions included in the body of main are placed between curly braces { } 22 Statements Using white spaces cout << "Hello world!\n"; // output "Hello world!" cout << "Hello world!\n"; // output "Hello world!" Instructions to be performed when the program is run Each statement is completed with a ; White spaces are blank lines, space characters, and tabs White spaces are ignored by the compiler Use indentation to group pieces of code together 23 24 4

Output command cout << "Hello world!\n"; cout << "text"; outputs the specified text to the screen cout is the output stream object The text is delimited by double-quotes " " Only use simple quotes (") not curly quotes ( ) <<is the stream insertion operator directing the text into cout Terminology: A character is any single letter or symbol. E.g.: 'b', '?', '&' A collection of characters is called a string. E.g.: "Hello world", "afe094n", "C++ is fun! " 25 Output command, part 2 cout << "Hello world!\n"; Hello world! > Escape character: backslash \ Escape sequence: backslash followed by another character New line: \n Tab: \t cout << "Hello\n world!\n"; 26 Output command, part 3 cout << "Hello world!\n"; Hello world! > We can place multiple stream insertion operators in a sequence. cout << "Hello" << " world."; cout << "How are \nyou today?"; 27 User input: Hello! string name; // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" // end program What is your name? Alice Hello Alice! > 28 Variables Variables store information char single character ('a', 'Q') int integers (-4, 82) bool logic (true or false) float real numbers (1.3,-0.45) vector string sequence ofvalues ({16,5}, {-2.3,3.4,-0.4}) text ("Hello", "reload") 29 Variable declaration string name; Updated for September 11, 2014 // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" // end program Declare new variable by writing type followed by variable name. More examples: int age, weight; // multiple declarations 30 5

Variable declaration and initialization All variables must be declared before they are used int cost; // declare variable Variables are initialized with the first assignment statement cost = 25; // initialize variable Declaration and initialization can be performed in one line int weight = 140; Constant variables The value of a variable ordinarily can be changed throughout the program const fixes variable value after initialization const float healthytemp = 98.6; 31 32 Variable names A variable name is any valid identifier that is not a keyword Starts with a letter, contains letters, digits, and underscores (_) only Cannot begin with a digit Case sensitive: username username UserName Variable names, part 2 Choose meaningful names Avoid acronyms Avoid lengthy names Good: age, size, address, count, sumdata x, y, i single letters as counting variables Bad: rbi, lda, xz25, neuron_response_magnitude 33 34 Keywords Also known as: Reserved names Examples cout, return, string, int Must be used as they are defined in the programming language Cannot be used as variable names 35 Variable assignment Typically, variables are assigned values with the = operator string weather; weather = "sunny"; cout << "The weather today is "; cout << weather << endl; The variable to be changed is always to the left of the = operator The value assigned from the right of the = operator Constants: weight = 140; Variables: ageerica = agejen; Expressions: balance = balance cost; 36 6

Input command string name; // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" // end program cin >> varname; receives input from keyboard saves into the varname Arithmetic in C++ Operators Addition: 5 + 2 evaluates to 7 Subtraction: 5-2 evaluates to 3 Multiplication: 5 * 2 evaluates to 10 Division: 4 / 2evaluates to 2 Modulo: 5 % 2 evaluates to 1 (only integers) 37 38 Order of operations First: Parentheses Second: Multiplication, Division, Modulo Third: Add, Subtract Evaluate from Left to Right Evaluate inner-most parentheses before outer ones int a = ( 4 * ( 5 + 2 ) - 4 ) / 4; Assignment operators int a = 6; Standard assignment: a = 3; Other assignments: a += 3; // a = a + 3; a -= 3; // a = a - 3; a *= 3; // a = a * 3; a /= 3; // a = a / 3; a %= 3; // a = a % 3; 39 40 Increment and decrement int c = 12; Increment by 1: c++evaluates to c + 1 Decrement by 1: c-- evaluates to c - 1 What does this program do? { int dollars, coins; cout << "How many dollars do you have? "; cin >> dollars; coins = dollars*4; cout << "I will give you " << coins; cout << " coins.\n"; } 41 42 7

The binary representation int age = 65;assigns a binary code to memory: 00000000000000000000000001000001 char grade = 'A';assigns a binary code to memory: 01000001 Every variable value is a number in binary, C++ interprets the binary number based on the variable type From numbers to symbols: the ASCII table 43 44 Variable types, revisited char single character ('a', 'Q') 1 byte int integers (-4, 82) 4 bytes bool logic (true or false) 1 byte float real numbers (1.3,-0.45) 4 bytes vector sequence ofvalues? bytes ({16,5}, {-2.3,3.4,-0.4}) string text ("Hello","reload")? bytes Each variable is represented by a certain number of 0s and 1s Each 0-or-1 is a bit 8 bits in a row is a byte 45 Variables locations in memory Each variable indicates a location in memory Each location holds a value Value can change as program progresses Variable value exists before initialization Address Value grade weight 04B0C320 A 04B0C328 --- 04B0C330 04B0C338 04B0C340 140 04B0C348 04B0C350 P 46 Assigning between types int x = 5; float y = -2.5; float z = x * y; int g = y - x; 47 Assigning between types int vs float If compiler permits, floats will be rounded to nearest integer and intswill be expanded to a precision float int vs char If compiler permits, char will be converted to integer ASCII code and intwill be converted to corresponding ASCII character int vs bool If compiler permits, boolwill be converted to 0 (if false) or 1 (if true) and intwill be converted to false (of 0) or 1 (if not 0) int x = 5; float y = -2.5; float z = x * y; int g = y - x; 48 8