0% found this document useful (0 votes)
21 views31 pages

Chapter 03

Uploaded by

bluephoenix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views31 pages

Chapter 03

Uploaded by

bluephoenix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Chapter 03

IT1134
Primary Data Types
A program can use several types of data to solve a given problem, for example, characters, integers, or
floating-point numbers. Since a computer uses different methods for processing and saving data, the data
type must be known.
 Character types: They can represent a single character, such as 'A' or '$'.
 Integer types: They can store a whole number value, such as 7 or -1024. They exist in a variety of sizes,
and can either be signed or unsigned, depending on whether they support negative values or not.
 Floating-point types: They can represent real values, such as 3.14 or -0.01, with different levels of
precision, depending on which of the floating-point types is used.
 Boolean type: The Boolean type can only represent one of two states, true or false.
Variables
A variable is a symbolic name for a memory location in which data can be stored and subsequently recalled.
Variables are used for holding data values so that they can be utilized in various computations in a program.
All variables have two important attributes:
A Data type which is established when the variable is defined (e.g., integer, real, character). Once defined,
the type of a C++ variable cannot be changed.
A variable name (Identifier)
Variable name

An identifier (variable name) must:


 start with a letter or underscore symbol
 consist only of letters, the digits 0-9, or the underscore symbol
 Not be a reserved word.
The following are valid identifiers:
 Length, days_in_year, DataSet1, Profit95, _Pressure, first_one, first_1
The following are invalid:
 days-in-year, 1data, int, first.val, throw
Note : The C++ language is a "case sensitive" language. That means that an identifier written in capital
letters is not equivalent to another one with the same name but written in small letters. Thus, for example,
RESULT variable is not the same as the result variable or the Result variable.
C++ keywords/reserved words

alignas, alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, char16_t,
char32_t, class, compl, const, constexpr, const_cast, continue, decltype, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch, template, this,
thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile,
wchar_t, while, xor, xor_eq
Declaration of variables
 C++ is a strongly-typed language, and requires every variable to be declared with its type before
its first use. This informs the compiler the size to reserve in memory for the variable and how to
interpret its value. The syntax to declare a new variable in C++ is straightforward:
<data type> <variable name>;
int x;
float mynumber;
 If declaring more than one variable of the same type, they can all be declared in a single statement by
separating their identifiers with commas. For example:
int x,y,z;
This declares three variables (x, y and z), all of them of type int
Initialization of variables
 When the variables are declared, they have an undetermined value until they are assigned a value for
the first time. But it is possible for a variable to have a specific value from the moment it is declared.
This is called the initialization of the variable.
type identifier = initial_value;
int a = 1;
int b = 3, c = 5;
char x = 'x'; // the variable x has the value 'x'.
bool s=false;
Constants
 Constants refer to fixed values that the program may not alter and they are called literals. Constants
can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point
Numerals, Characters, Strings and Boolean Values. Again, constants are treated just like regular variables
except that their values cannot be modified after their definition.
 Defined constants (#define)
You can define your own names for constants that you use very often without having to resort to memory-
consuming variables, simply by using the #define pre processor directive. Its for mat is:

#define identifier value


For example:
#define PI 3.14159
# define NEWLINE '\n'
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r; // radius
cout<<"radius:";
cin>>r;
double area;

area = PI * r *r;
cout<< "Area:"<<area;
cout<< NEWLINE;

return 0;
}
Declared constants (const)

 With the const prefix you can declare constants with a specific type
in the same way as you would do with a variable:
const int pathwidth = 100;
const char tabulator = '\t';
Here, pathwidth and tabulator are two typed constants. They are
treated just like regular variables except that their values cannot be
modified after their definition.
Operators in C++
 An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provides the following
types of operators: Arithmetic Operators, Relational Operators, Logical Operators,
Bitwise Operators, Assignment Operators, and Misc Operators.
Arithmetic Operators

Operator Description Example


A=10, B=20

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer B % A will give 0


division

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9


#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout<< "Line 1-Value of c is:" << c <<endl;
c = a - b;
cout<< "Line 2-Value of c is:" << c <<endl;
c = a * b;
cout<< "Line 3-Value of c is:" << c <<endl;
c = a / b;
cout<< "Line 4-Value of c is:" << c <<endl;
c = a % b;
cout<< "Line 5-Value of c is:" << c <<endl;
c = ++a;
cout<< "Line 6-Value of c is:" << c <<endl;
c=b++;
cout<< "Line 7-Value of c is:" << c <<endl;
c = a--;
cout<< "Line 8-Value of c is:" << c <<endl;
return 0;}
#include <iostream> Line 1-Value of c is:31
using namespace std; Line 2-Value of c is:11
main() { Line 3-Value of c is:210
int a = 21; Line 4-Value of c is:2
int b = 10; Line 5-Value of c is:1
int c ; Line 6-Value of c is:22
c = a + b; Line 7-Value of c is:10
cout<< "Line 1-Value of c is:" << c <<endl; Line 8-Value of c is:22
c = a - b;
cout<< "Line 2-Value of c is:" << c <<endl;
c = a * b;
cout<< "Line 3-Value of c is:" << c <<endl;
c = a / b;
cout<< "Line 4-Value of c is:" << c <<endl;
c = a % b;
cout<< "Line 5-Value of c is:" << c <<endl;
c = ++a;
cout<< "Line 6-Value of c is:" << c <<endl;
c=b++;
cout<< "Line 7-Value of c is:" << c <<endl;
c = a--;
cout<< "Line 8-Value of c is:" << c <<endl;
return 0;}
Propositional Logic
English sentences are either true or false or neither. Consider the following sentences:
 Colombo is the capital of Sri Lanka.
 3>5.
 How are you?
The first sentence is true, the second is false, while the last one is neither true nor false. A statement that is either true
or false but not both is called a proposition.
Compound Propositions
 Propositional logic deals with such statements and compound propositions that combine together simple
propositions (e.g., combining sentences (1) and (2) above we may say
“Colombo is the capital of Sri Lanka and 3>5”.
Relational Operators
Operator Description Example
A=10, B=20
== Checks if the values of two operands are equal or not, if (A == B) is not true.
yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand, if yes then condition becomes
true.
The bool Data Type
 The bool data type declares a variable with the value either true or false.

 In C++, you can assign a numeric value to a bool variable. Any nonzero value
evaluates to true and zero value evaluates to false. For example, after the following
assignment statements, b1 and b3 become true, and b2 becomes false.
Truth Tables
 We can express compound propositions using a truth table that displays the relationships between the truth
values of the simple propositions and the compound proposition.
Logical Operators
Operator Description Example
A=true, B=false

&& Called Logical AND operator. If both the operands are (A && B) is false.
non-zero, then condition becomes true.

|| Called Logical OR Operator. If any of the two operands (A || B) is true.


is non-zero, then condition becomes true.

! Called Logical NOT Operator. Use to reverses the


logical state of its operand. If a condition is true, then !(A && B) is true
Logical NOT operator will make false.
Assignment statements

Operator Description Example


= Simple assignment operator, Assigns values from C = A + B will assign value of
right side operands to left side operand A + B into C
+= Add AND assignment operator, It adds right C += A is equivalent to C = C
operand to the left operand and assign the result +A
to left operand
string
 A string is a sequence of characters.
 The char type represents only one character. To represent a string of
characters, use the data type called string. For example, the following
code declares that message to be a string with the value Programming is
fun.
 string message = "Programming is fun";
 The string type is not a primitive type. It is known as an object type.
Objects are defined using classes. string is a predefined class in the
<string> header file.
string
Empty string

String Index and Subscript


Operator The s.at(index) function can be used to
retrieve a specific character in a string s,
where
the index is between 0 and
s.length()–1. For example,
message.at(0) returns the character W
Reading Strings
 A string can be read from the keyboard using the cin object. For example, see the following code:

Line 3 reads a string to city. This approach to reading a string is simple, but there is a problem.
The input ends with a whitespace character. If you want to enter New York, you have to use an alternative approach.
C++ provides the getline function in the string header file,
Concatenating Strings
 C++ provides the + operator for concatenating two strings. The statement shown
below, for example, concatenates strings s1 and s2 into s3:
 string s3 = s1 + s2;
message= "Welcome to C++”
message = message+" and programming is fun";
Therefore, the new message is "Welcome to C++ and programming is fun".
Comparing Strings
 We can use the relational operators ==, !=, <, <=, >, >= to compare two strings. This is
done by comparing their corresponding characters one by one from left to right.

You might also like