ITP Lab 3
ITP Lab 3
________________________________________________________________________
PERFORMANCE OBJECTIVE
Upon successful completion of this experiment, the student will be able to learn:
VARIABLES, DATA TYPES AND CONSTANTS
Discussion
Lets start the discussion with Tokens:
Tokens are the minimal chunk of program that have meaning to the compiler –the smallest
meaningful symbols in the language. Our code displays all 6 kinds of tokens as shown in Table 1,
though the usual use of operators is not present here:
Table 1: C++ Tokens
Operators
We can perform arithmetic calculations with operators. Operators act on expressions toform a
new expression. For example, we could replace "Hello, world!\n" with (4 + 2) / 3, which would
cause the program to print the number 2. In this case, the + operator acts on the expressions 4
and 2 (Its operands).
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
Operator types:
• Mathematical: +, -, *, /, and parentheses have their usual mathematical meanings,
including using -for negation. % (the modulus operator) takes the remainder of two numbers:
6%5 evaluates to 1.
• Logical: used for “and,” “or,” and so on. More on those in the next lecture.
• Bitwise: used to manipulate the binary representations of numbers. We will not focus
on these.
VARIABLES
The basic definition of the variable says that the variables are those memory locations whose value can be
varied/altered according to the particular situations. Like in other programming languages variables are one of
the major building blocks of C++ programming language. The variables set the location into the memory and
give it certain name so you can store certain value and access the particular location of memory. The name
given to the variable is known as identifier. It is so called because it identifies/indicates certain memory
location. In C++ programming language there are certain rules for identifiers so, being in the boundary of
those you can declare an identifier.
1) The identifier can contain letters form a-z, numbers form 0-9 and an underscore sign.
2) The identifier can be in upper or lower case but the variable in upper case will differ from the variable in
lower i.e. ANS is not same as ans or Ans.
3) The first character of the identifier must be letter or an underscore sign.
4) The identifier should not contain any space (white space) within it.
5) You can also give underscore sign in the middle of the identifier as an space for your ease for example,
square_inch.
6) The identifier must not be same as the keywords—the words predefined in C++ which have their own
specific meaning and function. Like, main, void, return, cout, cin etc. are keywords so the identifier
should not be like them.
7) The identifier can be as long as you like, but only the first 247 characters (in Visual C++) or 250
characters (in C++ Builder) will be recognized.
8) The identifier must be unique through out the program i.e. if you have declared the identifier Var1 so, to
access or call it you must give its same name i.e. Var1.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
Some valid identifiers are:
You might think that the two words declaring and defining are equivalent but in fact there is a lot of difference
between both of them. The declaring is the process of giving a name to the variable and its data type. The data
type means that which type of value will be stored in that variable where as the name of the variable must
follow the identifier rules of C++.
int var1;
The above line is an example of declaring a variable in which the variable is given the name var1 and integer
data type declared for it which tells the computer that the value stored in the variable var1 must be an
integer.
Whereas the process of initializing certain value to the variable at the time of declaration is referred to as
defining a variable. The line below illustrated the concept of defining a variable:
int var1=50;
In a
bove line the variable var1 is initialized with the integer value 50.
In defining a variable we set/initialize some values to the variable before the compiling.
Memory Memory
50
var1 var1
Variable Declared Variable Defined or assignment done
int var1; int var1=50;
Examine the below program (Var.cpp) which initializes and declares some variables:
Program (Var.cpp)
#include <iostream.h>
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
#include <conio.h>
void main()
{
clrscr();
int mixture;
int ethane=5, methane=8, propane=2;
mixture=(ethane + methane + propane);
getch();
}
The above program starts with two preprocessor directives which include two header files which contain
definitions of some functions and keywords as, cout and getch(). Then in main function one variable mixture is
declared and three variables ethane, methane and propane are defined. The first variable mixture is only
declared as it is only given the name and its data type and no value is set in the memory location of the
variable. Where as in the second variable initialization statement the memory location is set for the three
variables and a certain value is initialized to the memory location of the variables. The last four cout
statements prints the values of the variable stored in to them on the console screen with some strings.
Input
Now that we know how to give names to values, we can have the user of the program input values. This is
demonstrated below:
Program (cin.cpp)
#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int x;
cin>>x;
cout<<x/3<<’ ‘<<x*2<<’ ‘<<x%4;
return 0;
}
Data Types
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
Every expression has a type – a formal description of what kind of data its value is. For
instance,0 is aninteger,3.142 is a floating-point (decimal) number, and "Hello, world!\n" is a
string value(a sequence of characters). Data of different types take a different amounts of
memory to store. Here are the built-in datatypes we will use most often:
• A signed integer is one that can represent a negative number; an unsigned integer will
never be interpreted as negative, so it can represent a wider range of positive numbers. Most
compilers assume signed if unspecified.
• There are actually 3 integer types: short, int, and long, in non-decreasing order of
size(int is usually a synonym for one of the other two). You generally don’t need to worry about
which kind to use unless you’re worried about memory usage or you’re using really huge
numbers. The same goes for the 3 floating point types,float, double, and long double, which are
in non-decreasing order of precision (there is usually some imprecision in representing real
numbers on a computer).
• The sizes/ranges for each type are not fully standardized; those shown above are the
ones used on most 32-bit computers.
An operation can only be performed on compatible types. You can add 34 and 3, but you can’t
take the remainder of an integer and a floating-point number.
An operator also normally produces a value of the same type as its operands; thus, 1/4
evaluates to 0 because with two integer operands, / truncates the result to an integer. To get
0.25, you’d need to write something like 1 / 4.0.
Program (integer.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=10000;
long b=20000;
short c=5;
cout<<”Integer = ”<<a<<endl;
cout<<”Long = ”<<b<<endl;
cout<<”Short = ”<<c;
getch();
}
FLOATING POINT DATA TYPE
The numeric data having fractional/decimal part is known as floating point data. The floating point data type
variables can store and represent floating point data. The floating point data type is of three types i.e. type
float, type double and type long double.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
Type float occupies 4 bytes (32 bits) of memory. In type float you can store the floating point values with in the
range of 3.8 x 10-38 to 3.8 x 1038 with the precision of seven (7) digits. To define or declare a type float variable
use the keyword float before the variable name and place the letter F after the floating point constant like,
The other two floating point data types are same as type float but they offer wider range of values and
precisions.
Type double occupies 8 bytes (64 bits) of memory. In type double you can store the floating point values with
in the range of 1.7 x 10-308 to 1.7 x 10308 with the precision of fifteen (15) digits. To define or declare a type
double variable use the keyword double before the variable name like,
double PI=3.141592654;
Type long double occupies 10 bytes (80 bits) of memory. In type long double you can store the floating point
values with in the range of 1.2 x 10-4932 to 1.2 x 104932 with the precision of nineteen (19) digits. To define or
declare a type long double variable use the keyword long double before the variable name and place the letter
L after the floating point constant like,
In floating point data types you can write the floating point constants using exponential notation, which is the
way to write very large or very small numbers in the power of ten. Like instead of writing 2,000,000,0 you can
write 1.0E7 in exponential notation. Similarly, for 52347.2 you can write 5.2E4 and for 0.0000006024 you can
write 6.02E-7.
double atoms=6.02E-7;
If you want to define a floating point variable then in type float place a letter F in the end of the constant
number, in type double you don’t have to identify the complier that it is a constant value it considers it as
default but in type long double you have to place the letter L after the constant number. But placing F and L is
optional.
float PI=3.1415F;
double PI=3.141592654;
long double PI=3.141592654546845348645454L;
You can also make the value of the floating point variable constant through out the function by using the
constant qualifier i.e. const. To define a constant floating point variable place the keyword const before the
data type of the variable as in:
________________________________________________________________________
Program (area.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
const float PI=3.14F;
int radius;
float area;
cout<<”Enter the radius of the circle: ”;
cin>>radius;
area=PI*(radius*radius);
cout<<”The area of the circle is: ”<<area;
getch();
}
This program defines the constant value of the variable PI and declares the integer variable radius and a type
floa
t variable area. The program gets the value of radius during the run-time in integer type and then puts it in the
expression area=PI*(radius*radius) and calculates the value of area and finally shows the value of area.
The data containing individual characters is known as character data. The character data type variables can
only store and represent the characters. The character data type variables can only store single character at a
time in a single variable.
Type char occupies 1byte (eight bits) of the memory. In type char you can store the characters within the
range of integers -128 to 127, whereas the integers -128 to 127 represent the ASCII equivalents to the
characters. To declare a character data type use keyword char before the variable name as in,
char ch;
The above declaration indicates that the variable ch is a character type data variable and in the program it will
only store the characters. And to define a variable you can either give the character in single quotation marks
or you can give the ASCII equivalent to that character. For example if we want to store the character A (capital
A letter) in the variable ch then we can write as in,
char ch=’A’;
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
char ch=65;
In first line the character A is enclosed in single quotation marks so the character A will be store in the variable
ch where as in second line the number 65 is the ASCII equivalent to the character A so the computer will
translate it in to character A and will store it in the variable ch. No matter which method you perform the aim
of both the methods is same.
Program (char.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char ch;
The keyword const is known as the constant qualifier. It specifies that the value of the variable will remain
constant and will not be altered throughout the function. If any attempt is made to alter the value of the
variable the compiler will give the error. It is always placed before the data type of the variable as in,
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
It specifies that the variable PI stores the floating point number 3.1415 and this value will not be altered and
will remain constant.
Program (const.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
const int a=15;
int b=10,c;
b=b+1;
c=a+b;
cout<<c;
getch();
}
Debugging
Two types of error may occur in C++ program:
Compilation errors and
Runtime errors.
Compilation errors are problems raised by the compiler, generally resulting from violations of the syntax rules
or misuse of types. These are often caused by typos and the like.
Runtime errors are problems that you only spot when you run the program: you did specify a legal program,
but it doesn’t do what you wanted it to. These are usually trickier to catch, since the compiler won’t tell you
about them.
EXERCISE
1. Write a program that will compute the area of a circle. The user must enter the radius of the circle.
Use the following formula for area A=3.14*R^2?
2. Write a program that will solve for the power dissipation of a resistor when the voltage across the
resistor and the current in the resistor are known. The relationship for the power dissipation is:
P=I^2*R?
3. Write a program that displays on screen the memory size of variable of different data type?
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
Hint: Make use of “size of()” function
4. Develop a program that will convert the temperature from degree Celsius to degree Fahrenheit.
User input the temperature in Celsius. The relation is F=5/9*C+32?
5. So far, we have learned how to declare and define simple functions. Now
write a program that calculates an item’s purchase price based on the item’s
store price added the tax. The tax rate is a percentage value. This means a
tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 =
0.075). The tax amount collected on a purchase is taken from an item’s price;
its formula is:
6. Write a program that asks student to enter marks of five subjects: Applied physics, ITP, Calculus,
English and professional ethics out of hundred. The program should display total percentage in the
output.
(b) Add the missing statements to complete the following code and Predict the output.
Void main()
Long x,y,z;
X=y=z=4;
X +=2;
Y -=1;
Z *=3;
Cout << x <<” “<< y << “ “ << z;
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 3
ST
________________________________________________________________________
8. Execute the following code step-by-step using “F8 key” and observe how the integer variables are
declared, initialized and modified in the program.
(a)
#include <iostream.h>
void main()
{
int i=0;
int j=1;
cout<<”i=“<<i<<”j=“<<j<<endl;
i=10;
j=20;
cout<<”i=“<<i<<”j=“<<j<<endl;
}
(b): In the above code do the following changes:
int i=0;
int j=1;
to
const int i=0;
const int j=1;
now compile it and find out the errors and try to understand the cause of the errors. Also mention whether
the errors are Compilation or Runtime.
LAB SUBMISSION
LAB MUST BE SUBMITTED ON OR BEFORE 14TH DEC 2016