Similar presentations

3
Introduction to C++ 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.”

4
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:

5
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!)

7
What Can We Do By the End of the Course? Program the computer in applications such as the following: n Program a simple calculator n Program simple computer games n Program a small inventory system for a small company

8
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

9
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

10
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?

11
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.

12
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.

13
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.

14
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.)

15
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.

16
Maintenance and Evolution of a System Ongoing, on-the-job modifications and updates of the programs.

17
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.” 1.4

18
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 run- time Logic errors ◦ Errors in the program’s algorithm ◦ Most difficult to diagnose ◦ Computer does not recognize an error

19
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?

20
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.

21
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

22
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

23
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

24
Simple Sort Algorithm

25

26

27

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

29

30
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:

39
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

42
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 and choose English--> C++ --> Declarations.

43
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

44
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

46
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 y Syntax: ; = ; Examples: int sum; int total = 3445; char answer = ' y ' ; double temperature = -3.14; Variable declarations

47
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. Variable declarations

48
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';

50
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:

51
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.

52
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

53
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. TypeSignByte Size N. of Bits Min ValueMax Value short int Signed unsigned int Signed unsigned ,147,483, ,147,483,647 4,294,967,295 long int Signed unsigned ,147,483, ,147,483,647 4,294,967,295

54
Floating Point A floating-point type is a number with a fractional part, such as 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

55
Floating Point typeByte sizeNumber of Bits float 432 double 864 long double 1080 Although the physical size of floating-point types is machine dependent, many computers support the sizes shown below.

58
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));

61
Rules for Division Examples: ◦ 220. / double/double -> double result is 2.2 ◦ 220. / 100 double/int -> double result is 2.2 ◦ 220 / int/double -> double result is 2.2 ◦ 220 / 100 int/int -> int 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).

62
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

68
Standard Input/Output Some special output characters: \t tab \n new line

69
Format Manipulation #include 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

71
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: Enter the number of people attending lunch: 9 If the lunch cost $800.75, and you have 9 attending, then the cost is $ Using setprecision (4) in the last cout statement can change the final result to $88.97.

72
Operators

73
Operators

74
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)) */

77
76 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.

78
77 Relational Operators Relational operators are used to compare two values to form a condition. MathC++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

80
Operator Precedence If you were a computer, what would you give as a result for: y = 2 * 5 * * 5 + 7;

81
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.

82
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. Programming Style (cont. )

83
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: = 7. Mohamed : Wow! You are amazing! after Mohamed says “2”, Ali has to keep this number in his mind. 257 First number: Second number: Sum: after Mohamed says “5”, Ali also needs to keep this number in his mind.

85
Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius.

86
fahrenheit Input(s) integer

87
celsius Output(s) double OR float 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. 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.

90
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.

95
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