Unit Three- Data Types and Operators
Unit Three- Data Types and Operators
These elements define the limits of a language and determine the kind of tasks to which it can be
applied. C++ supports a rich assortment of both data types and operators, making it suitable for a
wide range of programming.
Data types are means to identify the type of data and associated operations of handling it.
C++ provides a predefined set of data types for handling the data it uses. When variables
are declared of a particular data type then the variable becomes the place where the data is
stored and data types is the type of value (data) stored by that variable.
Data type determines the operations that are allowed and the range of values that can be
stored. C++ defines several types of data, and each type has unique characteristics. Because
data types differ, all variables must be declared prior to their use, and a variable declaration
always includes a type specifier. The compiler requires this information in order to generate
correct code. In C++ there is no concept of a “type-less” variable.
A second reason that data types are important to C++ programming is that several of the
basic types are closely tied to the building blocks upon which the computer operates: bytes
and words. Thus, C++ lets you operate on the same types of data as does the CPU itself
hence enabling you to write very efficient, system-level code.
1. Primitive Data Types: These data types are built-in or predefined data types and can be
used directly by the user to declare variables. Example: int, char , float, bool etc.
2. Abstract or user defined data type: These data types are defined by user himself. Like,
defining a class in C++ or a structure.
1
Type Description Example
void associated with no data type
int Whole number integer 3, 8, -10
float used to store numbers having fractional part 10.097
double stores the same data as float but with higher range and precision
Integer data type: (int) variables are used to store integer values like 34, 68704 etc. To
declare a variable of type integer, type keyword int followed by the name of the variable.
Eg int sum;
Float data type: Floating Point data type is used for storing single precision floating point
values or decimal values. For example, statement float average = 2.34;
Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Double variables typically requires 8 byte
of memory space.
Character data type :A variable of type char stores one character. It size of a variable of
type char is typically 1 byte. Eg char name = 'c';
Boolean : A variable of type bool can store either value true or false and is mostly used in
comparisons and logical operations. When converted to integer, true is any non zero value
and false corresponds to zero.
void: Void means without any value. Void data type represents a valueless entity. Used for
functions which do not return a value.
Reflection: Why does C++ have different data types for integers and floating-point
values? That is, why aren’t all numeric values just the same type?
2
C++ supplies different data types so that you can write efficient programs. For example, integer
arithmetic is faster than floating-point calculations. Thus, if you don’t need fractional values,
then you don’t need to incur the overhead associated with types float or double.
Also, the amount of memory required for one type of data might be less than that required for
another. By supplying different types, C++ enables you to make the best use of system
resources.
Finally, some algorithms require (or at least benefit from) the use of a specific type of data.
C++ supplies a number of built-in types to give you the greatest flexibility.
Example programs
cout<<"Age:"<<age<<endl;
cout<<"Salary:"<<salary<<endl; cout<<"Code:"<<code<<endl;
3
#include<iostream.h>
void main(void)
{
const float pi=3.14;//declaration and initialization of variable as const
int rad;
float area;
cout<<"Enter radius of circle:";
cin>>rad;
area=(rad*rad)*pi;//variable is only being accessed and NOT modified
#include <iostream>
using namespace std;
// declaring a constant. It's value cannot be changed.
const int CONST_VAL = 5;
int main()
{
int iValue; // An integer variable
float fValue; // A floating point variable
char cValue; // A character variable
4
cout << "Integer value is: " << iValue << endl;
cout << "Float value is: " << fValue << endl;
cout << "Character value is: " << cValue << endl;
cout << "The constant is: " << CONST_VAL << endl;
return 0;}
#include <iostream>
using namespace std;
int main()
{
float gallons, liters;
return 0;
}
Example: Program to enter two integers and find their sum and average
This program takes in two integers x and y as a screen input from the user. The sum and average
of these two integers are calculated and outputted using the 'cout' command.
#include <iostream>
using namespace std;
5
int main()
{
clrscr();// clears the screen.
int x,y,sum;
float average;
cout << "Enter 2 integers : " << endl;
cin>>x>>y;
sum=x+y;
average=sum/2;
cout << "The sum of " << x << " and " << y << " is " << sum << "." << endl;
cout << "The average of " << x << " and " << y << " is " << average << "." << endl;
return 0;}
4. This program takes in the velocity, acceleration and the time as a screen input from the user.
The final velocity is calculated using the formula v = u + a * t, and then outputted using the
'cout' command.
#include <iostream.h>
using namespace std;
void main()
{
int v,u,a,t;
cout << "Enter the velocity, acceleration, time as integers : " << endl;
cin>>u>>a>>t;
v=u+a*t;
cout << "The final velocity is " << v << "." << endl;
return 0;
}
Exercise
6
1.Write a program that calculates your daily driving cost, so that you can estimate how much
money could be saved by car-pooling, which also has other advantages such as reducing carbon
emissions and reducing traffic congestion. The application should input the following information
and display the user’s cost per day of driving to work:
a) Total kilometres driven per day.
b) Cost per litre of fuel.
c) Parking fees per day.
d) Tolls per day.
2. Write a C++ program that asks for the input of three integers, then calculates the sum, difference
and product of the numbers entered.
3. Write a program that takes in the principal, rate and time as a screen input from the user. It
calculates the simple interest using the formula I = PTR/100.The Principal, Rate, Time and the
simple Interest are then outputted using the 'cout' command.
3.3 Operators
An operator is a symbol that tells the compiler to perform a specific mathematical or logical
manipulation. C++ has four general classes of operators: arithmetic, bitwise, relational, and
logical. C++ also has several additional operators that handle certain special situations. Below is a
look at the main types of operators.
Arithmetic Operators
Are used to carry out arithmetic operations. The operators +, –, *, and / all work the same way in
C++ as they do in algebra. These can be applied to any built-in numeric data type. They can also
be applied to values of type char.
7
The % (modulus) operator returns the remainder of an integer division. Conventionally, when
/ is applied to an integer, any remainder will be truncated; for example, 10/3 will equal 3 in
integer division. To obtain the remainder of this division, you can use the % operator. For
example, 10 % 3 is 1. In C++, the % can be applied only to integer operands; it cannot be
applied to floating-point types.
The following program demonstrates the modulus operator:
// Demonstrate the modulus operator.
#include <iostream>
using namespace std;
int main()
{
int x, y;
x = 100;
y = 3;
cout << x << " / " << y << " is " << x / y <<" with a remainder of " << x % y << "\n";
x = 1;
y = 2;
cout << x << " / " << y << " is " << x / y << "\n" <<
x << " % " << y << " is " << x % y;
return 0;
}
Increment and Decrement
8
The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,
x = x + 1; is the same as x++;
and
x = x - 1; is the same as --x;
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the
operand.
For example,
x = x + 1; can be written as
++x; // prefix form or as
x++; // postfix form
NB: when an increment or decrement operator precedes its operand, C++ will perform the
operation prior to obtaining the operand’s value for use by the rest of the expression. If the
operator follows its operand, then C++ will obtain the operand’s value before incrementing or
decrementing it.
Exercise
Given the following find the value of c, explaining how you arrive at the answer:
i n t a = 6, b = 8;
c = a++ + ++b;
after the assignment statement, the value of b is 7, but will only be used in next execution; the
value of b is 9 since b is pre-incremented, and the value of c is the sum of the original value of a
(6) and the new value of b (9), hence c=15
9
Operator precedence
The logical operators are used to support the basic logical operations AND, OR, and NOT, as
shown in the truth table below:
10
Assignment operator
Represented by single equal sign, (=.): it allows you to create a chain of assignments. Takes
the form var = expression;
Here, the value of the expression is given to var. The assignment operator allows you to create
a chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement. This works because
the = is an operator that yields the value of the right-hand expression. Thus, the value of z =
100 is 100, which is then assigned to y, which in turn is assigned to x. Using a “chain of
assignment” is an easy way to set a group of variables to a common value.
Compound Assignments
C++ provides special compound assignment operators that simplify the coding of certain
assignment statements. Let’s begin with an example. The assignment statement shown here:
x = x + 10; can be written using a compound assignment as x += 10;
The operator pair += tells the compiler to assign to x the value of x plus 10. Here is another
example. The statement
x = x - 100;
11