700 likes | 710 Views
Basic Elements of C++. TK1913 C++ Programming. INTRODUCTION. In this chapter, you will learn some basic elements of the C++ language. 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:
E N D
Basic Elements of C++ TK1913 C++ Programming
INTRODUCTION • In this chapter, you will learn some basic elements of the C++ language.
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
PROGRAM 1 • The diagram below pictures the design of our program : Start Display message End
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.
PROGRAM 1 • The steps in the flowchart need to be translated to C++ language. Start Display message cout << "Welcome to C++ Programming"; End
PROGRAM 1 • Below is the complete C++ source code for our program. #include <iostream> usingnamespace std; int main() { cout << "Welcome to C++ Programming"; return 0; }
ANOTHER C++ PROGRAM • Write a C++ program which calculates the area of a circle based on the radius inputted by the user.
PROGRAM 2 • Let's first design our program. Start Input radius Calculate area of circle Display area End
PROGRAM 2 • Translate the steps into C++. cin >> radius; area = 3.14 * radius * radius; cout << area; Start Input radius Calculate area of circle Display area End
identifier keyword data type arithmetic operator PROGRAM 2 #include <iostream> usingnamespace std; int main() { float radius, area; cout << "Enter radius: "; cin >> radius; area = 3.14 * radius * radius; cout << "Area: "; cout << area; cout << endl; return 0; }
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.
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
IDENTIFIERS • The following are legal identifiers in C++: • first • conversion • payRate
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: -6789 0 52 • bool • Has two values: true, false • char
a single space char DATA TYPE • 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 ' '
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 1000001 (66th character) • ‘3’ is encoded as 0110011
FLOATING-POINT DATA TYPES • C++ uses scientific notation to represent real numbers (floating-point notation) • Two commonly used floating-point data types: floatdouble
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
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
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
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.
PROGRAM 3 • Consider the following flowchart: Start Input price and quantity Calculate amount to be paid Display payment details End
PROGRAM 3 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 Display total amount cout << total; End
variable variable declaration PROGRAM 3 #include <iostream> usingnamespace std; int main() { float price, total, discount; int quantity; cout << “Enter price: “; cin >> price; cout << “Enter quantity: “; cin >> quantity;
expression assignment statement PROGRAM 3 total = price * quantity; discount = 0.2*total; total = total – discount; cout << "Please pay: RM"; cout << total; cout << endl; return 0; }
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
DECLARING AND INITIALIZING VARIABLES • Variables can be initialized when declared: int first=13, second=10; char ch=' '; double x=12.6, y=123.456;
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
MIXED EXPRESSIONS • Mixed expression: • Has operands of different data types • Contains integers and floating-point • Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2
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 2.000000). • Operator is evaluated • Result is floating-point
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
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)
TYPE CONVERSION (CASTING) • Consider the following program (prog1.cpp): #include <iostream> usingnamespace 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; }
TYPE CONVERSION (CASTING) • Compare with the following program (prog2.cpp): #include <iostream> usingnamespace 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; }
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
stringDATA 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
stringDATA TYPE • To use the string type, you need to access its definition from the header file string • Include the following preprocessor directive: #include <string>
USING cinFOR 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...;
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
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";
preprocessor directive string data type namespace usage declaration PROGRAM 4 (prog3.cpp) #include <iostream> #include <string> usingnamespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Thank you, " << name << endl; return 0; }
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
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
USINGcinANDcout • 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;
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.
ANALYSIS • Input • Elapsed time (in seconds) elapsed_time • Output • 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
DESIGN Start Input elapsed_time Calculate hr:min:sec Display hr:min:sec End