Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE

Similar presentations


Presentation on theme: "CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE"— Presentation transcript:

1 CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE
PROGRAMMING C++ DOPC 330 CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE

2 Objectives To understand the basic structure of C++ program
To introduce the concepts of Data types Identifiers: variables & constants To introduce input & output statement To introduce a formatting output

3 Structure of C++ Program

4 Structure of C++ Program : Comments
Two format Line comment Marked by two slashes (//) at the beginning of comment For short comment : in a single line Example: // written by: Mohd Suffian Sulaiman Block comment Marked by opening token (/*) and closing token (*/) For long comment Example: /*This program is to calculate the area of a cylinder*/ Comments CANNOT be nested (comments inside comments) Use: to document programs and improve program readability Help other people read and understand others program IGNORED by C++ compiler and DO NOT cause any machine language object code to be generated DO NOT cause the computer to perform any action when the program is run CAN be put ANYWHERE in the program

5 Structure of C++ Program: Preprocessor Directive
Will be read first before the program is compiled Indicated by pound sign/hash (#) together with keyword #include – to include the contents of another file #define – to define global variable/ constant **No space between # and include #include<iostream.h> iostream.h Is the name of the file that is to be included Dot h indocates the type of the file – header file Allow C++ program to display output on the screen – cout and read input from keyboard - cin #define pi 3.142 pi – Name of constant 3.142 – value of the constant

6 Structure of C++ Program: main function
C++ program can have one or more functions, exactly one MUST be main() function int main() int – stands for integer. It indicates that the function sends an integer back to operating system when it is finished executing main() – the name of the function MUST be followed by set of braces ({ }) – indicates a block, the beginning and ending of a function All statements (function body) that make up a function are enclosed in a set of braces

7 Structure of C++ Program: function body
Enclosed by a set of braces ( { } ) Function contains Local declaration Declaration of data that will be used for the function/program Example: float radius, height; program body Set of instructions of what the function/program should do Return statement Return value that sends back to operating system Example: return 0; // 0 indicates the program executes successfully

8 Common Programming Language Elements
Syntax Rules that must be followed when constructing a program Lines / Lines of code A ‘line’ is a single line appear in the body of program Statement A complete instruction that causes the computer to perform some action Keywords (Reserve Words) Words that have special meaning and used for intended purpose

9 Common Programming Language Elements
Programmer-Defined Identifier (Identifier) Words/names defined by programmer. Symbolic names refer to variables or functions Punctuations Punctuation characters mark the beginning or ending of a statement or separate item in a list

10 Punctuations Comma ( , )  use to separate item in alist
Example: float radius, height; Semicolon ( ; ) Use at the end of a complete instruction Printf(“Enter radius: ”); Cylinder = 2*pi*radius*height; Return 0;

11 Reserve Word / Keyword Special words reserve for C++ program which have specific meaning and purpose CANNOT be used as identifiers or variable name Appear in lower case

12 Identifiers Allows programmers to NAME data and other objects in the program Variable, constant, function etc Rules in naming identifiers MUST consist ONLY of alphabetic characters (uppercase or lowercase), digits and underscores ( _ ) First character MUST be alphabetic character or underscore CANNOT contain spaces CANNOT dupliacte with any reserved word **C++ is CASE SENSITIVE This means that NUM1,Num1,num1 and NuM1 are four completely different name.

13 Example of Valid & Invalid Identifiers

14 Variables Variable names correspond to locations in the computer’s memory Every variable has a NAME, a DATA TYPE, a SIZE and a VALUE A variable is created via a declaration where its name and type are specified Example int integer1,integer2,sum; Whenever a new value is placed into a variable (through cin, for example), it replaces (and destroys) the prevoius value.

15 Variable Declaration Specifies in the memory to reserve a specific space for the variable that have the specific location and can store specific data type MUST be declared before the executable of the statement Variable need to FIRST declare before it being used Syntax: data type variable name; example: int maxItems; float payRate; double tax; char code; int a,b;

16 Example of Variable in Memory

17 Data Types Variables are classified according to their data type
Determine the kind of information stored in variables Address, phone numbers, price, distance and etc. Functions also have types which determine by the data it returns C++ program have 5 standard data types: void Floating point: double & float int char string

18 Data Types

19 Numeric Data Type Numeric data types rae broken into 2 categories: Integer and Floating-point Primary consideration for selecting data types: The largest and smallest number that maybe stored in the variable How much memory does the variable use Whether the variable stores signed or unsigned numbers The number of decimal places of precision the variables has The size of variable is the number of bytes of memory it uses. (> variable  > range can hold)

20 Integer Data Type To store WHOLE NUMBER without fraction
C++ program supports 3 different sizes of integer short int Int long int

21 Floating Point Data Type
To store Floating-point number C++ program supports 3 different sizes of numbers Float Double Long double

22 Char Data Type The smallest integral data type
Memory allocated for the char type is 1 byte Used for characters: letters, digits and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: ‘A’, ‘a’, ‘0’, ‘*’, ‘$’ etc A blank space is a character and is written ‘ ’, with a space left between the single quotes Find the range of char datatype?

23 Char Data Type

24 String Data Type Programmer-defined type supplied in standard library
Sequence of zero or more characters Enclosed in double quotation marks Null: a string with no characters 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

25 String Data Types

26 Variable Initialization
To establish the first value that the variable will contain Syntax: data_type variable_name = value; Example: int count =5; int sum=0; char letter = ‘a’; float price = 45.99;

27 Constants To define values that CANNOT be changed during the execution of a program Types of constant: integer constant, float constant, character constant, string constant and symbolic constant 3 ways of defining a constant Literal constant Defined constant – using pre-processor Defined constant – using const

28 Literal Constant An unnamed constant used to specify data
If the data CANNOT be changed, it can simply code the value itself in a statement Example; ‘A’ 5 A + 5 3.1455 “Hello”

29 Defined Constants 2 ways: Using pre-processor : #define
Example #define pi 3.142 Using keyword : const const int a = 1;

30 Example: Constant

31 Input & Output Stream Output  cout Input  cin
To display information on the computer’s screen Example: cout<<“Programming is great FUN!!”; Input  cin To read data typed from the keyboard cout<<“please enter a number >>\n”; cin>>val1; **MUST include <iostream> header file

32 Input & Output Stream

33 Escape Sequence Indicates that cout should do something out of the ordinary When encountering a backslash (\) in a string, the compiler looks ahead at the next character and combines it with the backslash to form an escape sequence

34 Formatting Program Output
Besides displaying correct results, it is extremely important for a program to present its output attractively. To include manipulators within an output display, must include the header file using the pre-processor command as follows: #include <iomanip> Most commonly used manipulators in a cout statement: setw(n) – set field width to n setfill(n) – sets fill character to n setprecision(n) – sets floating –point precision to n

35 I/O Manipulator Most system divides a page of text output into twenty five rows and eighty columns. Example: Suppose you want to create three column of output: person’s name, person’s student ID and person’s code program.

36 I/O Manipulator

37 I/O Manipulator: setfill(n)
Specifies character for blank space in field Single quotes required around character enclosed in parentheses Example: num = ; cout<<setw(10)<<setfill(‘*’)<<num;

38 I/O Manipulator Generating Left-Justified Value
Specifies character for blank space in field cout.setf(ios::left); By default, when we use setw(n) to print values or information, the values are right justified So to put as left justify we must write the above statement.

39 I/O Manipulator Generating Decimal Point Value cout.setf(ios::fixed);
cout.precision(n); Statement cout.setf(ios::fixed) forces the compiler to generate a fixed decimal output without exponential or e, notation. Meanwhile cout.precision(n) dictates the number of decimal places to the right of decimal point to be generated.

40 I/O Manipulator

41

42 I/O Manipulator The output of program:

43 Exercise Identify valid and invalid variable name:
Sum.of, 12345, newbal, c123, $balance Write declaration statement to declare that the variable count will be used to store an integer Write a declaration statement to declare that the variable initial will be used to store a character Write a declaration statements for the following: tempA,tempB and tempC used to store double – precision number price, yield and coupon used to store single- precision numbers

44 Exercise Write a relational expression to express the following condition (use your own variable name) A person’s height is less than 6 feet A length is greater than 2 and less equal than 3 feet A person’s is older than 50 or has been employed at the company for at least 5 years. Write a snippet code that can receive 3 input decimal number from user and prints the average of the numbers Assign the sum of value variable marks1, marks2 and marks3 to variable totalMarks Trace the output of the program int mystery = 5; mystery = 10 – 2 % mystery; ++mystery; printf(“%d\n”,mystery++);


Download ppt "CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE"

Similar presentations


Ads by Google