Ch 1. Algorithms and Basic C++ Programming

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

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

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

Programming with C++ as a Second Language

Fundamentals of Structured Programming

CSCI 1061U Programming Workshop 2. C++ Basics

CS110: PROGRAMMING LANGUAGE I

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

Introduction to Programming

Chapter 2. C++ Basics

Chapter 1 Introduction to Computers and C++ Programming

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

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

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

Reserved Words and Identifiers

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Objectives. In this chapter, you will:

Your First C++ Program. September 1, 2010

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

CMPS 221 Sample Final

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

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

Chapter 2. Outline. Simple C++ Programs

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

CS242 COMPUTER PROGRAMMING

2 nd Week Lecture Notes

Getting started with C++ (Part 2)

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

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

A First Program - Greeting.cpp

Fundamentals of Programming Session 4

Computer Programming : C++

Engineering Problem Solving with C++, Etter/Ingber

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

The C++ Language. Arizona State University 1

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

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

Introduction to C++ (Extensions to C)

Week 1: Hello World! Muhao Chen

Chapter 2: Introduction to C++

Chapter 2 Basic Elements of C++

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

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

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

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

LECTURE 02 INTRODUCTION TO C++

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

Computing and Statistical Data Analysis Lecture 3

Full file at

UNIT- 3 Introduction to C++

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

CSI33 Data Structures

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

C: How to Program. Week /Mar/05

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Object Oriented Design

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Fundamentals of Programming CS-110. Lecture 2

Maciej Sobieraj. Lecture 1

BITG 1233: Introduction to C++

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

Introduction to Programming EC-105. Lecture 2

Programming. C++ Basics

CSCI 123 Introduction to Programming Concepts in C++

IS 0020 Program Design and Software Tools

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

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

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

IT 374 C# and Applications/ IT695 C# Data Structures

Programming with C++ Language

H.O.#2 Fall 2015 Gary Chan. Overview of C++ Programming

Understanding main() function Input/Output Streams

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

WARM UP LESSONS BARE BASICS

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

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

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Definition Matching (10 Points)

Computer Science II Lecture 1 Introduction and Background

Chapter 2: Overview of C++

Full file at

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Chapter 1 INTRODUCTION

CHAPTER 3 BASIC INSTRUCTION OF C++

Expressions, Input, Output and Data Type Conversions

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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

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

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

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

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

Creating a C++ Program

Chapter 2: Data and Expressions

Transcription:

2013-2 Ch 1. Algorithms and Basic C++ Programming July 1, 2013 Dept. of Information & Communication Engineering College of Engineering Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr)

Outline Algorithms Step-by-step Procedure of Design and Implementation of a Program Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input (cin) / Output (cout) Program Style Libraries and Namespaces ch 1-2

Evolutions of Human Beings Evolutions with wise usage of new tools increased productivities with new tools of new materials, powered machines: from stone, stick, bronze, iron, telephone and computers increased collaborations among multiple persons increased performance in value creation increased energy efficiencies ch 1-3

What will you get from this course? You will learn how to think like an engineer Technician vs. Engineer Simple passive & repeated implementation vs. creative design and active prototyping You will learn about algorithms and how to design/implement algorithms You will learn programming in C++ You will have fun! ch 1-4

Text Books [1] Absolute C++, 4th Edition, Savitch, Pearson, 2010. [2] Starting out with C++ - Early Objects, 7th Edition, Pearson, 2011. [3] C++ - how to program, Deitel and Deitel, 6th Edition, Pearson Education, 2008. [4] Introduction to Engineering Programming - Solving Problems with Algorithms, James Paul Holloway, John Wiley & Sons, 2004. ch 1-5

Cycles in System design and implementation Design Implementation Problem Specifications (Requirements, Objectives) Analysis of the requirement Evaluate Feasibility Syntax Error Edit program source code Compile Source codes.c,.cc Object codes.o Algorithm design Link Executable codes.exe Software system design Subsystem design Block design Module design Class / Function design Logical Error Load Execute Correct Output? Program Execution output ch 1-6 Mission Completed!!

A list of instructions What is an algorithm? when executed, transform information from input to output The instructions are a finite set of steps that can be executed, in a definite deterministic order When these steps are actually executed, the execution must terminate after a finite time. ch 1-7

Pseudo code How to express algorithm Simplified list of instructions to show the overall process of algorithm not following the details of programming language the skeleton of the algorithm should be shown ch 1-8

Pseudo code Algorithm FindMax() 1: int dataarray[0..n-1] // array of data with N elements 2: int max; 3: int index; 4: index = 0; //initialize index 5: max = dataarray[index]; 6: while (index < N) { 7: if (max < dataarray[index]) 8: max = dataarray[index]; 9: index = index + 1; 10: } // end while 11: 12: printout max; 13: end // end of Algorithm FindMax() ch 1-9

Source code documentations Standard comment at each source code file produced in this course /** * File Name: "???.c" or "xxx.h", or "yyy.cpp" * Description: * - This program is...... * * Programmed by Gil-Dong Hong (Dept. of Info. & Comm. Eng., Yeungnam Univ.), * Last updated: Version 2.0, March 1, 2011 (by Young-Chul Kim). * * ======================================================== * Version Control (Explain updates in detail) * ======================================================== * Updated By Date (YYYY/MM/DD) Version Remarks * John Doe 2009/11/15 1.0 1:1 Chatting on UDP : socket, 2 threads * John Doe 2010/05/01 1.1 User interface has been updated with GUI * Mark Kim 2010/08/03 2.0 Major change in the program structure * ======================================================== */ ch 1-10

Introduction to C++ C++ Origins Low-level languages Machine, assembly High-level languages C, C++, ADA, COBOL, FORTRAN Object-Oriented Programming in C++ C++ Terminology Programs and functions Basic Input/Output (I/O) with cin and cout ch 1-11

A Sample C++ Program (1) ch 1-12

A Sample C++ Program (2) ch 1-13

C++ Variables C++ Identifiers Keywords/reserved words vs. Identifiers Case-sensitivity and validity of identifiers Meaningful names! Variables A memory location to store data for a program Must declare all data before use in program ch 1-14

Simple Data Types (1) ch 1-15

Simple Data Types (2) ch 1-16

Assigning Data Initializing data in declaration statement Results "undefined" if you don t! int myvalue = 0; Assigning data during execution Lvalues (left-side) & Rvalues (right-side) Lvalues must be variables Rvalues can be any expression Example: distance = rate * time; Lvalue: "distance" Rvalue: "rate * time" ch 1-17

Assigning Data: Shorthand Notations Examples of shorthand notations ch 1-18

Data Assignment Rules Compatibility of Data Assignments Type mismatches General Rule: Cannot place value of one type into variable of another type intvar = 2.99; // 2 is assigned to intvar! Only integer part "fits", so that s all that goes Called "implicit" or "automatic type conversion" Literals 2, 5.75, "Z", "Hello World" Considered "constants": can t change in program ch 1-19

Literal Data Literals Examples: 2 5.75 "Z" "Hello World" // Literal constant int // Literal constant double // Literal constant char // Literal constant string Cannot change values during execution Called literals because you literally typed them in your program! ch 1-20

Escape Sequences "Extend" character set Backslash, \, preceding a character Instructs compiler: a special "escape character" is coming Following character treated as "escape sequence char" Display 1.3 next slide ch 1-21

Some Escape Sequences (1) ch 1-22

Some Escape Sequences (2) ch 1-23

Constants Naming your constants Literal constants are "OK", but provide little meaning e.g., seeing 24 in a program, tells nothing about what it represents Use named constants instead Meaningful name to represent data const int NUMBER_OF_STUDENTS = 24; Called a "declared constant" or "named constant" Now use it s name wherever needed in program Added benefit: changes to value result in one fix ch 1-24

Arithmetic Operators Standard Arithmetic Operators Precedence rules standard rules ch 1-25

ch 1-26

Arithmetic Precision Precision of Calculations VERY important consideration! Expressions in C++ might not evaluate as you would "expect"! "Highest-order operand" determines type of arithmetic "precision" performed Common pitfall! ch 1-27

Arithmetic Precision Examples Examples: 17 / 5 evaluates to 3 in C++! Both operands are integers Integer division is performed! 17.0 / 5 equals 3.4 in C++! Highest-order operand is "double type" Double "precision" division is performed! int intvar1 =1, intvar2=2, result; result = intvar1 / intvar2; Performs integer division! Result: 0! ch 1-28

Individual Arithmetic Precision Calculations done "one-by-one" 1 / 2 / 3.0 / 4 performs 3 separate divisions. First 1 / 2 equals 0 Then 0 / 3.0 equals 0.0 Then 0.0 / 4 equals 0.0! So not necessarily sufficient to change just "one operand" in a large expression Must keep in mind all individual calculations that will be performed during evaluation! ch 1-29

Type Casting Casting for Variables Can add ".0" to literals to force precision arithmetic, but what about variables? We can t use "myint.0"! static_cast<double>intvar Explicitly "casts" or "converts" intvar to double type Result of conversion is then used Example expression: doublevar = static_cast<double>intvar1 / intvar2; Casting forces double-precision division to take place among two integer variables! ch 1-30

Two types Type Casting Implicit also called "Automatic" Done FOR you, automatically 17 / 5.5 This expression causes an "implicit type cast" to take place, casting the 17 17.0 Explicit type conversion Programmer specifies conversion with cast operator (double)17 / 5.5 Same expression as above, using explicit cast (double)myint / mydouble More typical use; cast operator on variable ch 1-31

Console Input/Output I/O objects cin, cout, cerr Defined in the C++ library called <iostream> Must have these lines (called pre-processor directives) near start of file: #include <iostream> using namespace std; Tells C++ to use appropriate library so we can use the I/O objects cin, cout, cerr ch 1-32

Console Output What can be outputted? Any data can be outputted to display screen Variables Constants Literals Expressions (which can include all of above) cout << numberofgames << "games played."; 2 values are outputted: - "value" of variable numberofgames, - literal string " games played." Cascading: multiple values in one cout ch 1-33

Separating Lines of Output New lines in output Recall: "\ n" is escape sequence for the char "newline" A second method: object endl Examples: cout << "Hello World\ n"; Sends string "Hello World" to display, & escape sequence "\ n", skipping to next line cout << "Hello World" << endl; Same result as above ch 1-34

Formatting Output Formatting numeric values for output Values may not display as you d expect! cout << "The price is $" << price << endl; If price (declared double) has value 78.5, you might get: The price is $78.500000 or: The price is $78.5 We must explicitly tell C++ how to output numbers in our programs! ch 1-35

Formatting Numbers "Magic Formula" to force decimal sizes: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); These stmts force all future cout ed values: To have exactly two digits after the decimal place Example: cout << "The price is $" << price << endl; Now results in the following: The price is $78.50 Can modify precision "as you go" as well! ch 1-36

cout formatting /** * SimpleTest.cpp * - Testing cout formatting */ #include <iostream> #include <iomanip> using namespace std; #define NUM_DATA 5 #define NUM_WIDTH 15 #define NUM_PRECISION 5 void main() { double dd[num_data] = {0.01, 123.45, 23456, 0.00123, 9876543210.12}; cout << endl; cout << " Double data output without formatting:" << endl; for (int i=0; i<num_data; i++) { cout <<" "; cout << dd[i] << endl; } cout << endl; ch 1-37

cout << " Double data output with formatting (cout.width(15); cout.precision(5)" << endl; for (int i=0; i<num_data; i++) { cout <<" "; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.width(15); cout.precision(5); cout << dd[i] << endl; } cout << endl; cout << " Double data output with formatting (cout.width(8); cout.precision(2)" << endl; for (int i=0; i<num_data; i++) { cout <<" "; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.width(8); cout.precision(2); cout << dd[i] << endl; } } cout << endl; ch 1-38

Output Result ch 1-39

Output with cerr cerr works same as cout Error Output Provides mechanism for distinguishing between regular output and error output Re-direct output streams Most systems allow cout and cerr to be "redirected" to other devices e.g., line printer, output file, error console, etc. ch 1-40

Input Using cin cin for input, cout for output Differences: ">>" (extraction operator) points opposite Think of it as "pointing toward where the data goes" Object name "cin" used instead of "cout" No literals allowed for cin Must input "to a variable" cin >> num; Waits on-screen for keyboard entry Value entered at keyboard is "assigned" to num ch 1-41

Prompting for Input: cin and cout Always "prompt" user for input cout << "Enter number of dragons: "; cin >> numofdragons; Note: no "\ n" in cout. Prompt "waits" on same line for keyboard input as follows: Enter number of dragons: Underscore above denotes where keyboard entry is made Every cin should have cout prompt Maximizes user-friendly input/output ch 1-42

Bottom-line: Program Style Make programs easy to read and modify the other programmer (who may update your source code) must easily understand your code Comments, two methods: // Two slashes indicate entire line is to be ignored /*Delimiters indicates everything between is ignored*/ Both methods commonly used Identifier naming ALL_CAPS for constants: e.g., MAX_NUM lowertoupper for variables Most important: MEANINGFUL NAMES! ch 1-43

Libraries C++ Standard Libraries #include <Library_Name> Directive to "add" contents of library file to your program Called "preprocessor directive" Executes before compiler, and simply "copies" library file into your program file C++ has many libraries Input/output, math, strings, etc. ch 1-44

Namespaces Namespaces defined: Collection of name definitions For now: interested in namespace "std" Has all standard library definitions we need Examples: #include <iostream> using namespace std; Includes entire standard library of name definitions #include <iostream> using std::cin; using std::cout; Can specify just the objects we want ch 1-45

Debugging Logical Error even though the program has been compiled and executed without error message, the program does not produce correct result the algorithm may be not correct the sequence of processing may be not correct Debugging logical errors printout the status of each statement during execution very difficult to check every variables at each statement some times, the (delayed) printout misleads the correct status of program execution check the status of each variables during program execution debugger is necessary more efficient ch 1-46

Debugger ch 2-47

Debugging in Microsoft Visual C++ (1) ch 2-48

Debugging in Microsoft Visual C++ (2) ch 2-49

Debugging in Microsoft Visual C++ (3) Commands in Visual C++ Debugger F5 (Go): execute program F10 (Trace with Step Over): execute each statement one-by-one (function call is treated as a statement) F11 (Trace with Step Into): execute each statement one-by-one (execute each statement in the called function, one-by-one) F9 (Breakpoint): set breakpoint at current statement ch 1-50

Homework 1 1.1 Calculations of simple statistics. 1) Write an algorithm in pseudo code that randomly generates 100 integer data, and calculates the sum, average, and standard deviation of the given data. 2) Write a C++ program according to the pseudo code. 1.2 Programming project 1-11. (p. 70) Convert the integer data of time length (in seconds) into hour, minutes, and seconds. Write an algorithm in pseudo code Write a C++ program that inputs an integer that represents a length of time in seconds. The program should then output the number of hours, minutes, and seconds that corresponds to that number of seconds. ch 1-51