0% found this document useful (0 votes)
115 views15 pages

Describe The Steps in Compiling and Executing A C++ Program With Programmatic Illustration

The three steps in executing a C++ program are: 1) Compiling the source code into object code. 2) Linking the object code and library files to create an executable file. 3) Running the executable file to execute the program statements. Some common errors that may occur during compilation are syntax errors, logical errors, and linker errors. Runtime errors occur during program execution. Selection control statements in C++ include if-else statements and switch statements. If-else statements allow for conditional execution based on boolean expressions, and can be nested. Switch statements provide an alternative to nested ifs when checking different cases of the same variable.

Uploaded by

Kuldeep Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views15 pages

Describe The Steps in Compiling and Executing A C++ Program With Programmatic Illustration

The three steps in executing a C++ program are: 1) Compiling the source code into object code. 2) Linking the object code and library files to create an executable file. 3) Running the executable file to execute the program statements. Some common errors that may occur during compilation are syntax errors, logical errors, and linker errors. Runtime errors occur during program execution. Selection control statements in C++ include if-else statements and switch statements. If-else statements allow for conditional execution based on boolean expressions, and can be nested. Switch statements provide an alternative to nested ifs when checking different cases of the same variable.

Uploaded by

Kuldeep Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

1. Describe the steps in compiling and executing a C++ program with programmatic illustration.

There are three steps in executing a c++ program: Compiling, Linking and Running the program.
The c++ programs have to be typed in a compiler. All the programs discussed in the book will be
compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor to type and edit
c++ program. After typing the program the file is saved with an extension .cpp. This is known as
source code. The source code has to be converted to an object code which is understandable by
the machine. This process is known as compiling the program. You can compile your program
by selecting compile from compile menu or press Alt+f9. After compiling a file with the same
name as source code file but with extension .obj. is created.
Second step is linking the program which creates an executable file .exe (filename same
as source code) after linking the object code and the library files (cs.lib) required for the
program. In a simple program, linking process may involve one object file and one library file.
However in a project, there may be several smaller programs. The object codes of these
programs and the library files are linked to create a single executable file. Third and the last
step is running the executable file where the statements in the program will be executed one
by one.
When you execute the program, the compiler displays the output of the program and
comes back to the program editor. To view the output and wait for user to press any key to
return to the editor, type getch() as the last statement in the program. Getch() is an inbuilt
predefined library function which inputs a character from the user through standard input.
However you should include another header file named conio.h to use this function. Conio.h
contains the necessary declarations for using this function. The include statement will be similar
to iostream.h.

Compiling and Linking

During compilation, if there are any errors that will be listing by the compiler. The errors may
be any one of the following

1. Syntax error
This error occurs due to mistake in writing the syntax of a c++ statement or wrong use of
reserved words, improper variable names, using variables without declaration etc. Examples
are : missing semi colon or paranthesis, type integer for int datatype etc. Appropriate error
message and the statement number will be displayed. You can see the statement and make
correction to the program file, save and recompile it.

2. Logical error
This error occurs due to the flaw in the logic. This will not be identified by the compiler.
However it can be traced using the debug tool in the editor. First identify the variable which
you suspect creating the error and add them to watch list by selecting Debug ->Watches->Add
watch. Write the variable name in the watch expression. After adding all the variables required
to the watch list, go to the statement from where you want to observe. If you are not sure, you
can go to the first statement of the program. Then select Debug ->Toggle Breakpoint (or press
ctrl + f8). A red line will appear on the statement. Then Run the program by selecting Ctrl + f9 or
Run option from run menu. The execution will halt at the statement where you had added the
breakpoint. The watch variables and their values at that point of time will be displayed in the
bottom in the watch window. Press F8 to execute the next statement till you reach the end of
the program. In this way you can watch closely the values in the watch variables after execution
of each and every statement in the program. If you want to exit before execution of the last
statement press Ctrl + Break. To remove the breakpoint in the program go to the statement
where you have added breakpoint select Debug ->Toggle Breakpoint (or press ctrl + f8). Select
Debug -> watch ->remove watches to remove the variables in the watch list. This tool helps in
knowing the values taken by the variable at each and every step. You can compare the
expected value with the actual value to identify the error.
3. Linker error
This error occur when the files during linking are missing or mispelt

4. Runtime error
This error occurs if the programs encounters division by zero, accessing a null pointer etc during
execution of the program

2. Describe the theory with programming examples the selection control statements in C++.

If s t a t e m e n t

S y nt ax : if (expression or condition)
{ statement 1;
statement 2;
}
else
{ statement 3;
statement 4;
}
The expression or condition is any expression built using relational operators which
either yields true or false condition. If no relational operators are used for comparison, then the
expression will be evaluated and zero is taken as false and non zero value is taken as true. If the
condition is true, statement1 and statement2 is executed otherwise statement 3 and statement
4 is executed. Else part in the if statement is optional. If there is no else part, then the next
statement after the if statement is exceuted, if the condition is false. If there is only one
statement to be executed in the if part or in the else part, braces can be omitted.

Following example program implements the if statement.


// evenodd.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int num;
cout<<  Please enter a number  <<endl;
cin>>num;
if ((num%2) == 0)
cout<<num <<  is a even number  ;
else
cout<<num <<  is a odd number  ;
getch();
}
The above program accepts a number from the user and divides it by 2 and if the
remainder (remainder is obtained by modulus operator) is zero, it displays the number is even,
otherwise as odd. We make use of the relational operator == to compare whether remainder is
equal to zero or not.

N ested I f statement

If statement can be nested in another if statement to check multiple conditions.


If (condition1)
{ if (condition 2)
{ statement1;
Statement2;
}
else if (condition3)
{statement3;
}
}
else statement4;
The flowchart of the above example is shown below

Multiple conditions can be checked using logical & & operator(AND) and || operator (OR).
If ((condition1) && (condition2))
statement1;
else
statement2;
In the above example statement1 will be executed if both the condition1 and condition2 are
true and in all other cases statement2 will be executed.
If ((condition1 || (condition2))
statement1;
else
statement2;
In the above example statement1 will be executed if either condition1 or condition2 are
true and even if both are true. Statement2 will be executed if both the conditions are false. The
following program demonstrates the use of && operator and nested if statement.
//Large.cpp
# include <iostream.h>
void main()
{ int a,b,c;
cout<<  Please enter three numbers ;
cin>>a>>b>>c;
if ((a>b) && (b>c))
cout<<a<<  is the largest number ;
else if ((b>a) && (b>c))
cout<<b<<  is the largest number ;
else if ((c>a) && (c>b))
cout<<c<<  is the largest number ;
}
The above program accepts three numbers from the user and displays which is the
largest number among the three.( assumption is that all the numbers are unique, the program
has to be modified if you would like to allow same number twice)

B) switch statements

Ans

S witch statement
Nested ifs can be confusing if thei f statement is deeply nested. One alternative to
nestedi f is the switch statement which can be used to increase clarity in case of checking the
different values of the same variable and execute statements accordingly.
S y nt ax :
Switch (variablename)
{ case value1: statement1;
break;
case value2: statement2;
break;
case value3: statement3;
break;
default: statement4;
}

If the variable in the switch statement is equal to value1 then statement1 is executed, if
it is equal to value2 then statement2 is executed, if it is value3 then statement3 is executed. If
the variable value is not in any of the cases listed then the default case statement or
statement4 is executed. The default case specification is optional, however keeping it is a good
practice. It can also be used for displaying any error message. Each case can have any number
of statements. However every case should have a break statement as the last statement. Break
statement takes the control out of the switch statement. The absence of the break statement
can cause execution of statements in the next case. No break is necessary for the last case. In
the above example, default case does not contain a break statement.
The flowchart for the switch statement is shown below
The following program implements the switch statement
position.cpp
# include<iostream.h>
void main()
{ char pos;
int x=15, y=15;
cout <<  you are currently located at  <<x<<  <<y<<endl;
cout>>  please choose the letter to move l for left, r for right, u for up and d for down  <<endl;
cin>>pos;
switch (pos)
{ case  l  : x  ;
break;
case  r  : x++;
break;
case  u  : y++;
break;
case  d  : y  ;
break;
default: cout<<  You selected a wrong option ;
}
cout<<  you are now located at  <<x<<  <<y;
}
The above program asks the user to enter l,r,u,d for allowing him to move left,right,up
and down respectively. The position is initialised to 15 and 15 which are x and y coordinates of
his position. Depending upon the what user has selected the the x and y co-ordinates are
incremented or decremented by one(x++ is same as x=x+1). If the user types a letter other than
l,r,u,d, he gets an error message. Since the switch variable is a character, l,u,r,d and enclosed
within single quote.
++ and  operator can be used as postfix or as prefix operator which has no effect if
used as an independent statement. However if it used as part of an expression, the prefix
operator will be operated and then the expression will be evaluated whereas the postfix
operated will be evaluated later.
For example in the statement x= a+ (b++), a will be added to b and then stored in x and
then the value of b will be incremented. If the same expression is written as x=a+(++b), the the
b will be incremented and then added to a and stored in x.

3. Given a RxC Matrix, A, i.e. R rows and C columns we define a Saddle-Point as


Saddle_Pt (A(i,j)) = A(i,j) is the minimum of Row i and the maximum of Col j.
e.g.
123
456
789
-- 7 is Saddle_Pt. at position (3,1)
Write a program in C++ to check and print for saddle points in a matrix.

Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][3],i,j,k,sp,minr,pos,flag=1;
cout<<"Enter the contents of the array ";
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
cin>>a[i][j];
}
cout<<"
The matrix representation of array is: ";
for(i=0;i<3;i++)
{cout<<"
";
for(j=0;j<3;j++)
cout<<a[i][j]<<" ";
}
cout<<endl;
for(i=0;i<3;i++)
{
flag=1;
sp=a[i][0],pos=0;
for(j=1;j<3;j++)
{if(a[i][j]<sp)
{ sp=a[i][j];
pos=j;
}
}
for(k=0;k<3;k++)
{if(a[k][pos]<sp)
{
flag=0;
break;
}
}
if(flag==1)
cout<<"The saddle point of row "<<i+1<<" is "<<sp<<endl;
}
getch();
}

4. Describe and Demonstrate the concept of Pass by Value and Pass By Reference using
appropriate programming examples of your own.

Ans.
Pass by Valu e
Consider a pair of C++ functions defined in Program. The function One calls the function Two. In
general, every function call includes a (possibly empty) list of arguments. The arguments
specified in a function call are called actual parameters . In this case, there is only one actual
parameter y.
void Two(int x)
{x=2;
cout << r << endl;
}
void One()
{int y=1;
Two(y);
cout << y << endl;
}
Program: Example of Pass-By-Value Parameter Passing
The method by which the parameter is passed to a function is determined by the function
definition. In this case, the function Two is defined as accepting a single argument of type int
called x. The arguments which appear in a function definition are called formal parameters . If
the type of a formal parameter is not a reference , then the parameter passing method is pass-
by-value.
The semantics of pass-by-value work like this: The effect of the formal parameter definition is
to create a local variable of the specified type in the given function. E.g., the function Two has a
local variable of type int called x. When the function is called, the values (r-values) of the actual
parameters are used to initialize the formal parameters before the body of the function is
executed.
Since the formal parameters give rise to local variables, if a new value is assigned to a formal
parameter, that value has no effect on the actual parameters. Therefore, the output obtained
produced by the function One defined in Program is:
2
1
Pass by Ref eren ce

Consider the pair of C++ functions defined in Program . The only difference between this code
and the code given in Program is the definition of the formal parameter of the function Two: In
this case, the parameter x is declared to be a reference to an int. In general, if the type of a
formal parameter is a reference, then the parameter passing method is pass-by-reference .
void Two(int& x)
{x=2;
cout << r << endl;
}
void One()
{int y=1;
Two(y);
cout << y << endl;
}
Program: Example of Pass-By-Reference Parameter Passing
A reference formal parameter is not a variable. When a function is called that has a reference
formal parameter, the effect of the call is to associate the reference with the corresponding
actual parameter. I.e., the reference becomes an alternative name for the corresponding actual
parameter. Consequently, this means that the actual parameter passed by reference must be
variable.
A reference formal parameter can be used in the called function everywhere that a variable can
be used. In particular, if the reference formal parameter is used where a r-value is required, it is
the r-value of actual parameter that is obtained. Similarly, if the reference parameter is used
where an l-value is required, it is the l-value of actual parameter that is obtained. Therefore,
the output obtained produced by the function one defined in Program is:
2
2

Book ID: B0715


5. Describe the theory of Derivation and Inheritance.

Derivation
Inheritance is implemented in C++ through the mechanism of derivation. Derivation allows you
to derive a class, called a derived class, from another class, called a base class.
Derived class syntax

Derived class syntax


>>-derived_class--:--------------------------------------------->
.-,---------------------------------------------------------.--------
V
|
>----+----------------------------+--qualified_class_specifier-+-><
+-virtual--+-----------+-----+
|
+-public----+
|
|
+-private---+
|
|
'-protected-'
|
'-+-public----+--+---------+-'
+-private---+ '-virtual-'
'-protected-'
In the declaration of a derived class, you list the base classes of the derived class. The derived
class inherits its members from these base classes.
Theq u alified_class_specifier must be a class that has been previously declared in a class
declaration.
An access specifier is one of public, private, or protected.
The virtual keyword can be used to declare virtual base classes.
The following example shows the declaration of the derived class D and the base classes V, B1,
and B2. The class B1 is both a base class and a derived class because it is derived from class V
and is a base class for D:
class V { /* ... */ };
class B1 : virtual public V { /* ... */ };
class B2 { /* ... */ };
class D : public B1, private B2 { /* ... */ };
Classes that are declared but not defined are not allowed in base lists.
For example:
class X;
// error
class Y: public X { };
The compiler will not allow the declaration of class Y because X has not been defined.
When you derive a class, the derived class inherits class members of the base class. You can
refer to inherited members (base class members) as if they were members of the derived class.
For example:
class Base {
public:
int a,b;
};
class Derived : public Base {
public:
int c;
};
int main() {
Derived d;
d.a = 1; // Base::a
d.b = 2; // Base::b
d.c = 3; // Derived::c
}
The derived class can also add new class members and redefine existing base class members. In
the above example, the two inherited members, a and b, of the derived class d, in addition to
the derived class member c, are assigned values. If you redefine base class members in the
derived class, you can still refer to the base class members by using the :: (scope resolution)
operator. For example:
#include <iostream>
using namespace std;
class Base {
public:
char* name;
void display() {
cout << name << endl;
}
};
class Derived: public Base {
public:
char* name;
void display() {
cout << name << ", " << Base::name << endl;
}
};
int main() {
Derived d;
d.name = "Derived Class";
d.Base::name = "Base Class";
// call Derived::display()
d.display();
// call Base::display()
d.Base::display();
}
The following is the output of the above example:
Derived Class, Base Class
Base Class
You can manipulate a derived class object as if it were a base class object. You can use a pointer
or a reference to a derived class object in place of a pointer or reference to its base class. For
example, you can pass a pointer or reference to a derived class object D to a function expecting
a pointer or reference to the base class of D. You do not need to use an explicit cast to achieve
this; a standard conversion is performed. You can implicitly convert a pointer to a derived class
to point to an accessible unambiguous base class. You can also implicitly convert a reference to
a derived class to a reference to a base class.
The following example demonstrates a standard conversion from a pointer to a derived class to
a pointer to a base class:
#include <iostream>
using namespace std;
class Base {
public:
char* name;
void display() {
cout << name << endl;
}
};
class Derived: public Base {
public:
char* name;
void display() {
cout << name << ", " << Base::name << endl;
}
};
int main() {
Derived d;
d.name = "Derived Class";
d.Base::name = "Base Class";
Derived* dptr = &d;
// standard conversion from Derived* to Base*
Base* bptr = dptr;
// call Base::display()
bptr->display();
}
The following is the output of the above example:
Base Class
The statement Base* bptr = dptr converts a pointer of type Derived to a pointer of type Base.
The reverse case is not allowed. You cannot implicitly convert a pointer or a reference to a base
class object to a pointer or reference to a derived class. For example, the compiler will not allow
the following code if the classes Base and Class are defined as in the above example:
int main() {
Base b;
b.name = "Base class";
Derived* dptr = &b;
}
The compiler will not allow the statement Derived* dptr = &b because the statement is trying
to implicitly convert a pointer of type Base to a pointer of type Derived.
If a member of a derived class and a member of a base class have the same name, the base
class member is hidden in the derived class. If a member of a derived class has the same name
as a base class, the base class name is hidden in the derived class.
I nheritance
Inheritance is a mechanism of reusing and extending existing classes without modifying them,
thus producing hierarchical relationships between them.
Inheritance is almost like embedding an object into a class. Suppose that you declare an object
x of class A in the class definition of B. As a result, class B will have access to all the public data
members and member functions of class A. However, in class B, you have to access the data
members and member functions of class A through object x. The following example
demonstrates this:
#include <iostream>
using namespace std;
class A {
int data;
public:
void f(int arg) { data = arg; }
int g() { return data; }
};
class B {
public:
A x;
};
int main() {
B obj;
obj.x.f(20);
cout << obj.x.g() << endl;
// cout << obj.g() << endl;
}
In the main function, object obj accesses function A::f() through its data member B::x with the
statement obj.x.f(20). Object obj accesses A::g() in a similar manner with the statement
obj.x.g(). The compiler would not allow the statement obj.g() because g() is a member function
of class A, not class B.
The inheritance mechanism lets you use a statement like obj.g() in the above example. In order
for that statement to be legal, g() must be a member function of class B.
Inheritance lets you include the names and definitions of another class's members as part of a
new class. The class whose members you want to include in your new class is called a base
class. Your new class is derived from the base class. The new class contains a sub object of the
type of the base class. The following example is the same as the previous example except it
uses the inheritance mechanism to give class B access to the members of class A
#include <iostream>
using namespace std;
class A {
int data;
public:
void f(int arg) { data = arg; }
int g() { return data; }
};
class B : public A { };
int main() {
B obj;
obj.f(20);
cout << obj.g() << endl;
}
Class A is a base class of class B. The names and definitions of the members of class A are
included in the definition of class B; class B inherits the members of class A. Class B is derived
from class A. Class B contains a subobject of type A.
You can also add new data members and member functions to the derived class. You can
modify the implementation of existing member functions or data by overriding base class
member functions or data in the newly derived class.
You may derive classes from other derived classes, thereby creating another level of
inheritance. The following example demonstrates this:
struct A { };
struct B : A { };
struct C : B { };
Class B is a derived class of A, but is also a base class of C. The number of levels of inheritance is
only limited by resources.
Multiple inheritance allows you to create a derived class that inherits properties from more
than one base class. Because a derived class inherits members from all its base classes,
ambiguities can result. For example, if two base classes have a member with the same name,
the derived class cannot implicitly differentiate between the two members. Note that, when
you are using multiple inheritance, the access to names of base classes may be ambiguous.
A direct base class is a base class that appears directly as a base specifier in the declaration of
its derived class
An indirect base class is a base class that does not appear directly in the declaration of the
derived class but is available to the derived class through one of its base classes. For a given
class, all base classes that are not direct base classes are indirect base classes. The following
example demonstrates direct and indirect base classes:
class A {
public:
int x;
};
class B : public A {
public:
int y;
};
class C : public B { };
Class B is a direct base class of C. Class A is a direct base class of B. Class A is an indirect base
class of C. (Class C has x and y as its data members.)
Polymorphic functions are functions that can be applied to objects of more than one type. In
C++, polymorphic functions are implemented in two ways:
 Overloaded functions are statically bound at compile time.
 C++ provides virtual functions. A virtual function is a function that can be called for a number
of different user-defined types that are related through derivation. Virtual functions are bound
dynamically at run time

6. Describe the Friend functions and friend classes with programming examples.
Ans
Friend function

When a data is declared as private inside a class, then it is not accessible from outside the class.
A function that is not a member or an external class will not be able to access the private data.
A programmer may have a situation where he or she would need to access private data from
non-member functions and external classes. For handling such cases, the concept of Friend
functions is a useful tool.
A friend function is used for accessing the non-public members of a class. A class can allow non-
member functions and other classes to access its own private data, by making them friends.
Thus, a friend function is an ordinary function or a member of another class.
The friend function is written as any other normal function, except the function declaration of
these functions is preceded with the keyword friend. The friend function must have the class to
which it is declared as friend passed to it in argument.
Some important points to note while using friend functions in C++:
The keyword friend is placed only in the function declaration of the friend function and not in
the function definition.
It is possible to declare a function as friend in any number of classes.
When a class is declared as a friend, the friend class has access to the private data of the class
that made this a friend.
A friend function, even though it is not a member function, would have the rights to access the
private members of the class.
It is possible to declare the friend function as either private or public.
The function can be invoked without the use of an object. The friend function has its argument
as objects, seen in example below.
#include
class exforsys
{
private:
int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)
//Friend Function Declaration with keyword friend and with the object of class exforsys to
which it is friend passed to it
};
int compute(exforsys e1)
{
//Friend Function Definition which has access to private data
return int(e1.a+e2.b)-5;
}
main()
{
exforsys e;
e.test();
cout<<"The result is:"< //Calling of Friend Function with object as argument.
}
The output of the above program is
The result is:295
The function compute() is a non-member function of the class exforsys. In order to make this
function have access to the private data a and b of class exforsys , it is created as a friend
function for the class exforsys. As a first step, the function compute() is declared as friend in the
class exforsys as:
friend int compute (exforsys e1)
Friend Class
C++ provides the friend keyword to do just this. Inside a class, you can indicate that other
classes (or simply functions) will have direct access to protected and private members of the
class. When granting access to a class, you must specify that the access is granted for a class
using the class keyword:
friend class aClass;
Note that friend declarations can go in either the public, private, or protected section of a class-
-it doesn't matter where they appear. In particular, specifying a friend in the section marked
protected doesn't prevent the friend from also accessing private fields. Here is a more concrete
example of declaring a friend:
class Node
{
private:
int data;
int key;
// ...
friend class BinaryTree; // class BinaryTree can now access data directly
};
Now, Node does not need to provide any means of accessing the data stored in the tree. The
BinaryTree class that will use the data is the only class that will ever need access to the data or
key. (The BinaryTree class needs to use the key to order the tree, and it will be the gateway
through which other classes can access data stored in any particular node.) Now in the
BinaryTree class, you can treat the key and data fields as though they were public:
class BinaryTree
{
private:
Node *root;
int find(int key);
};
int BinaryTree::find(int key)
{
// check root for NULL...
if(root->key == key)
{
// no need to go through an accessor function
return root->data;
}
// perform rest of find
}

7. Illustrate with suitable examples various file handling methods in C++.

Ans.

Openi ng a Fil e  Di f f erent Met hods


So far we have seen just one way to open a file, either for reading, either for writing. But
it can be opened another way too. So far, you should be aware of this method:
ifstream OpenFile(  cpp-home.txt  );
Well, this is not the only way. As mentioned before, the above code creates an object
from class ifstream, and passes the name of the file to be opened to its constructor. But in fact,
there are several overloaded constructors, which can take more than one parameter. Also,
there is function open() that can do the same job. Here is an example of the above code, but
using the open() function

ifstream OpenFile;
OpenFile.open(  cpp-home.txt  );
Other use of o pen() is for example if you open a file, then close it, and using the same
file handle open another file. This way, you will need the o pen() function.
Consider the following code example:
#include <fstream.h>
void read(ifstream &T) { //pass the file stream to the function
//the method to read a file
char ch;
while(!T.eof()) {
T.get(ch);
cout << ch;
}
cout << endl << "  " << endl;
}
void main() {
ifstream T("file1.txt");
read(T);
T.close();
T.open("file2.txt");
read(T);
T.close();
}
So, as long as file1.txt and file2.txt exists and has some text into, you will see it.
ifstream OpenFile(char *filename, int open_mode);
You should know that filename is the name of the file (a string). What is new here is the
o pen_m o de . The value of o pen_m o de defines how to a file can be opened. Here is a table of the
open modes

You might also like