C++ 프로그래밍 Introduction to this class & C++

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 1 C++ Basics. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 1-2 Learning Objectives Introduction to C++ Origins, Object-Oriented.
CS 6301 Lecture 2: First Program1. CS Topics of this lecture Introduce first program  Explore inputs and outputs of a program Arithmetic using.
Introduction Kingdom of Saudi Arabia Shaqra University
Three types of computer languages
 2003 Prentice Hall, Inc. All rights reserved. 1 Machine Languages, Assembly Languages, and High-level Languages Three types of computer languages 1.Machine.
CSC 200 Lecture 2 Matt Kayala 1/25/06. Lecture Objectives More detailed intro to C++ Variables, Expressions, and Assignment Statements Console Input/Output.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Basic Elements of C++ Chapter 2.
Copyright 2003 Scott/Jones Publishing Brief Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
Chapter 01: Introduction to Computer Programming
COMPUTER SCIENCE I C++ INTRODUCTION
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Input, Output, and Processing
Week 1 Algorithmization and Programming Languages.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
COMPUTER PROGRAMMING. A Typical C++ Environment Phases of C++ Programs: 1- Edit 2- Preprocess 3- Compile 4- Link 5- Load 6- Execute Loader Primary Memory.
Chapter 1 C++ Basics Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Slide 1. Slide 2 Chapter 1 C++ Basics Slide 3 Learning Objectives  Introduction to C++  Origins, Object-Oriented Programming, Terms  Variables, Expressions,
Today’s Lecture  Literal  Constant  Precedence rules  More assignment rules  Program Style.
CHAPTER 1: INTRODUCTION C++ Programming. CS 241 Course URL: Text Book: C++ How to Program, DETITEL & DEITEL, eighth Edition.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Chapter 1 C++ Basics Copyright © 2016 Pearson, Inc. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
C++ Primer I CMSC 202. Topics Covered Our first “Hello world” program Basic program structure main() Variables, identifiers, types Expressions, statements.
COMP 2710 Software Construction C++ Basics 2 and Exercises Dr. Xiao Qin Auburn University These slides.
Bill Tucker Austin Community College COSC 1315
FAQ: Exit Vi Using :q Can NOT exit with “:q” if you have not use “:w” to write changes.
Today Variable declaration Mathematical Operators Input and Output Lab
Chapter 1 C++ Basics Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Basic Elements of C++
C++ Basic Input and Output (I/O)
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
Chapter 1.2 Introduction to C++ Programming
Basics (Variables, Assignments, I/O)
Chapter 1: Introduction to computers and C++ Programming
Introduction to C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
COMP 2710 Software Construction Midterm Exam 1 - Review
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Programmer-Defined Functions Dr.
Completing the Problem-Solving Process
Introduction to C++ Systems Programming.
Basic Elements of C++.
Revision Lecture
Lecture 2-3 C++ Basic Constructs
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Basics (Variables, Assignments, I/O)
Introduction to C++ Programming
1.13 The Key Software Trend: Object Technology
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Topics Designing a Program Input, Processing, and Output
Programs written in C and C++ can run on many different computers
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Topics Designing a Program Input, Processing, and Output
Capitolo 1 – Introduction C++ Programming
The C Language: Intro.
C++ Programming Basics
C++ for Engineers and Scientists Second Edition
Introduction to C Programming
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

C++ 프로그래밍 Introduction to this class & C++ 1/9/2018 C++ 프로그래밍 Introduction to this class & C++ Howon Kim 2008.3.4

About this course… Course name : C++ Programming (CP24106) Objective of this class: Obtaining the basic ideas of object‑oriented programming Understanding C++ as a tool for problem solving Exercising computer programming to a practical level Understanding the basic concepts of software engineering Understanding the basic concepts of data structures

About this course… About me… Current Major Interests Howon Kim, Ph.D. from POSTECH, Feb. 1999 Joined to PNU from this semester Email: howonkim@gmail.com Phone: 051-510-1010, 010-8540-6336 Current Major Interests Public Key Cryptography (especially, ECC and Pairing) Low power consumed cryptographic techniques (RFID security, sensor network security) Sensor network security issues (TinyOS security, secure routing etc.) Cryptanalysis (with side channel attack) Teaching the CP24106 class !

About this course… Prerequisite class Textbook References Class time C Programming (미수강 전문과정 학생  선수과목 test 필요) Textbook Walter Savitch, Absolute C++, 3rd Ed., Addison Wesley, 2008 References Bjarne Stroustrup, The C++ Programming Languages, 3rd Ed., Addison Wesley Liang, Introduction to C++, Prentice Hall, 2007 Class time Tuesday, Thursday, 13:00 ~ 14:00

About this course… Detailed schedule on this class 범위 학습내용 주 C++ Basics 1 CH 2 Flow of Control 2 CH 3 Function Basics 3 CH 4 Parameters and Overloading 4 CH 5 Arrays 5 CH 6 Structures and Classes 6 CH 7 Constructors and Other Tools 7 Midterm Exam 8 CH 8 Operator Overloading , Friends, and Refrences 9 CH 12 Stream Input and Output 10 CH 14 Inheritance and OOP 11 CH 16 Templates CH 18 Exception Handling CH 19 STL(Standard Template Library) 14 Final Exam 15 Term project 수행

About this course… Assessment 점 수 항 목 5 출 석 40 중간고사 기말고사 15 과제물 100 합 계

What Is C and What Is C++? The C language was developed originally by Bell Laboratories and standardized by the American National Standards Institute (ANSI) in 1989. In 1990 the International Standards Organization (ISO) adopted the ANSI standard. C was expanded to include the ability to build object-oriented software, and hence named C++ in the mid 1990s. In short, C++ contains all of the C language features and more!

A Brief History of C and C++ In the early 1970s at the Bell Laboratories, C was used originally as a programming language for operating systems, including Bell Labs’ UNIX. For many years the C software supplied with the UNIX operating system was the standard. As C grew in popularity and computer hardware became more affordable, many versions of the C language were created. In 1982 an American National Standards Institute committee was formed to create the ANSI standard for the C language.

A Brief History of C and C++ This standard was adopted in 1989 and ensured that developers of C software used the same rules and procedures. In 1994 extensions and corrections to the ISO C standard were adopted. Extensions to the C language, providing an improved version of C as well as supporting object-oriented programming methodologies, were designed originally by Bjarne Stroustrup of AT&T Bell Labs. These extensions to the C language became known as the C++ language.

A Brief History of C and C++ In November 1997, after several drafts of the ISO C++ standards, the ANSI committee published the final draft of the language - making it an international standard.

How C Was Named To appreciate how C was named, one needs to examine the historical aspects of the language. C is the result of a development process that began in the early 1960s with ALGOL 60, then Cambridge’s CPL in 1963, Martin Richard’s BCPL in 1967, and Ken Thompson’s B language in 1970 at Bell Labs. Many of C’s principal concepts are based in BCPL, and these concepts influenced the B and C languages.

C/C++ Is a Compiled Language Create source code. Source code contains the actual lines of C or C++ statements that give the program direction. Compile the program. A compiler is a computer program that reads the source code, and if the code is “grammatically correct,” the compiler produces machine code The next build step uses a linker, which literally links, or hooks, the machine code and library code together and binds it into an executable file. A C++ program must be compiled and linked on its target machine because the C++ executable file “talks” to the processor directly. Note the changes that must be made.

Creating, Compiling, and Running Programs

Rules for Programmers Keep you cool (don’t get mad). Work when you are rested (don’t program when you are tired). KISS your software (keep it simple, sweetie). Give help/get help. Study and know the rules for the language (syntax).

Rules for Programmers Learn the development environment and tools (we’ll concentrate on Visual C++). Understand the problem you are trying to solve. Build and test your software in steps. Save early/save often (back up your computer programming files often).

Why Programmers Love C++ Extended set of data “containers” Numeric: both whole numbers and numbers with decimal precision Character: text values True/false data type bool in C++ Pointers and References Variables that “point” or “refer” to other variables

Why Programmers Love C++ Large number of operators Operators are symbols that perform certain actions in C++. The + symbol adds numbers, - subtracts. The * multiplies numbers. Basic decision and control structures enable a program to branch to different code statements or loop over statements. C++ uses functions. A function is a block of code that performs a task for the program.

Why Programmers Love C++ Functions allow the programmer to: organize code and separate tasks logically separate each piece of the program in its own function and place all the functions in a separate library keep the program size from becoming too large and unwieldy

Why Programmers Love C++ Integrated libraries provide useful functions and classes for mathematics, file input/output, text operations, and other tools. Standard Template Library which contains software utilities that are built and ready for use by the C++ programmer. The C++ language provides us many classes, and we can write our own classes as well.

Object-Oriented Programming - OOP In the old days, programs followed data flow, written line-by-line, and “flowed” from the top to the bottom step by step. This is called structured (or top-down) programming. In OOP, the program is based on real-world things (objects) - designed and built to model how these “real” things interact. A C++ program is not automatically object-oriented. For a program to be object-oriented, it must contain objects.

Introduction to C++ C++ Origins C++ Terminology 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 From these slides, I will use the materials form Pearson. Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 21

Display 1.1 A Sample C++ Program (1 of 2) 22

Display 1.1 A Sample C++ Program (2 of 2) 23

C++ Variables C++ Identifiers Variables 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

Data Types: Display 1.2 Simple Types (1 of 2)

Data Types: Display 1.2 Simple Types (2 of 2)

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"

Assigning Data: Shorthand Notations Display, page 14

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

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

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

Display 1.3 Some Escape Sequences (1 of 2)

Display 1.3 Some Escape Sequences (2 of 2)

Constants Naming your constants Use named constants instead Literal constants are "OK", but provide little meaning e.g., seeing 24 in a pgm, 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

Arithmetic Operators: Display 1.4 Named Constant (1 of 2) Standard Arithmetic Operators Precedence rules – standard rules

Arithmetic Operators: Display 1.4 Named Constant (2 of 2)

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

Arithmetic Precision 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; intVar1 / intVar2; Performs integer division! Result: 0!

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!

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!

Type Casting Two types 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

Shorthand Operators Increment & Decrement Operators Just short-hand notation Increment operator, ++ intVar++; is equivalent to intVar = intVar + 1; Decrement operator, -- intVar--; is equivalent to intVar = intVar – 1;

Shorthand Operators: Two Options Post-Increment intVar++ Uses current value of variable, THEN increments it Pre-Increment ++intVar Increments variable first, THEN uses new value "Use" is defined as whatever "context" variable is currently in No difference if "alone" in statement: intVar++; and ++intVar;  identical result

Post-Increment in Action Post-Increment in Expressions: int n = 2, valueProduced; valueProduced = 2 * (n++); cout << valueProduced << endl; cout << n << endl; This code segment produces the output: 4 3 Since post-increment was used

Pre-Increment in Action Now using Pre-increment: int n = 2, valueProduced; valueProduced = 2 * (++n); cout << valueProduced << endl; cout << n << endl; This code segment produces the output: 6 3 Because pre-increment was used

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

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

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

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!

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!

Error Output Output with cerr Re-direct output streams cerr works same as cout 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.

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

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

Program Style Bottom-line: Make programs easy to read and modify 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 lowerToUpper for variables Most important: MEANINGFUL NAMES!

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.

Namespaces Namespaces defined: For now: interested in namespace "std" 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

Summary 1 C++ is case-sensitive Use meaningful names For variables and constants Variables must be declared before use Should also be initialized Use care in numeric manipulation Precision, parentheses, order of operations #include C++ libraries as needed

Summary 2 Object cout Object cin Object cerr Used for console output Object cin Used for console input Object cerr Used for error messages Use comments to aid understanding of your program Do not overcomment

Q&A Thank you for your attention. Thank you. 59

Reference [1] Walter Savitch, Absolute C++, 3rd Ed., Addison Wesley, 2008 [2] Liang, Introduction to C++, Prentice Hall, 2007 [3] Barbara Johnston, C++ Programming Today, 2nd Ed., Prentice Hall, 2007