Lab 9 v1
Lab 9 v1
Upon successful completion of this lab the students will be able to:
TOOLS
Code::Blocks or Bloodshed Dev C++
9.1 INTRODUCTION
9.1.1 C++ Programming Language
C++ (pronounced "see plus plus") is a general-purpose Object Oriented Programming
language with high-level and low-level capabilities. It is a statically typed, free-form, usually
compiled language supporting procedural programming, data abstraction, object-oriented
programming, and generic programming. C++ is regarded as a mid-level language. This
indicates that C++ compriss a combination of both high-level and low-level language
features.
In 1983, the name of the language was changed from C with Classes to C++. New features
were added including virtual functions, function name and operator overloading, references,
constants, usercontrolled free-store memory control, improved type checking, and BCPL
style single-line comments with two forward slashes (//). In 1985, the first edition of The C++
Programming Language was released, providing an important reference to the language, as
there was not yet an official standard. In 1989, Release 2.0 of C++ was released. New
features included multiple inheritance, abstract classes, static member functions, const
member functions, and protected members. In 1990, The Annotated C++ Reference Manual
was published. This work became the basis for the future standard. Late addition of features
included templates, exceptions, namespaces, new casts, and a Boolean type.
As the C++ language evolved, a standard library also evolved with it. The first addition to
the C++ standard library was the stream I/O library which provided facilities to replace the
traditional C functions such as printf and scanf. Later, among the most significant additions
to the standard library, was the Standard Template Library.
9.1.3 Code::Blocks
Code::Blocks is a free, open source cross-platform IDE which supports multiple compilers
including GCC, Clang and Visual C++. It is developed in C++ using wxWidgets as the GUI
toolkit. Using a plugin architecture, its capabilities and features are defined by the provided
plugins. Currently, Code::Blocks is oriented towards C, C++, and Fortran. It has a custom
build system and optional Make support.
Code::Blocks is being developed for Windows, Linux, and Mac OS X and has been ported to
FreeBSD, OpenBSD and Solaris. Statements are executed on the basis of conditions.
9.1.4 Basic C++ Program
Program (basic.cpp)
The program starts with the two lines containing sign (#) and the keyword include. These are
known as preprocessor directives. The preprocessor directives are the instructions to the
part of the compiler known as preprocessor which includes some extra files (codes) to the
basic source program. The files iostream and conio.h are known as the header files which
contain the definitions of some functions. The iostream header file contains the definition of
standard input/output streams like, cout and cin where as conio.h header file includes the
definitions of function getch(), getche() and others. Simply speaking the preprocessor
directive #include is responsible for including the contents of the header files into the source
file.
using namespace std enables a program to use all the names in any standard C++ header
(such as <iostream>) that a program might include.
The main() is the function as the function is always along with the parentheses. The main()
function is the first executable function in any C++ program. No matter where the main()
function is located always the first precedence goes to the main() function and its contents.
The contents of main function are enclosed in curly braces
The braces “{ “and “}” also known as curly braces, enclose the block of code present in any
function. “{“ is known as the opening brace and ”}” is known as closing brace. Opening brace
shows the starting of the main or any function and closing brace shows the ending of the
main or any function. The code of each and every function is always enclosed in the curly
braces.
The cout<<”My name is Ali” tells the computer to print the string constant “My name is Ali” on
the console screen. The cout is the standard output stream which directs the flow of data to
the console screen. What ever written in the double quotations in cout statement is printed
as it is on the console screen. Every C++ statement must end with a semicolon (also known
as the statement terminator). Preprocessor directives (like #include) do not end with a
semicolon.
The getch() (get character) function waits to get the character from keyboard. If you run your
program without using getch() your program will show the result in just one blink and will
vanish out quickly. So to make the output console screen stop in order to examine the
results clearly we use getch() function. The definition of the function getch() is present in the
header file “conio.h”.
When the return statement is used at the end of main, the value 0 indicates that the program
has terminated successfully.
The output of basic.cpp on the console screen may look like as shown in below figure:
9.1.5 Functions
Functions are the one of the fundamental building blocks of C++ language. The functions
are the sub programs which contain some block of code inside the curly braces. The code
enclosed inside the curly braces is known as the body of the function. The functions always
start with the return type and the function name followed by the parenthesis. The
parentheses tell the compiler that it is a function not a variable or any other thing. The block
of code present in any function can be executed at any place by calling that function at that
point in the program. Any C++ program can contain number of functions or at least one i.e.
main(). All the C++ programs always contain the main() function, because it is the gateway
to enter in C++ and no program can run with out main() function.
In main.cpp, the main() is only the function present. It contains the block of three line code.
This three line code present in main() is always executed first in this program, because the
contents of the main() functions have the highest precedence as compared to the contents
of other functions.
9.1.6 Statements
Statements are the instructions to the computer to work accordingly. All the statements are
always terminated with the terminator “;”. This semicolon is known as terminator because it
terminates the statement and tells the compiler that the statement has ended. If we don’t
give the terminator at the end of any statement, the compiler will think that the statement is
still going on and will mix another statement or code with it hence giving an error. In
main.cpp, there is only one statement cout<<”My name is Ali”; it just tells the computer to
print the string constant present in quotation marks on the console screen. So every
statement is the instruction to the computer and do remember to place the terminator at
the end of each and every statement.
The preprocessor directives are always started with the “#” (hash/pound) sign which tells the
compiler that the thing that you are compiling is a preprocessor directive which is different
from other. And the header files are always enclosed in “< >” angle brackets following the
keyword include but in some cases it is enclosed in double quotation marks. If you enclose
the header file in the angle brackets it will start the search for the header file in the standard
INCLUDE directory.
#include <iostream>
But when you want to include the user defined header file the header file is enclosed in
quotation marks.
#include “ali.h”
The quotation marks tells the compiler to start the search for the header file in the current
directory—the directory usually containing the source files.
In main.cpp, there are two header files included in the source program. One is iostream
which contains the definitions of standard input and output streams like, cout and cin. The
other header file is conio.h which contains the basic definition of the functions like, getch(),
getche(), etc.
In above syntax the keyword cout tells the compiler that it is a standard output stream and
treat it as accordingly. The text in the double quotation marks ”My name is Ali” is the string
constant and is printed on the console screen as it is. The operator << is known as insertion
or put to operator. It directs the contents of the variable on its right to the object on its left.
The insertion operator can be used multiple times in single cout statement and it is perfectly
legal as in below statement:
Except printing the string constants, the situation also come in which we have to print out
the values of certain variables on the console screen then we can use the variable name in
cout statement to print its value on the console screen as in below statement:
As the cout is a statement therefore each and every cout statement should be terminated
with the terminator “;”. Let’s examine the following program:
The above program’s code contain three cout statements. The first cout statement prints the
string constant “My name is Memona.” on the screen as it is where as “\n” is the escape
sequence which moves the cursor to the new line so that the coming line will be printed on
the fresh line. Then the next cout statement flows the string constant ”I teach in MTE
department.”; to the console screen on the new line. In the last cout statement we face a
new unfamiliar word endl, it is known as the manipulator. The manipulators are the
instructions to the output stream which modify or manipulate the way the data is displayed
in the console screen. The manipulator endl has the same effect of causing a linefeed as
the \n has but it is somewhat clearer. The endl manipulator also causes the buffer to be
flushed. So, on conclusion the third cout statement in main.cpp, flows the string constant ”I
live in Hyd.” to the console screen on new line.
9.1.10 Inputting with cin
The identifier cin is an object which is predefined in C++. The cin statement is responsible
for getting input and passing for processing during the run-time. The simplest structure of
cin statement is:
cin>>number;
In above syntax the keyword cin tells the compiler that it is a standard input stream and treat
it as accordingly. The operator >> is known as extraction or get from operator. It takes the
value from stream object on its left and places it in the variable on its right. Let’s examine
the following program
The above program first initializes that the variables a, b and Ans contain the integer data
type values. The first cout statement sends the message to enter first number from your
keyboard and when you enter any number, the cin statement places that number in the
variable a. Then the program gives another message to enter second number and when you
enter any number that will be placed in the variable b. The statement Ans=a+b then adds
the two numbers and places the result in the variable Ans. Finally the last cout statement
shows the addition of both numbers.
9.1.11 Comments
Commenting is very effective feature in any programming language as it makes the source
program user friendly up to some extent. Comments are un-executable lines in any source
program. Comments make the program more readable and understandable to the user or
even an unknown reader. They help the programmer to make him remember that for this
purpose you have written this portion of code. And also if a person is unfamiliar with the
program, the comments will help him by telling him what is happening in a certain line or
portion of the program. When you write a program and suppose you are not in touch with it
for a two or three months so when you come back to your program after such a long period
you will forget that for what I had written it and what it tell? So if you had given the
comments in your program you would not be in such a great trouble.
In small programs it is not a huge problem to forget some code lines but in case of working
on some programs having hundreds or thousands of code line or working on a project you
have to deal with several different blocks of codes so, in these situations there are a lot of
chances to forget the construction of your own program. So here the comments play their
key role. // /*………………………….*/
There are two ways to comment in C++ source file. The first way it to start comment with the
two back slashes “//” , this causes the compiler to consider the whole line as a comment. The
other way is to start the comment with a back slash and an asterisk “/*” and terminate the
comment with an asterisk and back slash “*/”, which cause the certain block of line as a
comment.
The first way only make a single line as a comment but if we want to make the 100 lines as
the comment then we can not use the double backslashes “//” hundred of times. But at this
situation the second way suites very well in which we will place “/*” the starting of the
comment and “*/” at the ending of the comment.
Examine the following program:
9.1.12 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 situation. 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 Var1.
Some valid identifiers are: Var, var, VAR, Var1, VAR1, Var_one, _Var1, _Var_one_of_one etc.
Hint: The standard and easy way to declare the identifier is to declare all characters of its in
lower case like, var1, var2 etc.
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 whereas 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 as defining a variable. The line below illustrated the concept of defining a variable:
int var1=50;
In above 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.
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.
The numeric data having no fractional/decimal part is known as integer data. The integer
data type variables can only store and represent integer data. The integer data type is of
three types i.e. type int, type short and type long.
Type int occupies 4 bytes (32 bits) of memory. In type int you can store the integers with in
the rage of -2,147,483,648 to 2,147,483,647. To define or declare a type int variable use the
keyword int before the variable name like,
Type short occupies 2 bytes (16 bits) of memory. In type short you can store the integers
within the range of -32,768 to 32,767. To define or declare a type short variable use the
keyword short before the variable name like,
short var1=10;
Type long occupies 4 bytes (32 bits) of memory. In type long you can store the integers with
in the rage of -2,147,483,648 to 2,147,483,647. To define or declare a type long variable use
the keyword long before the variable name and place the letter L after the integer constant
like,
long var1=1000000000L;
The numeric data having fractional/decimal part is known as floating point data. The floating
point data 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.
Type float occupies 4 bytes (32 bits) of memory. In type float you can store the floating point
values within 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,
Type double occupies 8 bytes (64 bits) of memory. In type double you can store the floating
point values within 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 within 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
52349.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.
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:
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,
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.
The data types int, short, long and char have their range with in which they can store certain
values and these ranges start from some negative number to positive number. So by
eliminating negative numbers we can extend the size of the data types. Doing this will make
the data types to store large values as twice as the signed data types do.
The unsigned data types are used when we are dealing with only positive numbers. To
convert a signed data type into an unsigned data type place the keyword unsigned before
the data type as in,
Type unsigned char occupies 1 byte (8 bits) of memory. In type unsigned char you can store
the characters within the range of integers 0 to 255, whereas the integers 0 to 255 represent
the ASCII equivalents to the characters. To declare an unsigned data type variable use
keywords unsigned char before the variable name as in,
Type unsigned short occupies 2 bytes (16 bits) of memory. In type unsigned short you can
store the integers within the range of 0 to 65,535. To declare an unsigned short data type
variable use the keywords unsigned short before the variable name as in,
Type unsigned int and type unsigned long occupy 4 bytes (32 bits) of memory. In both the
data types you can store the integers within the range of 0 to 4,294,967,295. To declare an
unsigned int and unsigned long data type use the keywords unsigned int and unsigned long
respectively before the variable names as in,
var1=10000;
char 0 255 1
short 0 65,535 2
int 0 4,294,967,295 4
long 0 4,294,967,295 4
It specifies that the variable PI stores the floating point number 3.1415 and this value will not
be altered and will remain constant.
are the assignments statements which assign the values to the variable var1. The assignment
statements assign the value from the right of the = sign to the variable on the left. To assign
a variable it must be noted that the variable must be declared before it is assigned.
a=a+b; b=b-10;
var1=var1*50;
var1=var1/var2;
In C++ a=a+1; and a+=1; have the same effects. Some other equivalents are,
electrons=electrons%1;
== Equal to
!= Not equal to
And && operator combines the Boolean values and makes the condition satisfied only when
all the comparisons are satisfied as,
OR || operator combines the Boolean values and makes the condition satisfied when atleast
one comparison becomes true as,
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
postfix
In first two line codes the value of the variable “ans” is incremented first and then it is
printed on the console screen but in the second two line codes the value of the variable
“ans” is first printed on the console screen and then it is incremented the one. Operators
used as prefix and as postfix behave differently.
In C++,
9.2 PROCEDURE
9.2.1 Problem example
Consider the following problem example. We are going to write C++ source code in
Code::Blocks IDE.
Problem statement: Write a program in C++ that accepts the width and the height of a
rectangle from the user and prints the area of the rectangle.
Step 06: Press button and create a new file with .cpp extension by choosing the
destination location of the file.
Step 10: Debug any error in the code and recompile it.
2. Write a statement (or comment) to accomplish each of the following (assume that
using directives have been used for cin, cout and endl ):
3. Using the statements, you wrote in Exercise 2, write a complete program that
calculates and displays the product of three integers. Add comments to the code
where appropriate. [Note: You’ll need to write the necessary using directives.]
4. Write a program that asks the user to enter two numbers, obtain the two numbers
from the user and print the sum, product, difference, and quotient of the two
numbers.
a. cout << x;
b. cout << x + x;
c. cout << "x=";
d. cout << "x = " << x;
e. cout << x + y << " = " << y + x;
f. z = x + y;
g. cin >> x >> y;
h. // cout << "x + y = " << x + y;
i. cout << "\n";
6. Write a program that prints the numbers 1 to 4 on the same line with each pair of
adjacent numbers separated by one space. Do this several ways:
7. Write a program that reads in the radius of a circle as an integer and prints the
circle’s diameter, circumference and area. Use the constant value 3.14159 for π. Do
all calculations in output statements.
Create a BMI calculator application in C++ that reads the user’s weight in pounds and
height in inches (or, if you prefer, the user’s weight in kilograms and height in meters),
then calculates and displays the user’s body mass index.