Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "Introduction to programming using C++ Dr. Mohamed Khafagy."— Presentation transcript:


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

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

6 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

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




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:


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:

31 Flowchart

32 Pseudocode Read NAME, BALANCE, RATE Compute INTEREST as BALANCE x RATE Write (Display) NAME and INTEREST


34 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

35 The example below shows the flowchart for a program that reads two numbers and displays the numbers read in decreasing order


37 Read A, B If A is less than B BIG = B SMALL = A else BIG = A SMALL = B Write (Display) BIG, SMALL

38 Example Problem Statement ◦ Given a collection of nickels (US 5-cent coins) and pennies (US 1- cent 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 

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

40 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)/ Compute the corresponding total in HK dollars total_HKD = total_USD * US2HK 4. Find the number of HK dollar coins total_HK_cent = total_HKD * dollar = total_HK_cent / Display the number of HK dollar.

41 General form of a C++ program // Program description #include directives int main(){ constant declarations variable declarations executable statements return 0; }

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

45 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 = ; ◦ char begin = 'A', end = 'Z', newLine = '\n‘;

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

49 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 = ; 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$

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.

56 More Data Types bool ◦ 8 bits ◦ either trueor false string ◦ Class type ◦ Defined in double quotes ◦ Must include the library

57 Assignment Literal Values someInt= 27; someDub= 33.33; Expressions someInt= ; someDub= 5.55 * 1.0; Values of other Variables someInt= someOtherInt; someDub= someOtherDub; someInt= someInt2 + someInt3; someDub= someDub2 / someDub3;

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

59 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 */

60 Rules for Division C++ treats integers differently from decimal numbers. 100 is an int type , , 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)

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

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

64 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

65 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

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

67 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;

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

70 // Demonstrate the features of output format manipulators // Input: cost of lunch, number of people attending lunch // Output: lunch cost per person #include // Use IO manipulators #include 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";

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

75 Operator Examples P?: < a ? b : c; /* if a is true, then b, else c; a is usually in parens */ 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;

76 Arithmetic Operators Can be used for literal values and variables (in order of precedence) ◦ Parentheses( ) ◦ Multiplication * ◦ Division / ◦ Modulus% ◦ Addition + ◦ Subtraction –

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

79 78 Operator Precedence Which comes first? * / % + - = > == != = Answer:

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.

84 The Corresponding C++ Program #include 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!" <> 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; }

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.

88 Relevant Formula celsius=(5/9)*(fahrenheit – 32)

89 #include int main() { #include int main() { return 0; } return 0; } int fahrenheit; double celsius; cout<<"Please enter a temperature in degrees Fahrenheit :“; cin>>fahrenheit ; 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;

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.

91 hours minutes hours minutes Input(s) integer

92 temperature Output(s) double

93 Relevant Formula temperature=(4*time*time)/(time+2)-20 time=hours+minutes/60

94 #include int main() { #include int main() { return 0; } return 0; } int hours; int minutes; int hours; int minutes; double time; double temperature; double time; double temperature; cout<<"Please enter the time : “; cin>>hours>>minutes ; cout<<"Please enter the time : “; cin>>hours>>minutes ; time = hours + (double) minutes / 60; temperature = ( 4 * time * time) / (time + 2) - 20; time = hours + (double) minutes / 60; temperature = ( 4 * time * time) / (time + 2) - 20; cout<<"The temperature in freezer is \n“<< temperature;

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

Download ppt "Introduction to programming using C++ Dr. Mohamed Khafagy."

Similar presentations

Ads by Google