You are on page 1of 19

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

Answer: 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. 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. 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.

Program : Sum of two numbers #include<iostream.h> #include<conio.h> void main(); { int a, b, sum; cout<<Please enter two number<<endl; cin>>a>>b>>; sum=a+b; cout<<Sum of two number is <<sum; getch(); }

include Example.cpp (Source Code) Compiling Cs.lib (Library file) Example.obj (object Code) Other object codes (if any) Iostream.h (header file)

Linking Example.exe (executable file)

Fig : Compiling and Linking

2. Describe the theory with programming examples the selection control statements in C++. Answer : There are basically two types of control statements in C++ which allows the programmer to modify the regular sequential execution of statements. They are selection and iteration statements, The selection statements allow to choose a set of statements for execution depending on a condition. if statement and Switch statement are two statements which allow selection in C++ There is also an operator known as conditional operator which enables selection. 1) Selection If statement Syntax: 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 at false and non zero value is taken as true if the condition is true, statement 1 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 executed, 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. Program : if. .Else #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. Nested if Statement : if statement can be nested in another if staternent to check multiple conditions. Syntax : if (condition 1) { if (condition 2) { statement1; statement2; }else If (condition3) {

statement3; } } else statement4;

Conditio -nal 1

Statement 4

Conditio -nal 2

Conditio -nal 3

Statement 1 Statement 2

Statement 4

Next Statement after if statement

Multiple condition can be checked using logical && operator(AND) and || operator(OR). if((condition1) && (condition2)) statement1; else statement2; Program : Largest of the three number #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 the user display which is the largest number among the three. Switch statement : Syntax: Switch(variablename){ case value 1 : statement1; break; case value 2 : statements2; break; case value 3 : statements3; break; default statement4; } If the variable in the switch statement is equal to value 1 then statement1 is executed, if it is equal to value2 then statement2 is executed, if it is value3 then statements is executed. If the variable value is not in any of the cases listed then the default case statement or statement is executed. Each case can have any number of statements and 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. Program : Switch # include<iostream.h> #include<conio.h> void main() { char pos; int x=15, y=15; cout<<PIease choose the letter 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 : "You selected a wrong option"; } cout<< You are now located at<<x<< <<y; getch(); }

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 initialized to 15 and 15 which are x and y coordinates of his position. Depending upon the what user has selected the x and y coordinates are incremented or decremented by one. If the user types a letter other than l,r,u,d he gets an error message 2) Iteration Iteration or loops are important statements in C++ which helps to accomplish repetitive execution of programming statements. There are three statements in C++: while loop, do while loop and for loop While loop While loop Syntax: while (condition expression) { Statement 1; Statement 2; } In the above example, condition expression is evaluated end if the condition is true, then the statement 1 and statement2 are executed. After execution, the condition is checked again. If true, the statements inside the while loop are executed again. This continues until the loop condition becomes false.

Program : Average of the given 5 number # include <iostream.h> void mainO { int n=0, a, sum=0; cout<< enter five numbers; while (n<5) { cin>>a; sum=sum+a; n++; } cout<< Average of the number is<<sum/n); } The above program accepts five numbers from the user and finds the average of the five numbers. In the above while loop, the variable n is initialized to zero and this variable keeps track of the count of numbers input from the user. It is incremented every time a number is input from the user The number accepted from the user is added to the value stored in the sum variable. When n becomes 5 the while loop condition becomes false and the average of the numbers is printed. Do while loop The do while loop is same as while loop except that the condition is checked after the execution of statements in the do while loop. Hence in do while loop, statements inside the loop ere executed at least once. However, in while loop, since the condition is checked before, the statements inside the loop will not be executed if the loop condition is false. Syntax: do { Statement1; Statement2; } while (condition expression); In me above example the statement1 and statement2 are executed and the condition is checked, if the condition is true then the statements are executed again and if the condition is false then the control is transferred to the next statement after the do while statement

Program : Average of the given number #include <iostream.h> void main() { int n=0,a,sum=0; cout<< enter five number<<endl; do { cin>>a; sum=sum+a; n++; }while(n<5); cout<< Average of the numbers is <<(sum/n); } The decision on whether to use while or do while statement depends on whether the statements inside (the loop have to be executed at least once or not. If it has to be executed at least once, then the do while statement should be used. For loop The for loop is one of the popular control statement as it is compact and clear in specification. The loop initialization, loop termination condition statement and statement for the next iteration are all included in one statement Syntax: for(initialization; condition; Increment/decrement) { Statement 1; Statement2; } In the above example, initiation statement is executed first and then the condition is checked. If the condition is true, statement 1 and statements 2 will be executed. Then the third statement in the for loop is executed which modifies the loop control variable Program : Average using For loop #include<iostream.h> void main() { int a, sum=0; cout<< enter five numbers; for(int n=0;n<5;n++) { cin>>a;

sum=sum+a; } cout<< Average of the number is <<(sum/n); } In the above program n variable is loop variable which is initialized to zero. The statements inside the loop are executed until the loop termination condition n<5 becomes false. after every iteration, the loop variable n is incremented. 3. Given a RxC Matrix, A, i.e. R rows and C columns we define a SaddlePoint 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. Answer: Program: #include<stdio.h> #include<conio.h> main() { int a[10][10],i,j,k,n,min,max,col; clrscr(); printf("enter order m,n of mxn matrix"); scanf("%d %d",&m,&n); printf("enter elements row-wise"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<m;i++) { min=a[i][0]; for(j=0;j<n;j++)

{ if(a[i][j]<=min) { min=a[i][j]; col=j; } } max=a[0][col]; for(k=0;k<m;k++) { if(a[k][col]>=max) { max=a[k][col]; } } if(max==min) printf("saddle (%d,%d)",i+1,col+1); } getch(); }

4. Describe and demonstrate the concept of pass by value and pass by reference using appropriate programming example of your own. Answer : Data can be passed to functions in two ways. One method is passing by value. In this way of passing variables, a copy of the variable is created during function call with the name specified in the function and initialized with the value to the original variable. All the operations in the function is then performed on the function variable. The values in the variables declared in the main program remain unchanged by the function operations. Program : Pass by value #include<iostream.h> #include<conio.h> void main() { int a,b; cout<< Enter two numbers;

cin>>a>>b; swap(a,b); count<< The value of a is <<a<<endl; cout<<The value of b is <<bendl; getch(); } void swap(int m, int n) { int temp; temp = m; m=n; n=temp; }

Another alternative to passing argument is passing by reference. In passing by reference, no copy of the variable is created. however, the variables in the main program are refered to by different name in the function. since no copy is created, when the values in the function variables are modified. Passing by reference provide an easy mechanism for modifying the variable by function and also enables to return multiple variables. Program : Pass by reference #include<iostream.h> #include<conio.h> void main() { int a,b; cout<< Enter two numbers; cin>>a>>b; swap(a,b); count<< The value of a is <<a<<endl; cout<<The value of b is <<bendl; getch(); } void swap(int &m, int &n) { int temp; temp = m; m=n;

n=temp; } In the above program, the variables a and b are passed by reference which implies that they will be accessed directly the variable are however will be referred as m and n in the function and are swapped. The result is that the function swaps the values in the original variables a and b.

5. Describe the theory of Derivation and Inheritance. Answer : Derivarion : It allows you to derive a class, called a derived class, from another class, called a base class. The general forms of defining a derived class is : class derived-class-name : visibility-mode base-class-name { . . . . . // . . . . . // members of derived class . . . . . // }; The colon indicates that the derived-class-name is derived from the base-class-name. The visibility mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the feature of the base class are privately derived or publicly derived example : class ABC: private XYZ { members of ABC }; class ABC: public XYZ { members of ABC }; class ABC: XYZ { members of ABC }; // private derivation

// public derivation

// private derivation by default

When a base class is privately inherited by a derived class, public members of the base class become private members of the derived class and therefore the public members of the base class can only be accessed by the member functions of the derived class. They are inaccessible to the objects of the derived class. A public member of a class can be accessed by its own objects using a dot operator. The result is that no member of the base class is accessible to the objects of the derived class.On the other hand, when the base class is publicly inherited, public members of the base class become public members of the derived class and therefore they are accessible to the objects of the derived class. in both the cases, the private members are not inherited and therefore, the private members of a base class will never become the member of its derived class. Program : Derivation #include<iostream.h> 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; = Derived Class; d.Base::name = Base Class; Derived* dptr = &d; Base* bptr = dptr;

bptr->display(); } Inheritance : It is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them. It is almost like embedding an object into class. example : #include<iostream.h> using namespace std; class A{ int data; public: void f(int arg){ data = arg; } int g() { return data; } }; class B { public: AX; }; int main() { B obj; obj.x.f(20); cout<<obj.x.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 a class A, not class B. You can also add new data member and member functions to the derived class. You can modify the implementation of existing member functions or data by overriding base class member function or data in a newly derived class. You can derive classes from another classes, thereby creating another levels of inheritance. Multiple inheritance allows you to create a derived class that inherits properties from more than one base class. Because a derived class inherits member from all its base classes

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 but is available to the derived class through one of its classes 6. Describe the Friend functions and friend classes with programming examples. Answer: Friend functions : Friend function can be declared anywhere within a class declaration, but it is common practice to list friends at the beginning of the class. The public and protected keywords do not apply to friend function, as the class has no control over the scope of friends. If we want to declare an external function as friend of a class. thus allowing this function to have access to the private and protected member of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend. Program : Friend functions #include <iostream.h> using namespace std; class CRectangle { int width, height; public : void set_values (int, int); Int area() { return (width * height);} friend CRectangle duplicate (CRectangle); }; void CRectangle::set_values (int a. Int b) { width = a; height=b; } CRectangle duplicate (CRectangle rectparam) { CRectangie rectres; rectres.width = rectparam.width*2; rectres.height= rectparam.height*2; return (rectres); } int main() { CRectangle rect, rectb; rect.set_values(2,3); rectb=duplicate(rect);

cout<<rectb.area(); return0; } The duplicate function is a CRectangle. From within that function we have been able to access the members width and height of different objects of type CRectangle, which are private member. Friend Classes : A class can declare a member function of another class as a friend, or declare another class as a friend class. Friend classes are used in cases where one class it tightly coupled to another class. For example, suppose we have a class CPoint that represents a coordinate, and a data CPointCollection that holds a list of points. Since the collection class may need to manipulate point objects, we could declare CPointCollection aa a friend of the CPomt class // Forward declaration of friend class class CPointCollectton; //Point class class CPosnt { friend CPointCollection; private: double m_x; double m_y; public: CPoint(const double x, const double y); m_x(x); m_y(y); ~CPointCollection(void); void set(const double x, const double y); // . . . . }; The set member can iterate over the collection and reset each point; void CPointCollection::set(const double x,const double y) { const int nElements = m_vecPoints.size(); for(int i=0;i<nElements;i++) { m_vecPoint[i].m_x = x; m_vecPoint[i].m_y = y;

} } Derived classes of CPointCollection will not be able to access CPoint. The principle is that friendship is not implicitly granted; each class must explicitly choose its friends. 7. Illustrate with suitable examples various file handling methods in C++. Answer:

8. Explain the concept of class templates in C++ with some real time programming examples. Answer : A class template definition looks like a regular class definition, except it is prefixed by the keyword template. For example template <class T> class stack { public: Stack(int = 0); ~Stack() { delete[] stackPtr; } int push(const T&); int pop(T&); int isEmpty()const { return top == -1; } private: int size; int top; T* stackPtr; }; T is a type parameter and it can be any type. for example, Stack<Token>, where Token is a user defined class. T does not have to be a class type as implied by the keyword class. For example, Stack<int> and Stack<Message*> are valid instantiations, even though int and Message* are not classes. Implementing Class Template Member Functions The declaration and definition of the class template member function should all be in the same header file. The declarations and definitions need to be in the same header file. Consider the following: //B.H //B.CPP //MAIN.CPP Template <class t> #include<B.H> #include<B.H>

class b { public: b(); ~b(); };

Template<class t> B<t>::b() { } Template <class t> B<t>::~b(){ }

Void main(){ b<int> bi; b<float> bf; }

When compiling B.cpp, the compiler has both the declarations and the definition available. At this point the compiler does not need to generate any definition for template classes, since there are no instantiation: template class B<int> and B<float>. At this point the compiler has the declarations but no definitions Using a class template Using a class template is easy. Create the required classes by plugging in the actual type for the type parameters. This process is commonly known as instantiating a class. Program: Stack class template #include<iostream.h> #include<stack.h> using namespace std; void main() { typedef Stack<float> FloatStack; typedef Stack<int> IntStack; FloatStack fs(5); float f = 1.1; cout<<Pushing elements onto fs<<endl; while(fs.push(f)) { cout<<f<<; f+=1.1; } cout<<endl<<Stack Full. <<endl; while(fs.pop(f)) cout<<f<<; cout<<endl<< Stack Empty.<<endl; cout<<endl; IntStack is; int I = 1.1; cout<<Push element onto is<<endl;

while(is.push(i)) { cout<<i<< ; i+=1; } cout<<endl<< Stack Full<<endl<<endl<< Popping elements from is<<endl; while(is.pop(i)) { cout<<i<< ; cout<<endl<< Stack Empty <<endl; } In the above program we defined a class template Stack. In the driver program we instantiated a Stack of float (FloatStack) and a Stack of int(intStack). Once the template classes are instantiated you can instantiated objects of that type(for example, fs and is.)