Lecture 3+4 Data Types
Lecture 3+4 Data Types
,Data types
Variables and Constant
Variable Declaration
Assignment Statement
Reading and writing variables
First C program
CODE: MEMORY:
char letter; letter
letter = 'C'; 67
Declaration of character Variables
switch (a) {
case RED:
...
case WHITE:
...
}
Data Type: 6-void
1 - char
2 - short
4 - int
4 - long
4 7 float
8 15 double
10 19 long
double
Type Conversions
• C++ is a hard-typed language, meaning that each variable
has a fixed type that does not change.
double pi=3.14; // ok
double x=”Hello”; // fails
• Some type conversions occur automatically for example int to
float or float to double
int i = 17;
float x = i; // assigns 17 to x
int j = 2;
float y = i/j;
Type conversions can be forced by a programmer through
a type cast
float z = static_cast<float>(i)/j; // casts i into float before division
Keywords and Identifier
Some Keywords in C and C++ :
Yes total_Sales
Syntax:
const <type> <identifier> = <expression>;
Examples:
const double x = 7.8;
const double r = x * 2;
Variable declarations
• Variables are used to store values that can be changed during the
program execution.
Syntax:
< type > < identifier >;
< type > < identifier > = < expression >;
Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;
.Variable declarations,cont
• A variable has a type and it can contain only values of that type.
• For example, a variable of the type int can only hold integer
values.
• Variables are not automatically initialized. For example, after
declaration
int sum;
the value of the variable sum can be anything (garbage).
• Thus, it is good practice to initialize variables when they are
declared.
• Once a value has been placed in a variable it stays there until the
program alters it.
Character data
• A variable or a constant of char type can hold an ASCII character.
Examples:
const char star = '*';
char letter, one = '1';
Variable Assignments and
Initialization
Assignment:
• Uses the = operator
• Has a single variable on the left side and a
value (constant, variable, or expression)
on the right side
• Copies the value on the right into the
variable on the left:
item = 12;
Variable Assignments and
Initialization
• Initialize a variable: assign it a value
when it is defined:
int length = 12;
• Can initialize some or all variables:
int length = 12, width = 5, area;
Scope
• The scope )مجا<<لof
( a variable: where the
program can access the variable
• A variable cannot be used before it is
defined
Arithmetic Operators
4 ;ans = 7 - 3 subtraction -
21 ;ans = 7 * 3 multiplication *
2 ;ans = 7 / 3 division /
1 ;ans = 7 % 3 modulus %
Operator /