introduction to programming using c++

94
Introduction to programming using C++ Dr. Mohamed Khafagy

Upload: melissa-cole

Post on 01-Jan-2016

49 views

Category:

Documents


2 download

DESCRIPTION

Introduction to programming using C++. Dr. Mohamed Khafagy. Introduction to C++. C is a programming language developed in the 1970's alongside the UNIX operating system. - PowerPoint PPT Presentation

TRANSCRIPT

Introduction to Data mining

Introduction to programming using C++Dr. Mohamed KhafagyIntroduction to C++ C is a programming language developed in the 1970's alongside the UNIX operating system. C provides a comprehensive set of features for handling a wide variety of applications, such as systems development and scientific computation. C++ is an extension of the C language, in that most C programs are also C++ programs. C++, as opposed to C, supports object-oriented programming.2What is C++? C++ is a programming language. A computer program performs a specific task, and may interact with the user and the computer hardware.Human work model:

Computer work model:WorkComputerProductProgramWorkWorkerProductInstructions

3Why C++?Bad News:C++ is not easy to learn

Good News:Lots of good-paying jobs for programmers because C++ is not easy to learn!Java uses C++ syntax, it is easy to learn Java if you know C++.Though C++ is not the easiest language (Basic and Pascal are easier), it is not the hardest either (Ada, Prolog and Assembly languages are really difficult!)

Who Uses C++? Computer makers such as Sun, SGI, IBM, and HPAirport Computer chip manufacturers like Motorola & IntelSoftware companiesBanksHong Kong GovernmentHospital AuthorityTelecommunicationsUniversities

5What Can We Do By the End of the Course?Program the computer in applications such as the following:Program a simple calculatorProgram simple computer gamesProgram a small inventory system for a small company

Programming and Problem Solving AlgorithmA sequence of precise instructions which leads to a solution

ProgramAn algorithm expressed in a language the computer can understandSoftware Life CycleAnalysis and specification of the task (problem definition)Design of the software (object and algorithm design)Implementation (coding)Maintenance and evolution of the systemObsolescenceQuestionsCan youDescribe the first step to take when creating a program?

List the two main phases of the program design process?

Explain the importance of the problem-solving phase?

List the steps in the software life cycle?Specification of a problem A precise statement/description of the problem. It involves describing the input, the expected output, and the relationship between the input and output. This is often done through preconditions and postconditions. Design Formulation of a method, that is, of a sequence of steps, to solve the problem. The design language can be pseudo-code, flowcharts, natural language, any combinations of those, etc. A design so expressed is called an algorithm(s). A good design approach is a top-down design where the problem is decomposed into smaller, simpler pieces, where each piece is designed into a module. Implementation Development of actual C++ code that will carry out the design and solve the problem. The design and implementation of data structures, abstract data types, and classes, are often a major part of design implementation.Analysis of the Solution Estimation of how much time and memory an algorithm takes. The purpose is twofold: to get a ballpark figure of the speed and memory requirements to see if they meet the targetto compare competing designs and thus choose the best before any further investment in the application (implementation, testing, etc.)Testing and Debugging Testing a program for syntactical correctness (no compiler errors)Testing a program for semantic correctness, that is, checking if the program gives the correct output. This is done by having sample input data and corresponding, known output datarunning the programs against the sample inputcomparing the program output to the known outputin case there is no match, modify the code to achieve a perfect match. One important tip for thorough testing: Fully exercise the code, that is, make sure each line of your code is executed.Maintenance and Evolution of a System Ongoing, on-the-job modifications and updates of the programs. Testing and DebuggingBugA mistake in a programDebuggingEliminating mistakes in programsTerm used when a moth caused a failed relayon the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: First actual case of a bug being found.1.4Program ErrorsSyntax errorsViolation of the grammar rules of the languageDiscovered by the compilerError messages may not always show correct location of errorsRun-time errorsError conditions detected by the computer at run-timeLogic errorsErrors in the programs algorithmMost difficult to diagnoseComputer does not recognize an errorQuestionsCan youDescribe the three kinds of program errors?

Tell what kind of errors the compiler catches?

What kind of error is produced if you forget a punctuation symbol such as a semi-colon?

Tell what type of error is produced when a program runs but produces incorrect results?

Programming as a Problem Solving ProcessDefine and analyze the problem. What is the input & output? What other information is necessary?Develop an algorithm. What steps must be done?Implement a program. Compile, test, and debug the program. Document and maintain the program.

AlgorithmsSequential steps for solving a problem or task

Language independent

Written in plain English

Allows programmers to concentrate on the solution without worrying about the implementation details

Cake AlgorithmStir into a large mixing bowl2 eggs4cups of waterCake mixOnce all the lumps are gonePreheat oven to 400 degreesPlace cake mix in a 4X7 greased cake panBake for 35 minutesCool for 15 minutes and serve

Simple Sort Algorithm 1.Get a list of unsorted numbers

2.Repeat steps 3 through 6 until the unsorted list is empty

3.Compare the unsorted numbers

4.Select the smallest unsorted number

5.Move this number to the sorted list

6.Remove the selected smallest number from the unsorted list

7.Stop

Simple Sort Algorithm

There are two commonly used tools to help to document program logic (the algorithm). These are flowcharts and Pseudocode.in flowcharts are shown below:

With flowcharting, essential steps of an algorithm are shown using the shapes above. The flow of data between steps is indicated by arrows, or flowlines. For example, a flowchart (and equivalentPseudocode) to compute the interest on a loan is shown below:Flowchart

PseudocodeRead NAME, BALANCE, RATECompute INTEREST as BALANCE x RATEWrite (Display) NAME and INTEREST

Read X, Y, ZCompute Sum (S) as X + Y + ZCompute Average (A) as S / 3Compute Product (P) as X x Y x ZWrite (Display) the Sum, Average and ProductThe example below shows the flowchart for a program that reads two numbers and displays the numbers read in decreasing order

Read A, BIf A is less than BBIG = BSMALL = AelseBIG = ASMALL = BWrite (Display) BIG, SMALLExample Problem Statement Given a collection of nickels (US 5-cent coins) and pennies (US 1-cent coins), find the equivalent number of Hong Kong dollarsProblem Analysis Input: nickels (integer) - number of US nickels pennies (integer) - number of US pennies Output: dollars (integer) - number of HK dollar coins to return

Example: Initial Algorithm1. Read in the numbers of nickels and pennies. 2. Compute the total value in US dollars. 3. Compute the corresponding total value in HK dollars. 4. Find the number of HK dollar coins

5. Display the number of HK dollar coins

Example: Refined AlgorithmRead in the number of nickels and pennies and US2HK . 2. Compute the total value in US dollars.2.1 total_USD = (5 * nickel + penny)/100 3. Compute the corresponding total in HK dollars.3.1. total_HKD = total_USD * US2HK 4. Find the number of HK dollar coins.4.1. total_HK_cent = total_HKD * 100 4.2. dollar = total_HK_cent / 100 5. Display the number of HK dollar.

General form of a C++ program// Program description #include directives int main(){ constant declarations variable declarations executable statements return 0; } DeclarationsConstants and variables must be declared before they can be used.A constant declaration specifies the type, the name and the value of the constant.A variable declaration specifies the type, the name and possibly the initial value of the variable.When you declare a constant or a variable, the compiler:Reserves a memory location in which to store the value of the constant or variable.Associates the name of the constant or variable with the memory location. (You will use this name for referring to the constant or variable.)For more on declarations, see www.courseware.ust.hk and choose English--> C++ --> Declarations.Identifier Names (i.e., Symbols)

Variables, functions, structures, classes, etc.Prules Are case sensitive Must begin with a letter, which includes an underscore (_) Subsequent characters may be letters, digits, and underscores Cannot be a keyword May only be defined once in a scope Should avoid library names Must be declared before use

C++ keywordsKeywords appear in blue in Visual C++. Each keyword has a predefined purpose in the language. Do not use keywords as variable and constant names!!The complete list of keywords is on page 673 of the textbook.We shall cover the following keywords in this class: bool, break, case, char, const, continue, do, default, double, else, extern, false, float, for, if, int, long, namespace, return, short, static, struct, switch, typedef, true, unsigned, void, while43VariablesName a region of memory where data is storedMust be defined before use: includes data type and nameNames are case sensitiveExamples (definition and initialization)int dollars;int quarters, dimes, nickels, pennies;int money = 217;double x, pi = 3.14159;char begin = 'A', end = 'Z', newLine = '\n;Variables are used to store values that can be changed during the program execution. A variable is best thought of as a container for a value. 3445 y Syntax: < type >< identifier >;< type >< identifier >=< expression >; Examples: int sum;int total = 3445;char answer = 'y';double temperature = -3.14;Variable declarationsA variable has a type and it can contain only values of that type. For example, a variable of the type int can only hold integer values. Variables are not automatically initialized. For example, after declarationint sum;the value of the variable sum can be anything (garbage).Thus, it is good practice to initialize variables when they are declared. Once a value has been placed in a variable it stays there until the program deliberately alters it. Variable declarationsCharacter dataA variable or a constant of char type can hold an ASCII character

When initializing a constant or a variable of char type, or when changing the value of a variable of char type, the value is enclosed in single quotation marks. Examples: const char star = '*'; char letter, one = '1'; Constant declarationsConstants are used to store values that never change during the program execution. Using constants makes programs more readable and maintainable. Syntax: const = ; Examples: const double US2HK = 7.8; //Exchange rate of US$ to HK$ const double HK2TW = 3.98; //Exchange rate of HK$ to TW$ const double US2TW = US2HK * HK2TW; //Exchange rate of US$ to TW$ C++ Data Type A type defines a set of values and a set of operations that can be applied on those values. The set of values for each type is known as the domain for the type.

C++ contains 5 standard types:

void The void type has no values and no operations. In other words, both the set of values and the set of operations are empty. Although this might seem unusual, we will see later that it is a very useful data type.

Integer An integer type is a number without a fractional part. It is also known as an integral number. C++ supports three different sizes of the integer data type: short int, int and long int. sizeof(short int) double (normal)int/int -> int (note: the decimal part is discarded)59Rules for DivisionExamples:220. / 100.0 double/double -> doubleresult is 2.2220. / 100 double/int -> doubleresult is 2.2220 / 100.0 int/double -> doubleresult is 2.2220 / 100 int/int -> intresult is 2

Summary: division is normal unless both the numerator and denominator are int, then the result is an int (the decimal part is discarded).Assignment ConversionsA decimal number assigned to an int type variable is truncated.An integer assigned to a double type variable is converted to a decimal number.Example 1:double yy = 2.7;int i = 15;int j = 10;i = yy; // i is now 2yy = j; // yy is now 10.0Assignment ConversionsExample 2:int m, n;double xx;m = 7;n = 2.5;xx = m / n;n = xx + m / 2;// What is the value of n?Assignment ConversionsExample 2:int m, n;double xx;m = 7;n = 2.5; // 2.5 converted to 2 and assigned to nxx = m/n; // 7/2=3 converted to 3.0 and assigned to xxn = xx+m/2;// m/2=3 : integer division// xx+m/2 : double addition because xx is double// convert result of m/2 to double (i.e. 3.0)// xx+m/2=6.0// convert result of xx+m/2 to int (i.e. 6)//because n is intForcing a Type ChangeYou can change the type of an expression with a cast operation.Syntax:variable1 = type(variable2);variable1 = type(expression);Example:int x=1, y=2;double result1 = x/y;// result1 is 0.0double result2 = double(x)/y;// result2 is 0.5double result3 = x/double(y);// result3 is 0.5double result4 = double(x)/double(y);// result4 is 0.5double result5 = double(x/y);// result5 is 0.0int cents = int(result4*100); // cents is 50Standard Input/Outputcin - the standard input stream

Input operator >>Extracts data from input stream (the keyboard by default).Skips over white spaces.Extracts only characters of the right form and performs automatic conversion to the type specified.

Standard Input/Outputcout - the standard output streamOutput operator > score;cout >fahrenheit ; celsius= (5.0 / 9.0) * (fahrenheit - 32);cout>hours>>minutes ;time = hours + (double) minutes / 60;temperature = ( 4 * time * time) / (time + 2) - 20;cout