Topic 2 Student
Topic 2 Student
Elektrik, PMU
Start
OVERVIEW
2.1
Understand constant and variables Understand data types Understand operator and expression
2.2
2.3
Variables
Variables are like small blackboards We can write a number on them We can change the number We can erase the number Example: int answer;
Identifiers
Identifiers
Variables names are called identifiers Choosing variable names Use meaningful names that represent data to be stored First character must be a letter the underscore character Remaining characters must be letters numbers underscore character
Example of identifiers
Identifier Valid Reason if Invalid
Yes Yes No No No Cannot contains . Cannot begin with number Cannot contain $
Keyword
Keywords (also called reserved words)
Are used by the C++ language Must be used as they are defined in the programming language Cannot be used as identifiers Examples of keyword: asm class do auto conts break huge while else case float if far
char
At the beginning int main() { int sum; sum = score1 + score2; return 0; }
Declaration Examples:
double average, m_score, total_score; double moon_distance; int age, num_students; int cars_waiting;
Assignment statement
An assignment statement changes the value of a variable total_weight = one_weight + number_of_bars;
total_weight is set to the sum one_weight + number_of_bars
Assignment statements end with a semi-colon The single variable to be changed is always on the left of the assignment operator = On the right of the assignment operator can be
Constants -- age = 21; Variables -- my_cost = your_cost; Expressions -- circumference = diameter * 3.14159;
Exercise 1
Give good variable names for identifiers to store.
the speed of an automobile? an hourly pay rate? the highest score on an exam?
Stored in a form similar to scientific notation All floating-point numbers are signed
Number left of e does not require a decimal point Exponent cannot contain a decimal point
a
Identifier
7
constant
(2+a-3)
expression
ASSIGNMENT EXPRESSION
variable
Assignment operators
expression
BINARY EXPRESSION
7
Second operand
First operand
operator
POSTFIX OPERATOR
operand
a++
Postfix operator (increment by 1)
PREFIX EXPRESSION
operand
++a
unary operator
Operator
Can be classified according to:
The type of their operands and their output.
Arithmetic Relational Logical Boolean
Exercise 2
Expression
Formed by combining operators, variables and constant. Examples:
Gross_pay deductions (basic_pay + hours * rate) (socso + premium + loan) (b * b 4 * a * c) > 0 (sex == male || sex == female) && age >=21
+ x
OR AND NOT
+ * / || && !
Example:
Given the following formula
1 F= 6.2832 LC
Exercise 3
Convert the following equation to C expression:
i. x = m2(m-q) + (p-n) x2 ii. y =
x5
iii.
w = y (x
5.5 ) 10