* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Introduction To C++
Survey
Document related concepts
Transcript
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. 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.” What 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: Why 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 HP Airport Computer chip manufacturers like Motorola & Intel Software companies Banks Hong Kong Government Hospital Authority Telecommunications Universities What Can We Do By the End of the Course? Program the computer in applications such as the following: Program a simple calculator Program simple computer games Program a small inventory system for a small company Programming and Problem Solving Algorithm ◦ A sequence of precise instructions which leads to a solution Program ◦ An algorithm expressed in a language the computer can understand Software Life Cycle 1. Analysis and specification of the task (problem definition) 2. Design of the software (object and algorithm design) 3. Implementation (coding) 4. Maintenance and evolution of the system 5. Obsolescence Questions Can you… ◦ Describe 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 target to 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 data running the programs against the sample input comparing the program output to the known output in 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. 1.4 Testing and Debugging Bug ◦ A mistake in a program Debugging ◦ Eliminating mistakes in programs ◦ Term used when a moth caused a failed relay on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.” Program Errors Syntax errors ◦ Violation of the grammar rules of the language ◦ Discovered by the compiler Error messages may not always show correct location of errors Run-time errors ◦ Error conditions detected by the computer at runtime Logic errors ◦ Errors in the program’s algorithm ◦ Most difficult to diagnose ◦ Computer does not recognize an error Questions Can you… ◦ Describe 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 Process Define 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. Algorithms Sequential 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 Algorithm Stir into a large mixing bowl 2 eggs 4cups of water Cake mix Once all the lumps are gone Preheat oven to 400 degrees Place cake mix in a 4X7 greased cake pan Bake for 35 minutes Cool 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 equivalent Pseudocode) to compute the interest on a loan is shown below: Example Problem Statement ◦ Given a collection of nickels (US 5-cent coins) and pennies (US 1cent coins), find the equivalent number of Hong Kong dollars Problem 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 Algorithm 1. 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 Algorithm 1. Read 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. Flowchart Pseudocode Read NAME, BALANCE, RATE Compute INTEREST as BALANCE x RATE Write (Display) NAME and INTEREST Read X,Y, Z Compute Sum (S) as X + Y + Z Compute Average (A) as S / 3 Compute Product (P) as X x Y x Z Write (Display) the Sum, Average and Product The example below shows the flowchart for a program that reads two numbers and displays the numbers read in decreasing order Read A, B If A is less than B BIG = B SMALL = A else BIG = A SMALL = B Write (Display) BIG, SMALL General form of a C++ program // Program description #include directives int main(){ constant declarations variable declarations executable statements return 0; } Declarations Constants 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: 1. Reserves a memory location in which to store the value of the constant or variable. 2. 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. Variable declarations 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 declarations A 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 declaration int 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. Character data A 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 declarations Constants are used to store values that never change during the program execution. Using constants makes programs more readable and maintainable. Syntax: const <type> <identifier> = <expression>; 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: Standard Data Types void int char float bool 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)<= sizeof(int)<= sizeof(long int) Short int int long int Integer The type also defines the size of the field in which data can be stored. In C++, even though the size is machine dependent, most PCs use the integer sizes shown below. Type Sign Byte N. of Min Value Max Value Size Bits short int Signed 2 unsigned int long int 16 -32768 0 32767 65535 Signed 4 unsigned 32 -2,147,483,648 2,147,483,647 Signed 4 unsigned 32 0 -2,147,483,648 4,294,967,295 2,147,483,647 4,294,967,295 0 Floating Point A floating-point type is a number with a fractional part, such as 43.32. The C++ language supports three different sizes of floating-point: float, double and long double. sizeof(float)<= sizeof(double)<= sizeof(long double) float double long double Floating Point Although the physical size of floating-point types is machine dependent, many computers support the sizes shown below. type Byte size Number of Bits float 4 32 double 8 64 10 80 long double More Data Types bool ◦ 8 bits ◦ either trueor false string ◦ Class type ◦ Defined in double quotes ◦ Must include the <string> library Identifier Names (i.e., Symbols) Variables, functions, structures, classes, etc. Prules ◦ Are case sensitive ◦ Must begin with a letter, which includes an nderscore (_) ◦ 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++ keywords Keywords 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, while Variables Name a region of memory where data is stored Must be defined before use: includes data type and name Names are case sensitive Examples (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‘; Assignment Literal Values someInt= 27; someDub= 33.33; Expressions someInt= 27+ 23; someDub= 5.55 * 1.0; Values of other Variables someInt= someOtherInt; someDub= someOtherDub; someInt= someInt2 + someInt3; someDub= someDub2 / someDub3; Multiple Assignment and Combined Assignment =is an operator that can be used > 1 time in an expression: x = y = z = 5; Value of =is the value that is assigned Associates right to left: x = (y = (z = 5)); Comments ◦ Single line Comments// ‐single line comment // Name: Brad Rippe // File:Assignment23.cpp // Date:1/21/07 ◦ Multiple line Comments/* … */ /* Name: Brad Rippe File:Assignment23.cpp Date:1/21/07 */ Rules for Division C++ treats integers differently from decimal numbers. 100 is an int type. 100.0 , 100.0000, and 100. are double type. The general rule for division of int and double types is: ◦ ◦ ◦ ◦ double/double -> double (normal) double/int -> double (normal) int/double -> double (normal) int/int -> int (note: the decimal part is discarded) Rules for Division Examples: ◦ ◦ ◦ ◦ 220. / 100.0 220. / 100 220 / 100.0 220 / 100 double/double -> double result double/int -> double int/double -> double int/int -> int is 2.2 result is 2.2 result is 2.2 result 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 Conversions A 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 2 yy = j; // yy is now 10.0 Assignment Conversions Example 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 Conversions Example 2: int m, n; double xx; m = 7; n = 2.5; // 2.5 converted to 2 and assigned to n xx = m/n; // 7/2=3 converted to 3.0 and assigned to xx n = 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 int Forcing a Type Change You 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.0 double result2 = double(x)/y; // result2 is 0.5 double result3 = x/double(y); // result3 is 0.5 double result4 = double(x)/double(y);// result4 is 0.5 double result5 = double(x/y); // result5 is 0.0 int cents = int(result4*100); // cents is 50 Standard Input/Output cin - 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/Output cout - the standard output stream Output operator “<<” ◦ Inserts data into the output “stream” (the screen by default). ◦ Example: int id, score; cout << "Enter student ID and score: "; cin >> id >> score; cout << "Student ID: " << id << " score: “ << score << endl; Standard Input/Output Some special output characters: \t \n tab new line Format Manipulation #include <iomanip> setw(int size) Specifies the number of characters to use in displaying the next value, which is right-justified. Ex: cout << setw(5) << 12; //output 3 spaces and then 12 setprecision(int digit) Specifies the number of significant digits for all subsequent output. cout << fixed << setprecision(2); the precision is: two digits after the decimal point. Fixed: uses fixed-point notation in the float field // Demonstrate the features of output format manipulators // Input: cost of lunch, number of people attending lunch // Output: lunch cost per person #include <iomanip> // Use IO manipulators #include <iostream> using namespace std; int main() { double cost_of_lunch, cost_per_person; int number_of_people; cout << "Press return after entering a number.\n"; cout << "Enter the cost of lunch:\n"; cin >> cost_of_lunch; cout << "Enter the number of people attending lunch:\n"; cin >> number_of_people; cost_per_person = cost_of_lunch / number_of_people; //cout << setiosflags(ios::fixed) << setprecision(2); cout << "If the lunch cost $"; cout << cost_of_lunch; cout << ", and you have " << number_of_people << " persons attending, then \n"; cout << "the cost per person is $" << cost_per_person << ".\n"; /* cout << "the cost per person is $"; cout << setprecision(4) << cost_per_person << ".\n"; */ return 0; } Output of example program: Press return after entering a number. Enter the cost of lunch: 800.75 Enter the number of people attending lunch: 9 If the lunch cost $800.75, and you have 9 attending, then the cost is $88.9722. Using setprecision(4) in the last cout statement can change the final result to $88.97. Operators Operators Operator Examples Auto increment and decrement Target must be a variable (i.e., an l-value) int i, j =10; i = j++; /* i is 10, j is 11 */ i = ++j; /* i is 11, j is 11 */ i = j--; /* i is 10, j is 9 */ i = --j; /* i is 9, j is 9 */ i++, ++i, i--, and --i are legal (i.e., assignment is not required) < May be embedded in expressions < Often used in array indexes Multiple assignment (i.e., the = operator returns a value) < i = j = k = 0; /* equivalent to i = (j = (k = 0)) */ Operator Examples P?: < a ? b : c; /* if a is true, then b, else c; a is usually in parens */ < int max = (x > y) ? x : y; Pop= (+=, -=, *=, /=, %=, ~=, <<=, >>=) < variable op= expression; ø variable = variable op expression; < x += 10; ø x = x + 10; < i -= 2; ø i = i - 2; < a /= b; ø a = a / b; < index %= size; ø index = index % size; < mask <<= 2; ø mask = mask << 2; Arithmetic Operators Can be used for literal values and variables (in order of precedence) ◦ ◦ ◦ ◦ ◦ ◦ Parentheses( ) Multiplication * Division / Modulus% Addition + Subtraction – Operators and Precedence Which of the following is equivalent to mx + b ? ◦ (m * x) + b ◦ m * (x + b) Operator precedence tells the order in which different operators in an expression are evaluated. Standard precedence order ◦ ( ) ◦ * / % ◦ + - Evaluated first, if nested then evaluate the innermost first. Evaluated second. If there are several, then evaluate from left-to-right. Evaluate third. If there are several, then evaluate from left-to-right. 76 Relational Operators Relational operators are used to compare two values to form a condition. Math C++ Plain English = == equals [example: if(a==b) ] [ (a=b) means put the value of b into a ] < > < <= > >= != less than less than or equal to greater than greater than or equal to not equal to 77 Operator Precedence Which comes first? Answer: * < / + <= == % >= != > = 78 Operator Precedence If you were a computer, what would you give as a result for: y = 2 * 5 * 5 + 3 * 5 + 7; Programming Style C++ is a free-format language, which means that: Extra blanks (spaces) or tabs before or after identifiers/operators are ignored. Blank lines are ignored by the compiler just like comments. Code can be indented in any way. There can be more than one statement on a single line. A single statement can continue over several lines. Programming Style (cont. ) In order to improve the readability of your program, use the following conventions: Start the program with a header that tells what the program does. Use meaningful variable names. Document each variable declaration with a comment telling what the variable is used for. Place each executable statement on a single line. A segment of code is a sequence of executable statements that belong together. ◦ Use blank lines to separate different segments of code. ◦ Document each segment of code with a comment telling what the segment does. Example 0 – adding 2 numbers Ali: Hey Mohamed, I just learned how to add two numbers together. Mohamed : Cool! Ali : Give me the first number. Mohamed : 2. Ali : Ok, and give me the second number. Mohamed : 5. Ali : Ok, here's the answer: 2 + 5 = 7. Mohamed : Wow! You are amazing! after Mohamed says “2”, Ali has to keep this number in his mind. after Mohamed says “5”, Ali also needs to keep this number in his mind. First number: 2 Second number: 5 Sum: 7 The Corresponding C++ Program #include <iostream> using namespace std; int main() { int first, second, sum; cout << " Ali : Hey Mohamed, I just learned how to add” << “ two numbers together."<< endl; cout << " Mohamed : Cool!" <<endl; cout << " Ali : Give me the first number."<< endl; cout << " Mohamed : "; cin >> first; cout << " Ali : Give me the second number."<< endl; cout << " Mohamed : "; cin >> second; sum = first + second; cout << " Ali : OK, here is the answer:"; cout << sum << endl; cout << " Mohamed : Wow! You are amazing!" << endl; return 0; } Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius. Input(s) fahrenheit integer Output(s) celsius double OR float Additional Notes: *Remark (General information about “float” and “double”): • Both can be used for real numbers. • The difference between double and float is their ranges. • For memory efficiency, you should check their ranges and decide which one to use for a variable. Note that memory efficiency is not considered in our examples. Therefore, double is used in general. *Research Task: Learn the ranges of float and double. Relevant Formula celsius=(5/9)*(fahrenheit – 32) #include <iostream.h> int main() { int fahrenheit; double celsius; cout<<"Please enter a temperature in degrees Fahrenheit :“; cin>>fahrenheit ; celsius= (5.0 / 9.0) * (fahrenheit - 32); cout<<"The temperature in degrees Celsius is\n“<< celsius; return 0; } Write a program that estimates the temperature in a freezer (in Celsius) given the elapsed time (hours) since a power failure. Assume this temperature (T) is given by where t is the time since the power failure. Your program should prompt the user to enter how long it has been since the start of the power failure in whole hours and minutes. Note that you will need to convert the elapsed time into hours. For example, if the user entered 2 30 (2 hours 30 minutes), you would need to convert this to 2.5 hours. Input(s) hours minutes integer integer Output(s) temperature double Relevant Formula temperature=(4*time*time)/(time+2)-20 time=hours+minutes/60 #include <iostream.h> int main() { int hours; int minutes; double time; double temperature; cout<<"Please enter the time : “; cin>>hours>>minutes ; time = hours + (double) minutes / 60; temperature = ( 4 * time * time) / (time + 2) - 20; cout<<"The temperature in freezer is \n“<< temperature; return 0; } What makes a bad program? Writing Code without detailed analysis and design Repeating trial and error without understanding the problem Debugging the program line by line, statement by statement Writing tricky and dirty programs