Download presentation
Presentation is loading. Please wait.
1
DFC1023 PROBLEM SOLVING AND PROGRAM DESIGN
CHAPTER 3: FUNDAMENTALS OF PROGRAMMING LANGUAGE
2
AT THE END OF THIS CHAPTER, STUDENTS SHOULD BE ABLE TO:
Understand data and Identifier State the definition of data. Explain the data types: numeric and non-numeric. Define Identifier, Variable and Constant and reserved word. State the naming convention rules for Identifier. Declare data types, variables and constants in programming language Solve problems using operators Explain Arithmetic, Relational and Logical operators Write expression and solve problems
3
What is Data? Data is a collection of numbers, characters, alphabets, and special symbols etc. It can be processed to produce some meaningful information. It also can be modified by the computer into useful forms for human beings.
4
Basic Data Type Data is divided into: Numeric Integer Float
Non Numeric Character String Boolean
5
Basic Data Type Numeric Non Numeric Contains all types of numbers.
Data which can be used for calculation. Contains all types of non-numbers. INTEGER All positive and negative numbers including zero and no decimal place. Example: 0, +1, -10. Integers are used to represent the counting of things. Example: Numbers of month in a year (1,2,3…) CHARACTER Consists of all letters, numbers and special symbols. Characters are surrounded by single quotation mark (‘ ‘). Example: ‘A’, ‘m’,’=’, ‘#’, ‘1’ or ‘ ‘. FLOAT Contains all real numbers. The number will be stored in floating point. Used for metric measurement, temperature and price. Example: 1.0, , 20.30, 36.7. STRING A combination of one or more characters. A string is surrounded by double quotation marks (“ “). Example: (“WELCOME TO COSMOPOINT”) or (“8758”). BOOLEAN (LOGICAL VALUE) Used in making yes-or-no decisions (T or F). Example: To check 2 integers using If…Else control structure.
6
Basic Data Type int int is used to define integer numbers. int Count;
USES EXAMPLE CODE int int is used to define integer numbers. int Count; Count = 5; float float is used to define floating point numbers. float Miles; Miles = 5.6; double A double is used to define BIG floating point numbers. It reserves twice the storage for the number. double Atoms; Atoms= ; char A char defines characters. char Letter; Letter = 'x';
7
Identifier IDENTIFIER is words used to represent certain program entities (variables, function names, etc). Example: int my_name; my_name is an identifier used as a program variable void CalculateTotal(int value) CalculateTotal is an identifier used as a function name FP101Programming Fundamentals with C++
8
Variable VARIABLE is identifier whose value can change during the course of execution of a program Variable is a specified location in memory which: we can refer to by an identifier value can be stored but the data value that can be change while the program is running. declaring a variable means specifying both its name and its data type. Example: int size1, numbers;
9
Constant CONSTANTS are values that do not change during program execution. Also called named constants or read-only variables. Entities that appear in the program code as fixed values and any attempt to modify a constant will result in error. Declared using the const qualifier. Must be initialized with a constant expression when they are declared and cannot be modified thereafter Example: const int size = 5;
10
Naming convention rules for identifier
They are formed by combining letters, digits & underscores. Blank space is not allowed in an identifier. The first character of an identifier must be a letter. valid invalid reason Monthly_Salary Monthly Salary Blank space cannot be used Month1 1stMonth Digit cannot be used as a first character _add Special characters cannot be used
11
Naming convention rules for identifier
Example Can contain a mix of character and numbers. However it cannot start with a number H2o First character must be a letter or underscore Number1, _area Can be of mixed cases including underscore character XsquAre my_num Cannot contain any arithmetic operators R*S+T … or any other punctuation marks Cannot be a C keyword/reserved word struct; cout; Cannot contain a space My height … identifiers are case sensitive Tax != tax
12
Naming convention rules for identifier
Valid Invalid Comment X “x” Illegal character Gross_Pay Gross pay Illegal blank Hourly_rate Hourly-rate Illegal character - name Illegal sumx2 2sumx Illegal 1st character
13
Declare Data Types, Variables and Constant in Programming Language
A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location. Before use, variables must be declared to tells the compiler the type of data to store. Declaration syntax: Data_Type identifier_name;
14
Declare Data Types, Variables and Constant in Programming Language
Declaration Examples: int age, num_students; int cars_waiting; float taxRateY2K, AverageNumber; double average, m_score, total_score; double moon_distance; char middleInitial;
15
Two locations for variable declarations:
Declare Data Types, Variables and Constant in Programming Language Two locations for variable declarations: main() { … … int sum, score1, score2; sum = score1 + score 2; … } main() { int sum, score1, score2; … … sum = score1 + score2; … } a) Immediately prior to use b) At the beginning
16
Declare Data Types, Variables and Constant in Programming Language
Declaring a variable does not give it a value. Giving a variable its first value is initializing the variable. Method 1: Variables are initialized in assignment statements double mpg; // declare the variable mpg = 26.3; // initialize the variable Method 2: Declaration and initialization can be combined using two methods: Method 1: double mpg = 26.3, area = 0.0 , volume; Method 2: double mpg(26.3), area(0.0), volume;
17
Variables Declaration with Data Types Integer
Used to declare numeric program variables of integer type includes positive, negative and zero numbers. Keyword: int Syntax: Example code : Sample values: int identifier_name; int number; number = 12;
18
Variables Declaration with Data Types Float
Float is a floating point numbers with maximum 6 decimal place. Keyword: float Syntax: Example code: Sample values: float identifier_name; float height; height = 1.72;
19
Variables Declaration with Data Types Double
Double is a floating point numbers with maximum 15 decimal place and long double (19 place decimal). Used to declare floating point variable of higher precision or higher range of numbers. Examples are exponential numbers, positive and negative keyword: double Code example: double valuebig; valuebig = 12E-3;
20
char name_identifier;
Variables Declaration with Data Types Character character Example of characters: Numeric digits: 0 - 9 Lowercase/uppercase letters: a - z and A - Z Space (blank) Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc Syntax: Keyword: char Example code: Sample values: ‘B’ ‘d’ ‘4’ ‘?’ ‘*’ The declared character must be enclosed within a single quote! char name_identifier; char gred; gred = ‘A’;
21
FP101 Programming Principles
Variables Declaration with Data Types String String String is a sequence of characters enclosed in double quotes. The empty string (null string) contains no characters and is written as “ ”. keyword: string To declare a variable of type string: Sample values: “Hello” “Year 2000” “1234” string greeting=“Hello”; Chapter 3 - Fundamentals of Programming Language
22
bool name_identifier;
Variables Declaration with Data Types Boolean Boolean Boolean is a new addition to C++. Boolean values are either true or false. Keyword: bool Syntax: To declare a variable of type bool: bool name_identifier; bool booleanVar = true;
23
FP101 Programming Principles
Constant Declaration A named constant is a location in memory that we can refer to by an identifier. The data value that cannot be changed is stored. There are two methods to declare a constants: a) by using cons b) by using #define preprocessor directives A character constant must be enclosed in a single quotation mark Chapter 3 - Fundamentals of Programming Language
24
Constant Declaration – Method 1
Example of valid constant declaration: Enumeration are the values are given as a list. Example: const char letter = ‘n’; const string STARS = “****”; const float NORMAL_TEMP = 98.6; const int VOTING_AGE = 18; const float MAX_HOURS = 40.0; enum Language { Malay, English, Arabic };
25
Constant Declaration - Method 2
You may also associate constant using #define preprocessor directive. Example: #include <iostream.h> #define pi 3.412 void main(void) { double height, radius, base, volume; cout <<“Enter the height and radius of the cone:”; cin >>height >> radius; base = pi * radius * radius; volume = (1.0/3.0) * base * height; cout <<“\nThe volume of a cone is ” << volume; }
26
How data is stored in computer memory based on data and identifier declaration?
27
AT THE END OF THIS CHAPTER, STUDENTS SHOULD BE ABLE TO:
Solve problems using operators Explain Arithmetic, Relational and Logical operators Write expression using operators Solve problems using expressions
28
Operators in a Program Operators are symbols used to represent computer operations. These symbols have one or more special characters defined by programming language. The operations that can be operated on variables are: Arithmetic operation Assignment operation Relational operation Logical operation
29
Operators in a Program Arithmetic Operators
Calculation operation that can be done on data in variables Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and division (/) operations. In addition there is the modulus operator (%) which gives the remainder left over from a division operation.
30
Operators in a Program Arithmetic Operators
Variables usually can be increased or decreased by 1. For example, C language and Java has provided operator to add or subtract 1 from variable values. This operators are called Increment and Decrement. The symbols are: Symbol Operation ++ – – Add 1 Subtract 1 Notes: x++ can also be written as x = x + 1 y– – can also be written as y = y – 1
31
Operators in a Program Assignment Operators
Assignment operators are used to combine the '=' operator with one of the binary arithmetic operators. Examples expression using assignment operators: c = c + 3 d = d - 4 e = e * 5 g = g % 9 f = f / 3
32
FP101 Programming Principles
Operators in a Program Relational Operators The relational operators compare values to one other. All of the relational operators result in a Boolean value. Expression that consist relational operator will return the value 1 if true and 0 if it false. Relational operator can be divided into 2 groups: Not Equivalent Group Equivalent Group Chapter 3 - Fundamentals of Programming Language
33
Greater than or equals to
Operators in a Program Not Equivalent Group Not equal is an expression that consists relational operator that will return the value of 1, if the relation is true and 0 if it is false. Symbols: Example: a = 10, b = 2; c = a > b; d = (b * 3) > a; Symbol Operators > >= < <= Greater than Greater than or equals to Less than Less than or equals to Variable c will have 1 as value because relation (10 > 2) is true, while variable d will have 0 because relation (6 < 0) is false.
34
Operators in a Program 2. Equivalent Group
Equivalent is an expression that consists of relational operator that will return 1 if the relation is true and 0 if false. Symbols: Example: a = 10; b = 2; c = a != b; d = (b * 5) == a; Symbol Operators == != Equal to Not equal to Variable c will have 1 as value because relation (10! = 2) is true, and variable d will have 1 as value because relation (2 * 5 == 10) is also true.
35
Operators in a Program Logical operators
The three logical operators (AND, OR and NOT) are as follows: AND (&&) : Returns true only if both operand are true. OR (||) : Returns true if one of the operand is true. NOT (!) : Converts false to true and true to false. Symbol Operators && || ! AND OR NOT
36
Operators in a Program Logical operators
Expression that consist logic operator will return the value 1 if the relation is true and 0 if it false. The Truth Table below shows the definition of C languages for logical operator: P Q P&&Q P||Q !P !Q 1
37
Operators in a Program Logical operators Example 1: If x = 2 and y = 3
Expression Value a a = x && y a = (x > 0) && (y > 0) a = (x < y) && (y == 0) a = x || y a = (x !0) || (y != 0) a = (x == y) || (y == 0) a = ! (x == y) a = ! (x < y) 1
38
Operators in a Program Logical operators Operator Operator's Name
Example Result && AND 3>2 && 3>1 3>2 && 3<1 3<2 && 3<1 || OR 3>2 || 3>1 3>2 || 3<1 3<2 || 3<1 ! NOT !(3==2) !(3==3)
39
Operators in a Program All operators (for example in C language) can be combined into one expression. Notes below shows the priorities set for all operators, that has been discussed before: Operations ( ) Highest priority ! ++ – – * / % + – < <= > >= = = != && || = Lowest priority
40
Operators in a Program Write expression using operators Example:
Expression x + y == z && m – n will be defined as below: + operation gets highest priority in the expression. Then, followed by – operation and then == operation. The last operation done is && because it has the lowest priority. ( x + y ) == z && m – n ( x + y ) == z && ( m – n ) ( ( ( x + y ) == z ) && ( m – n ) ) ( ( x + y ) == z ) && ( m – n )
41
Operators in a Program Given x = 8, y = 6. Find the value for: x++ x--
x < y && x > y x + 2 == 0 || y – x > 0 y + 3 > 0 && x < y
42
FP101 Programming Principles
Operators in a Program Get the answer for the following questions: 2 * / 1 12 % 5 - 1 4 + (7 - 3) * 3 ( 2 * 4 ) * 2 – (6 +2) / 8 Find x value from the questions: Given a = 2 and b = 4; x = (a != 0) || (b != 0) x = (a == 0) || (b == 0) x = !(a == b) x = !(a < b) Chapter 3 - Fundamentals of Programming Language
43
AT THE END OF THIS CHAPTER, STUDENTS SHOULD BE ABLE TO:
Apply program control structure Control structure in problem solving: Sequence, Selection and Repetition Illustrate flow of control structure using pseudo code and flow chart Write pseudo code and flow chart using control structure Analyze problem and design algorithm for a given case study
44
Program Control Structure
In 1966, two researchers, C. Bohn and G. Jacopini, demonstrated that any algorithm can be described using only 3 control structures: Sequence control structure Selection/decision control structure If……endif If……else Nested if Switch Looping control structure For While Do……while
45
Sequence Control Structure
In this control, every step will be executed one by one from top to bottom. Every box in control structure is a process. Every process is done sequentially The beginning and end of a block of statements can be optionally marked with the keywords begin/start and end.
46
Sequence Control Structure
Format: Pseudocode: Start Statement A; Statement B; End Flowchart: Start Statement A Statement B End
47
Sequence Control Structure
PROBLEM: Compute the total overtime wages of an employee. Problem Analysis: Input: Hours, Basic_salary, OT_rate Process: 1) calculate overtime using formula: Overtime = OT_rate * Hours 2) calculate salary using formula: Salary = Basic_salary + Overtime Output: Salary
48
Sequence Control Structure
Algorithm: Enter Hours, Basic_salary, OT_rate Calculate overtime using formula: Overtime = OT rate * Hours Calculate salary using formula: Salary = Basic_salary + Overtime Display Salary Pseudocode: Start Input Hours, Basic_salary, OT_rate; Overtime = OT_rate * Hours; Salary = Basic_salary + Overtime; Display Salary; End
49
Sequence Control Structure
Flowchart START Input Hours, Basic_salary, OT_rate Overtime = OT_rate * Hours Output Salary END Salary = Basic_salary + Overtime
50
Selection / Decision Control Structure
Usually used in structured programming. Control structure will execute an instruction based on result of a condition or comparison, the result either TRUE or FALSE. If the condition result is true, the control program will execute the instruction within the TRUE loop operation. Otherwise, it will execute the next instruction or the instruction within the FALSE loop operation.
51
Selection / Decision Control Structure
Type of selection / decision control structure: If……endif If……else Nested if Switch
52
Selection / Decision Control Structure
If……endif Rules: If (condition) Instruction (do this instruction if condition is true) Endif If condition is not true, no instruction will be executed
53
Selection / Decision Control Structure
Flowchart Pseudocode: If (condition) True statement Endif START Condition Statement END False True
54
Selection / Decision Control Structure
Problem If student’s grade is greater than or equal to 60 Print “Passed” Pseudocode: if ( grade >= 60 ) print “ Passed” endif
55
Selection / Decision Control Structure
Flowchart
56
Selection / Decision Control Structure
2) IF…….Else Rules: If (condition) True statement Else False statement Endif
57
Selection / Decision Control Structure
Flowchart START Condition END False True Statement 2 Pseudocode: If (condition) True statement Else False statement Endif Statement 1
58
Selection / Decision Control Structure
Problem If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” Pseudocode: if ( grade >= 60 ) print “ Passed” else print “ Failed” endif
59
Selection / Decision Control Structure
Flowchart
60
Selection / Decision Control Structure
NESTED IF There are 3 types: Type 1: If (condition1) If (condition2) If (condition3) True statement Endif
61
Selection / Decision Control Structure
Type 2: If (condition1) If (condition2) If (condition3) Statement that will be executed if condition1, condition2 and condition3 are true Else Statement that will be executed if condition1, and condition2 are true but condition3 is false Endif Statement that will be executed if condition1 is true but condition2 and condition3 is false Statement that will be executed if condition1 is false
62
Selection / Decision Control Structure
Type 3: If (condition1) Statement that will be executed if condition 1 is true Else If (condition 2) Statement that will be executed if condition2 is true but condition1 is false If (condition3) Statement that will be executed if condition3 is true but condition1 and condition2 are false Statement that will be executed if condition1, condition2 and condition3 are false Endif End if
63
Selection / Decision Control Structure
Problem Pseudo code If (grade >=90) Print “A” Else If (grade >=80) Print “B” Else If (grade >=70) Print “C” Else If (grade >=60) Print “D” Else Print “F”
64
Selection / Decision Control Structure
SWITCH Rules: switch (expression) case condition1 : Instruction statement break case condition2 : Instruction default
65
Selection / Decision Control Structure
Example
66
Selection / Decision Control Structure
Start Enter Grade Grade== A Print “Excellent” break Grade== B Print “Above Average” Grade== C Print “Average” Y N End Grade== D Print “Below Average” Flowchart Selection / Decision Control Structure Print “Error”
67
Repetition Problem : Develop a program to print “FP101 is easy” for 5 times without looping. Solution: Understand the problem: repeat print “FP101 is easy” 5 times. 1. Problem Analysis: Input: None Proses: None Output: print “FP101 is easy” for 5 times
68
Repetition 4. Flow Chart 2. Algorithm: 3. Pseudocode:
1. print “FP101 is easy” for 5 times. 3. Pseudocode: START print “FP101 is easy” for 5 times; END START Print “FP101 is easy” END
69
3 basic types of Repetition Control:
From one number to another number and increases/decrease by a specified value each time for loop The while loop can be used if we don’t know how many times a loop must run. while loop DO..WHILE loops are useful for things that want to repeat at least once. do … while loop for ( variable initialization; end condition; variable update ) { Repeat statement process } while ( condition ) { Process repeat while the condition is true } do { do repeat statement } while ( condition );
70
FP101 Programming Principles
3 basic types of Repetition Control: Flow Chart while do-while For Start Start Start is i < 10? print i i = i+1 i = 0 i = 0 i = 0 is i < 10? print i i = i+1 No i++ Yes Yes Print i i < 10? No Yes End No End End Chapter 3 - Fundamentals of Programming Language
71
Case Study Problem : Develop a program can print “FP101 is easy” for 5 times using looping. Solution: Understand the problem: repeat print “FP101 is easy” 5 times .
72
1.Solution using For Control Loop
1. Problem Analysis: Input: None Process: print “FP 101 is easy” repeat until the condition (5 times) to exit the loop is met Output: print “FP101 is easy” 2. Algorithm: 1. Set n = 0 2. Check condition (n < 5) If true, print “FP101 is easy”. Go to step 3. If false, process will end. 3. Increase counter using formula : n = n + 1 Go to step 2.
73
1. Solution using For Control Loop
3. Psedocode: Start For (n=0; n<5; n++) { print “FP101 is easy”; } End 4. Flow Chart Start n = 0 n++ Yes Print “FP101 is easy” n< 5? No End
74
2.Solution using While control loop
1. Problem Analysis: Input: None Process: print “FP 01 is easy” repeat until the condition (5 times) to exit the loop is met Output: print “FP101 is easy” 2. Algorithm: 1. Set n=0 2. Check condition (n < 5) If true, print “FP101 is easy”. Go to step 3. If false, process will end. 3. Increase counter using formula : n = n+1 Go to step 2.
75
2. Solution using While Control Loop
4. Flow Chart 3. Psedocode: Start Set n = 0; While (n < 5) { print “FP101 is easy”; n++; } End while End Start n = 0 is n < 5? No Yes print “FP101 is easy” n = n+1 End
76
3. Solution using do…While control loop
1. Problem Analysis: Input: None Process: print “FP 01 is easy” repeat until the condition (5 times) to exit the loop is met Output: print “FP101 is easy” 2. Algorithm: 1. Set n = 0 2. Print “FP101 is easy”. 3. Increase counter using formula : n = n+1 4.Check condition (n < 5) If true, Go to step 2. If false, process will end.
77
3. Solution using do…While Control Loop
4. Flow Chart Start 3. Psedocode: Start Set n = 0; Do { print “FP101 is easy”; n++; } While (n < 5) End n = 0 is n < 5? print “FP101 is easy” n = n+1 Yes No End
78
~~THANK YOU~~ http://www.learncpp.com/#Chapter2
THE END ~~THANK YOU~~
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.