Presentation is loading. Please wait.

Presentation is loading. Please wait.

TK1913 C++ Programming Basic Elements of C++.

Similar presentations


Presentation on theme: "TK1913 C++ Programming Basic Elements of C++."— Presentation transcript:

1 TK1913 C++ Programming Basic Elements of C++

2 INTRODUCTION In this chapter, you will learn some basic elements of the C++ language.

3 MY FIRST C++ PROGRAM Let's write a C++ program which simply instructs the computer to present the following text message on the display screen: Welcome to C++ Programming

4 PROGRAM 1 The diagram below pictures the design of our program : Start
Display message End

5 FLOWCHART The diagram shown in the previous slide is called a flowchart. A flowchart is a diagram which represents graphically a sequence of steps to be followed in carrying out a task (for example, by the computer). You will learn more about flowcharts later.

6 PROGRAM 1 The steps in the flowchart need to be translated to C++ language. Start Display message cout << "Welcome to C++ Programming"; End

7 PROGRAM 1 Below is the complete C++ source code for our program.
#include <iostream> using namespace std; int main() { cout << "Welcome to C++ Programming"; return 0; }

8 ANOTHER C++ PROGRAM Write a C++ program which calculates the area of a circle based on the radius inputted by the user.

9 PROGRAM 2 Let's first design our program. Start Input radius
End Input radius Display area Calculate area of circle

10 PROGRAM 2 Translate the steps into C++. cin >> radius;
Start End Input radius Display area Calculate area of circle cin >> radius; area = 3.14 * radius * radius; cout << area;

11 PROGRAM 2 identifier keyword data type arithmetic operator
#include <iostream> using namespace std; int main() { float radius, area; cout << "Enter radius: "; cin >> radius; area = 3.14 * radius * radius; cout << "Area: "; cout << area; cout << endl; return 0; } keyword identifier data type arithmetic operator progB.cpp

12 KEYWORDS Keywords are words which are part of the syntax of a language. Some examples of C++ keywords: int,float,double,char,void,return Keywords in C++ are reserved words. You cannot use them to name variables, functions, etc.

13 IDENTIFIERS Identifiers are names used in programs. They are names of variables, types, labels, functions, etc. In C++, an identifier consists of letters, digits, and the underscore character (_) It must begin with a letter or underscore C++ is case sensitive Some identifiers are predefined such as cout and cin Predefined identifiers may be redefined, but it is not a good idea

14 IDENTIFIERS The following are legal identifiers in C++: first
conversion payRate

15 DATA TYPES A data type is a set of values together with a set of operations. Some integral data types: int Examples of int values: bool Has two values: true, false char

16 char DATA TYPE Each character is enclosed in single quotes
char is an integral data type for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some examples of char values 'A' 'a' '0' '*' '+' '$' '&' A blank space is a character and is written as ' ' a single space

17 char DATA TYPE Each character is actually represented by an integer code based on the ASCII character set. ASCII (American Standard Code for Information Interchange) 128 characters in the character set ‘A’ is encoded as (66th character) ‘3’ is encoded as

18 FLOATING-POINT DATA TYPES
C++ uses scientific notation to represent real numbers (floating-point notation) Two commonly used floating-point data types: float double

19 FLOATING-POINT DATA TYPE
float: represents any real number Range: -3.4E+38 to 3.4E+38 Single precision values i.e. maximum number of significant digits (decimal places) is 6 or 7 Memory allocated for the float type is 4 bytes double: represents any real number Range: -1.7E+308 to 1.7E+308 Double precision values i.e. maximum number of significant digits (decimal places) is 15 Memory allocated for double type is 8 bytes

20 ARITHMETIC OPERATORS C++ Arithmetic Operators
+ addition - subtraction * multiplication / division % remainder (mod operator) +, -, *, and / can be used with integral and floating-point data types Unary operator - has only one operand Binary Operator - has two operands

21 ORDER OF PRECEDENCE All operations inside of () are evaluated first
*, /, and % are at the same level of precedence and are evaluated next + and – have the same level of precedence and are evaluated last When operators are on the same level Performed from left to right

22

23 ANOTHER C++ PROGRAM Write a C++ program which inputs the price of an item and the quantity bought from the user. The program then calculates the total amount to be paid after a 20% discount.

24 PROGRAM 3 Consider the following flowchart: Start Input
price and quantity Calculate amount to be paid Display payment details End

25 PROGRAM 3 cin >> price; cin >> quantity;
Start cin >> price; cin >> quantity; Input price and quantity total = price * quantity; discount = 0.2*total; total = total – discount; Calculate total amount to be paid cout << total; Display total amount End

26 PROGRAM 3 #include <iostream> using namespace std; int main() {
float price, total, discount; int quantity; cout << “Enter price: “; cin >> price; cout << “Enter quantity: “; cin >> quantity; variable variable declaration progC.cpp

27 PROGRAM 3 total = price * quantity; discount = 0.2*total;
expression total = price * quantity; discount = 0.2*total; total = total – discount; cout << "Please pay: RM"; cout << total; cout << endl; return 0; } assignment statement progC.cpp

28 VARIABLES A variable refers to a memory location whose content may change during execution. A variable must be declared first before it can be used in a C++ program. Examples

29 DECLARING AND INITIALIZING VARIABLES
Variables can be initialized when declared: int first=13, second=10; char ch=' '; double x=12.6, y= ;

30 EXPRESSIONS If all operands are integers
Expression is called an integral expression An integral expression yields integral result If all operands are floating-point Expression is called a floating-point expression A floating-point expression yields a floating-point result

31 MIXED EXPRESSIONS Mixed expression: Examples of mixed expressions:
Has operands of different data types Contains integers and floating-point Examples of mixed expressions: 6 / 5.4 * 2 – / 2

32 EVALUATING MIXED EXPRESSIONS
If operator has same types of operands Evaluated according to the type of the operands If operator has both types of operands Integer value is converted to floating-point value (e.g 2 converted to ). Operator is evaluated Result is floating-point

33 EVALUATING MIXED EXPRESSIONS
Entire expression is evaluated according to precedence rules Multiplication, division, and modulus are evaluated before addition and subtraction Operators having same level of precedence are evaluated from left to right Grouping is allowed for clarity

34 TYPE CONVERSION (CASTING)
Implicit type coercion: when value of one type is automatically changed to another type Cast operator provides explicit type conversion Use the following form: static_cast<dataTypeName>(expression)

35 TYPE CONVERSION (CASTING)
Consider the following program (prog1.cpp): #include <iostream> using namespace std; int main() { int amt1, amt2, amt3; float average; cout << "Enter three readings: "; cin >> amt1 >> amt2 >> amt3; average = (amt1+amt2+amt3) / 3; cout << "Average reading: " << average << endl; return 0; }

36 TYPE CONVERSION (CASTING)
Compare with the following program (prog2.cpp): #include <iostream> using namespace std; int main() { int amt1, amt2, amt3; float average; cout << "Enter three readings: "; cin >> amt1 >> amt2 >> amt3; average = static_cast<float>(amt1+amt2+amt3) / 3; cout << "Average reading: " << average << endl; return 0; }

37 ASSIGNMENT STATEMENT The assignment statement takes the form:
variable = expression; Expression is evaluated and its value is assigned to the variable on the left side In C++, = is called the assignment operator

38 string DATA TYPE Programmer-defined type supplied in standard library
Sequence of zero or more characters Enclosed in double quotation marks "" is a string with no characters (empty string) Each character has relative position in string Position of first character is 0, the position of the second is 1, and so on Length: number of characters in string

39 string DATA TYPE To use the string type, you need to access its definition from the header file string Include the following preprocessor directive: #include <string>

40 USING cin FOR INPUTTING
cin is used with >> to gather input cin >> variable; The extraction operator is >> Using more than one variable in cin allows more than one value to be read at a time cin >> variable >> variable...;

41 USING cout FOR OUTPUTTING
The syntax of cout and << is: cout<< expression or manipulator << expression or manipulator << ...; Called an output (cout) statement The << operator is called the insertion operator or the stream insertion operator Expression evaluated and its value is printed at the current cursor position on the screen

42 USING cout FOR OUTPUTTING
Manipulator: alters output endl: the simplest manipulator Causes cursor to move to beginning of the next line The newline character '\n' can also be output which causes the cursor to move to the next line. Example: cout << "Hello.\nWelcome to UKM\n";

43 COMMON ESCAPE SEQUENCES

44 PROGRAM 4 (prog3.cpp) preprocessor directive string data type
#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Thank you, " << name << endl; return 0; } namespace usage declaration

45 PREPROCESSOR DIRECTIVES
C++ has a small number of operations Many functions and symbols needed to run a C++ program are provided as collection of libraries Every library has a name and is referred to by a header file Preprocessor directives are commands supplied to the preprocessor All preprocessor commands begin with # No semicolon at the end of these commands

46 PREPROCESSOR DIRECTIVES
Syntax to include a header file #include <headerFileName> Example: #include <iostream> Causes the preprocessor to include the header file iostream in the program

47 USING cin AND cout cin and cout are declared in the header file iostream, but within a namespace named std To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std;

48 PROBLEM [Textbook, pg 111, no. 12]
Write a C++ program that prompts the user to input the elapsed time for an event in seconds. The program then outputs the elapsed time in hours, minutes and seconds.

49 ANALYSIS Input Output Process Elapsed time (in seconds) elapsed_time
Elapsed time hr : min : sec Process 1 minute = 60 seconds 1 hour = 60 minutes To get min : sec min = elapsed_time / 60 sec = elapsed_time % 60 To get hr : min : sec hr = min / 60 min = min % 60

50 DESIGN Start Input elapsed_time Calculate hr:min:sec Display
End

51 DESIGN Start Input elapsed_time Display hr:min:sec
min ← elapsed_time / 60 sec ← elapsed_time % 60 End hr ← min / 60 min ← min % 60

52 PROGRAM 5 (prog4.cpp) #include <iostream> using namespace std;
int main() { int elapsed_time, hr, min, sec; cout << "Enter elapsed time: "; cin >> elapsed_time; min = elapsed_time / 60; sec = elapsed_time % 60; hr = min / 60; min = min % 60; cout << hr << “ : “ << min << " : " << sec << endl; return 0; }

53 COMPILE SOURCE CODE Suppose the source code is saved in a file called convert.cpp. To compile the source code and generate an executable file called convertElapsedTime (using g++ in Linux): g++ -o convertElapsedTime convert.cpp To run the program: ./convertElapsedTime

54 SYNTAX ERRORS Syntax errors are errors in the source code which are related to the syntax of the language. Syntax errors are detected by the compiler. An executable file will be generated by the compiler only if the source code it compiles has no syntax errors. Syntax errors are reported by the compiler in the form of error messages.

55 #include <iostream> using namespace std; int main() {
cout << "This program has errors return; } Error messages displayed by the compiler

56 LOGICAL ERRORS Logical errors are errors which are related to program logic. Normally, logical errors are not detectable by the compiler. Logical errors are usually detected during program runtime. For example, a program producing unexpected results is an indication that it has logical errors. It is important to remember that if the compiler does not produce any error messages, it does not mean that your program is free of logical errors.

57 LOGICAL ERRORS Possible to remove all syntax errors in a program and still not have it run Even if it runs, it may still not do what you meant it to do For example, 2 + 3 * 5 and (2 + 3) * 5 are both syntactically correct expressions, but have different meanings

58 Write a program to calculate the area of the region in blue.
#include <iostream> using namespace std; int main() { float radius, length, width; cout << "Enter radius, length and width: "; cin >> radius >> length >> width; cout << "Area of blue region: " << length*width *radius*radius; return 0; } Example of logical error

59 Suppose we test the program with these inputs:
radius: 7 length: 2 width: 3 Area of circle = 3.14 * 7 * 7 = Area of rectangle = 2 * 3 = 6 This means that the rectangle is enclosed by the circle. The area of the region should not be negative.

60 The following output is generated when the program is executed with those inputs.
The program should be checked for logical errors.

61 3.14*radius*radius – length*width
#include <iostream> using namespace std; int main() { float radius, length, width; cout << "Enter radius, length and width: "; cin >> radius >> length >> width; cout << "Area of blue region: " << length*width *radius*radius; return 0; } The formula should be 3.14*radius*radius – length*width Example of logical error

62 PROGRAM STYLE AND FORM Every C++ program has a function called main
#include <iostream> using namespace std; int main() { cout << "Welcome to C++ Programming"; cout << endl; return 0; } Every C++ program has a function called main Basic parts of function main are: The heading The body of the function

63 USE OF WHITESPACE Insert white space characters (such as blanks, tabs and newlines) if necessary to increase the readability of your source code. Example: int matrix[][3]={1,0,0,0,1,0,0,0,1}; int matrix[][3] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; White space characters are ignored by the compiler during compilation. Remember to separate reserved words and identifiers from each other and other symbols. Example: inta, b, c; This statement is syntactically incorrect.

64 COMMAS AND SEMICOLONS Example: int a, b, c;
Commas separate items in a list. Example: int a, b, c; All C++ statements end with a semicolon. Example: area = length * width; Semicolon is also called a statement terminator.

65 DOCUMENTATION Programs are easier to read and maintain if they are well-documented. Comments can be used to document code Single line comments begin with // anywhere in the line Multiple line comments are enclosed between /* and */ Example: MapGenerator.cpp

66 DOCUMENTATION Avoid putting in useless comments such as shown below:
int main() { min = elapsed_time / 60; // assign elapsed_time / 60 to min sec = elapsed_time % 60; // assign elapsed_time % 60 to sec hr = min / 60; // assign min / 60 to hr min = min % 60; // assign min % 60 to min }

67 DOCUMENTATION The program comments below are more useful: int main() {
// Convert elapsed_time to min:sec min = elapsed_time / 60; sec = elapsed_time % 60; // Convert min:sec to hr:min:sec hr = min / 60; min = min % 60; }

68 DOCUMENTATION Name identifiers with meaningful names.
For example, which of the statements below is more meaningful? a = l * w; area = length * width;

69 YOU SHOULD NOW KNOW… Keywords Identifiers
Data types; integral, floating-point Arithmetic operators Order of precedence Variables and variable declarations Expressions and evaluating them Type casting Assignment statement

70 YOU SHOULD NOW KNOW… Basic input/output using cin and cout
Escape sequences Preprocessor directives The string data type Compiling and generating executable programs from C++ source code Syntax and logical errors Form of the function main() Importance of program readability using whitespace characters inserting comments using meaningful names for identifiers


Download ppt "TK1913 C++ Programming Basic Elements of C++."

Similar presentations


Ads by Google