Section-1 C++ Lab
Section-1 C++ Lab
1.0 Introduction 5
1.1 Objectives 5
1.2 General Guidelines 6
1.3 Some C + + Compilers 6
1.4 Dev C + + IDE 7
1.5 Using Dev C + + IDE 10
1.6 Running Example Programs Using Dev C + + 15
1.7 Session Wise Problems 18
1.8 Summary 22
1.9 Further Reading 22
1.0 INTRODUCTION
Our attempt in this section is to make you familiar with object oriented programming
(OOP) using C + + . We will discuss about how to write and run C + + program. It is
essential for you to practice as much as possible for getting more and more
understanding in the programming and problem solving. So far you have learnt basics
of problem solving and data handling concepts in courses MCS-011 & MCS-023 and
their respective lab work. By now you must have experienced that by experimenting
with the tool/package/programming language, you gain valuable experience and your
efficiency has increased.
the tools you are using for program writing and running,
basic language feature like data types, variables, loops and functions etc.,
understanding of problem and deciding how to go from an idea to code, and
a clear, understanding of OOP features need to be used in specific program.
In this lab course, we have used Dev-C + + , for writing and running the programs.
The Dev-C + + , is developed by Bloodshed Software. It is a full featured graphical
IDE (Integrated Development Environment), which is able to create Windows or
console-based C/C + + programs using the MinGW compiler system. We have also
added practice problems in this section, which you can attempt and enjoy C + +
programming.
1.1 OBJECTIVES
By the end of the practical sessions of this section, you will be able to:
You may seek assistance in doing the lab exercises from the available lab
instructor.
For each program, you should add general comments such as your name date of
programming etc.
Your program should be interactive and properly documented with real Input/
Output data.
There are total 10 lab sessions ( of 3 hours each) for this lab course.
For writing C + + program, you are free to use any C + + compiler and editor
available at your centre/home. If you get opportunity you may experiment with more
than one C + + compilers. In your c programming lab, you might have used Borland
C/C + + compiler. The use of Borland C/C + + compiler is explained to you in
BCSL-021 course. List of some compilers which are avauilable for free download is
given below. You are advised to check their conditions/licenses before using them.
Apple C + + .
Bloodshed Dev-C + + .
Borland C + +
Clang C + + ..
Cygwin (GNU C + + )
Digital Mars C + +
DJ Delorie's C + + development system for DOS/Windows (GNU C + + )
IBM C + + for IBM power, System Z, Bluegene, and Cell.
Intel C + + for non-commercial development Sun Studio.
6
Here you are re-introduced about working with Borland C/C + + compiler. For more C + + Programming
details you may refer to your BCSL-021 course.
The Dev-C + + as available as free software (under GPL). Link to Bloodshed Dev-C
+ + sites is : http://www.bloodshed.net/devcpp.html.
You may download Dev-C + + and should installer put Dev-C + + in the default
directory of C:\Dev-Cpp. Hence, later on installation of add-ons or upgrades can be
easily done.
Dev C + + Installation:
To install Dev-C + + onto your computer , first download the free installation
program, copying it to a folder on youre computer.
When first time you run Dev-C + + , it will ask you for your language.
Chose English as language.
2. Now you may set the default user directory for saving/keeping your C + +
programs.
Under Tools | Environment Options, click the Files & Directories tab.
8 In the "User's Default Directory" field, either type the path of your chice
Leave all other defaults "as is".
Click the Ok button. C + + Programming
3. Before you start using Dev-C + + , you need to modify one of the default
settings to enable you to use debugger with your programs:
In the "Settings" tab, click on "Linker" in the left panel, and change "Generate
debugging information" to "Yes":
Click "OK".
9
C + + Programming
Lab Course 1.5 USING DEV C + + IDE
Here you have to give your project a name. You should give your project a valid and
meaningful filename. The name of your project will also be the name of your final
executable.
A project may have more than one file in it. To add empty source files, follow one of
two ways:
Go to the "File" menu and select "New Source File" (or just press CTRL+N)
You should save your file befor compilation. Note that Dev-C + + will not ask for a
filename for any new source file until you attempt to do any of the following actvity:
1. Compile
2. Save the project
3. Save the source file
4. Exit Dev-C + +
If you are having a pre-existing source files and want to add it to your project . You
can do it with one of two following ways:
Now let us write our first program using Dev C + + . This program is to display
message “Welcome to C + + programming”.
The above program include the statement, "using namespace std;". This line tells the
compiler to use a group of functions that are part of the standard library (std). By
including this line at the top of a file, you allow the program to use functions such as
cout.
Let us try to execute above programe in Dev C + + . Type this program in Dev C + +
IDE. Once you complete the writing, save the file with .cpp extention. Now you
program is ready for compilation.
11
C + + Programming
Lab Course
12
Executing Program in Dev C + + : C + + Programming
If you execute your program, you may notice something peculiar; a console window
will pop up, flash some text and disappear. The problem is that, if programs directly
executed, console program windows close after the program exits.Not that in the
above program system ("PAUSE"); command is used. If this command is not used,
guess what will happen? The program would print the name entered to the screen and
then immediately close without giving you the chance to read what was printed. But
you need to see the result/output of the program. Here is the use of system
("PAUSE"); , it give you a chance to read what was actually printed. You may try
the above program after removing/commenting, system ("PAUSE"); and can observe
the advantage of this command.
For using debugging facility in Dev C + + , you have to first, make sure that you are
using a project.Then follow the following steps:
13
C + + Programming
Lab Course
After that, do a full rebuild (Ctrl-F11), then set breakpoint(s) where you want the
debugger to stop (otherwise it will just run the program).
To set a breakpoint on a line, click on the gutter (the gray band on the left), or press
Ctrl-F5.
Dev-C + + 's basic debugger functions are controlled via the "Debug" tab at the
bottom of the screen. More advanced functions are available in the "Debug" menu of
Dev C + + .
For using Dev C + + debugger functions you may use the following instructions:
Click the "Run to cursor" icon to run your program and pause at the current
source code cursor location.
Click "Next Step" to step through the code.
You can launch the debugger, by pressing F8 or clicking the debug button.
Now you may start debugging. If exection of program goes well, the program
14 will start executing step by step, and then stop at the first breakpoint.
Then you may go through the code, entering function calls, by pressing Shift- C + + Programming
F7 or the "step into" button, or stepping over the function calls, by pressing
F7 or the "next step" button.
You can press Ctrl-F7 or the "continue" button to continue execution till the
next breakpoint.
At any time, you can add or remove breakpoints.
When the program stopped at a breakpoint and you are walking through the
code, you can display the values of various variables in your program by
putting your mouse over them, or you can display variables and expressions
by pressing F4 or the "add watch" button and typing the expression or
variable name.
A debugger basically runs a program while keeping track of its functions, variables
and instructions. It is capable of stopping your program at a given moment, which is
called breakpointing. It is necessary to set a breakpoint. So that the debugger may
know where to stop. If you don't set a break point, the debugger runs the whole
program and stop only after finishing of the program.
In programming, before you try to receive input, you must have a place to store that
input. The input and data are stored in variables. There are several different types of
variables which store different kinds of information. When you tell the compiler you
are declaring a variable, you must include the data type along with the name of the
variable. The vname of variables should be meaningful. This will help you in tracing
and debugging your program. Also if some body eles read your program, proper
variable naming will them to understand your program.
Also using the right variable type is important for making your code readable and and
efficient. You should use appropriate type when declaring variables, as some
variables require more memory than others. For example to store numeric values, a
float may be used to store an "inexact" value and inter may be used to store"exact"
value.
Some time comilatiuon error create problem and irritation to programmer. Usually,
times compilation errors may seem like a small, but as a beginner in C + +
programming, you may not be familiar with the strictness of the format of the program
(the syntax), hence you may tend to run into lots of complaints generated by the
compiler. You avoid many of compilation error and add more clarity to your
program by followinbg some basic principles given below:
15
C + + Programming Just do not start learning C + + programming by compiling the examples. Try to
Lab Course understand the line by line code of examples given in your BCS-031 course or
from some other reference locations.
If there is something, you do not understand about a program, simply make some
changes in the program and see the effect, in two to three attempts, you will come
to know what actually that program is intended to do.
With large and complex advanced programs that interact with the file system and
uses advance features of OOP, you need to be much more careful about
experimental program changes.
Avoid jumping forward while program analysis. If the compiler indicates an error,
or your program is not giving expect result, try to explore why this happened then
try to fix the error. If a program compiles and runs without proper result, take the
time to study each line and its purpose, so that problem can be traced.
Upon reaching the end of main, the closing brace, you C + + program will return
the value of 0 to the operating system. This return value is important as it can be
used to tell the OS whether our program succeeded or not. A return value of 0
means success and is returned automatically.
Declare a variable fefore its use, if you attempt to use a variable that you have not
declared, your program will not be compiled or run, and you will receive an error
message with information that you have made a mistake.
Example1: This program l create a class named Book. This class is having following
private data member:
Title
Author
ISBN
Publisher
Price
Also the Book class is having following member functions to access/display the data
members:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{ int i = 'a';
cout<<"The value of i is:"<<i<<endl;
system("PAUSE");
return (0);
}
You will get error message while compiling, because in this code an integer type
variable i is assigned a character value which is a type mismatch.
17
C + + Programming Now try this program by assigning an integer value to i.
Lab Course
We have allotted ten practical sessions for you to exercise. You have keep all program
document in the file including all the steps involve in solving these problems. You
must take output of pogram and should keep in your file. You are again advised to
come prepared with your design of the following problems on paper in order to take
maximum advantage of the Lab session. You are advised to make assumptions
whereever necessary while solving these problems.
Session 1:
Problem1. Write a program in C + + to find and print the all basic data types of
C++.
Problem 2. Write a program in C + + to explain the use of for loop, while loop,
swith-case, break and continue statements.
Marks 50 70 65 80 56
18
Session 2: C + + Programming
Employee_id
Employee_name
Designation
Employee_Department
Years of experience
and display it on screen using display_info() method.
Session 3:
Problem 8. Write a program in C + + with class Rectangle with the data fields
width, length, area and color .The length, width and area are of double
type and color is of string type .The methods are set_ length () , set_width
(), set_ color(), and find_ area (). Create two object of Rectangle and
compare their area and color. If area and color both are same for the
objects then display “Matching Rectangles” otherwise display “Non
matching Rectangle”.
Problem 9. Create a class Account with two overloaded constructors using C + + .
First constructor is used for initializing, name of account holder, account
number and initial amount in account. Second constructor is used for
initializing name of account holder, account number, addresses, type of
account and current balance. Account class is having methods Deposit (),
Withdraw (), and Get_Balance().Make necessary assumption for data
members and return types of the methods. Create objects of Account class
and use them. Also create appropriate destructors for the Account class.
Session 4:
Problem 11. Write a program in C + + to create a data base with the following
items by using structure/class:
19
C + + Programming Problem 12. Write a program in C + + to create a Player class. Inhermit classes
Lab Course Cricket _Player, Football _Player and Hockey_ Player from Player
class. Create appropriate constructors and destructors for these
classes.
Session 5:
Problem 14. Write a class Bookr and derive classes ReferenceBook and
Magazines from it. Every book has a price, title, author and ISBN
number. Implement conmstructors, destructos and appropriate
methods to manage a Book Stor.
Session 6:
Problem 16. Write a program which read two number ax and y then perform the
following function
a. x + y
b. x - y
c. x * y
d. x / y
20 Problem 19. Write a C + + program to create a class called DATE. Accept two
valid dates in the form dd/mm/yy. Implement the following operations C + + Programming
by overloading the operators + and -. After every operation display the
results by overloading the operator <<.
i. no_of_days=d1-d2; where d1 and d2 are DATE objects.d1>=d2 and
no_of_days is an integer.
ii. d2=d1-no_of_days; where d1 is a DATE object and no_of_days is an
integer.
Problem 20. Write a C + + program to create a class called COMPLEX and
implement the following overloading functions ADD that return a
COMPLEX number.
i. ADD(a, s2)- where a is an integer (real part) and s2 is a complex
number.
ii. ADD(s1, s2)- where s1 and s2 are complex numbers.
Problem 21. Write a C + + program to create a class called MATRIX using a two-
dimensional array of integers. Implement the following operations by
overloading the operator== which checks the compatibility of two
matrices to be added and subtracted. Perform the addition and
subtraction by overloading the operators + and – respectively. Display
the results by overloading the operator<<.
if(m1==m2) {
m3=m1-m2;
m4=m1+m2;
}
else display error
Session 8:
Problem 22. Write a program which designs two classes and the calculate the
division of first class private data with second class private data by
using concept of friend function.
Problem 23. Write a program to calculate following function by using the concept
of virtual function.
F(x) = 7x5 + 9x4 + 6x3 + 2x2 + 4
Session 9:
Problem 24. Two vehicles are running on single track. If the vehicles are running
in opposite direction there is a chance of collision. To avoid collisions
write a C + + program using exception handling. You are free to
make necessary assumptions.
Problem 25. Write a function template palindrome that takes a vector parameter
and returns true or false according to whether the vector does not read
the same forward as backward.
Session 10:
Problem 27 . Implement the case study given in your course BCS-031 Block 3 Unit 4.
21
C + + Programming
Lab Course 1.8 SUMMARY
This lab manual is for supporting the practice of C + + programming skill, based on
BCS-031 course. This manual has detailed out how write and execute C + +
programs. This lab manual started with discussion on need of a tool to write and
execute C + + program. Using of the Dev C + + an IDE for C + + programming is
explained with the help of explaining the steps to take in C + + program execution.
Also how to debug C + + program in Dev C + + is explain in this manual. The best
programming practice make a lot of impact in learing programming skill. This lab
manual has hielighed how to write C + + programs to gain in terms of time saving
and programming skill development. In the last section of this manual, a list of C + +
programming exercised are given, which need to be solved learners by all of you for a
complete understanding.
22