Madhvi

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 73

Unix & Shell Programming

INDEX

S.No.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Lab Objective Introduction about Lab Guidelines to Students

Contents

Page No.

List of Syllabus Programs (CSVTU) Solution for Program-01 Solution for Program-02 Solution for Program-03 Solution for Program-04 Solution for Program-05 Solution for Program-06 Solution for Program-07 Solution for Program-08 Solution for Program-09 Solution for Program-10 Bibliography

LAB OBJECTIVE
MMCT,Raipur Department of Computer Science and Engineering Page 1

Unix & Shell Programming

Upon successful completion of this Lab the student will be able to: 1. 2. 3. 4 5. 6. 7. Learn basic fundamental concept about c++ . Demonstrate how to use the following function cout, cin . etc. Use the following condition statement if,if-else . Use looping statement while, do-while ,for loop . Learn the use of switch statement. Learn arrays & accessing array element . Learn structure & function for need of reusability in the program to record same type of information . 8. 9. 10. 11. Use static automatic variable when it s necessary for a function to remember a value . Learn about friend function. Learn practical implementation of CONSTRUCTOR in class. Implementation of passing object of a class as function argument an analyzing it s usage.

INTRODUCTION ABOUT LAB

There are . systems ( Wipro system ) installed in this Lab. The configuration of these systems is as follows : Hardware Processor RAM Hard Disk : : 512 MB : 160 GB Dual core

MMCT,Raipur Department of Computer Science and Engineering

Page 2

Unix & Shell Programming

Mouse

Optical Mouse

Software 1. Software installed : C, C++.

2. 3.

Systems are provided for students in the 1:1 ratio. compiler Turbo C++ Compiler.

GUIDELINES TO STUDENTS
How to Run c++ program There are two ways you can execute your c++ program Method 1 Step 1 : Save the program by .cpp

Step 2 : Use keyboard (contrl+F9) Key. Method 2 Step 1 is repeat . Step 2 : Use run option in menubar

LIST OF SYLLABUS PROGRAMS (CSVTU)


1. Write a Program to check whether number is prime or not. 2. Write a Program to read number and to display the largest value between: A. Two number B. Three number C. Four number by using switch-case statements. 3. Write a Program to find sum of first natural numbers: sum= 1+2+3+4+ by using a. for loop b. while loop c. do-while loop . 4. Write a Program to find sum of the following series using function declaration. Sum=x-(x)3/3!+ (x)5/5!.................... (x)n/n! MMCT,Raipur Department of Computer Science and Engineering Page 3 ..100

Unix & Shell Programming

5. Write a Program to read the element of the given two matrix & to perform the Matrix multiplication. 6. Write a Program to exchange the contents of two variable by using (a) call by value (b) Call by reference. 7. Write a Program to perform the following arithmetic operations of a complex number using a structure . (a) Addition of the two complex number. (b) Subtraction of the two complex number. (c) Multiplication of the two complex number. (d) Division of the two complex number. 8. Write a Program to generate a series of Fibonacci Nos . using the constructor

Where the constructor member function had been defines (a) is the scope of class definition itself (b) out of the class definitions using the scope resolutions operator. Also make this program with the help of the copy constructor . 9. Write a program to demonstrate how ambiguity is avoided using scope resolution operator in the following inheritance (a). Single inheritance (b) Multiple inheritance. 10. Write a program to perform the swapping of two data items of integer, floating point number and character type with the help of function overloading 11. Write a program to generate a Fibonacci series by overloading a. Prefix Operator b. Postfix Operator . 12. Write a program to access the private data of a class by non member function through friend function where the friends function is declared : (1) is the location of public category (2) is the location of private category (3) With in the scope of a class definition itself (4) Defined with inline code subtraction . MMCT,Raipur Department of Computer Science and Engineering Page 4

Unix & Shell Programming

13. Write a program to demonstrate how a pure virtual function defined declared and invoked from the object of derived class through the pointed of the base class. 14. Write a program to Bubble Sort Using template function. 15. Write a program for invoking for that Generate & Handle exception.

SOLUTION FOR PROGRAM - 01

Aim:

Write a Program to check whether number is prime or not

Programming Constructs used: Program statement that cause such jumps are called control statements. There are two major categories :loops and decision. Loops:- Loops cause a section of your program to be repeated a certain no of times. The repetition continues while a condition is true. When the condition become false , the loop ends and control passes to the statement following the loop. There are three type of loop(1)For loop (2)While loop (3)Do while loop For loop:- The for loop execute a section of code a fixed no. of times.It s usually used when you know before entering the loop. how many times you want to execute the code. The for statement control the loop. It consist of the keyword for, followed by parenthesis that contain 3 expression separated by semicolons: For(j=0;j<1;j++) These three expression are the initialization expression, the text expression & the increment expression. These three expression usually involve the same variable which we call the loop variable.

MMCT,Raipur Department of Computer Science and Engineering

Page 5

Unix & Shell Programming

Note that the fir statement is not followed by a semicolon. That s because the for statement &the loop body are together consider to be a programe statement. Decision s:-Program also needs to make these one time decision . In a program a decision cause a one time jump to a different part of a program, depending on the value of an expression decision can be made in c++ in several ways. The most important is with the if else statement, which choose between two alternatives. This statement can be used without the else,as a simple if statement. The if else statement:-The if statement lets you do something if a condition is true. If it is not true ,nothing happens . But suppose we want to do one thing if a condition is true and do something else if it is false.

Source Code: # include <iostream.h> #include <conio.h> #include<math.h> #include<cmath> void main() { int i,num; cout<< Enter the number ;cin>>n; isprime(n); } bool isprime(int num) { //no number can divide into 0

MMCT,Raipur Department of Computer Science and Engineering

Page 6

Unix & Shell Programming

if (num==0) return true; // make sure it is not negative num=abs(num); for (int i=2;i<=sqrt(num);i++) if (num%i==0) return(false); return(true); }

Output: Enter the number:5 true Viva Questions and Answers: (1) What is decision about program . program

Ans:- The decision in a loop always related to the should we do this (the loop body) also need to one time decision. (2) what is control statement?

Ans:- Conditional, Loop & breaking statement are called control statement (3)What is conditional statement. Ans:- The conditional statement are mainly used for decision making. These types are:(1) if statement (2) if..else statement MMCT,Raipur Department of Computer Science and Engineering Page 7

Unix & Shell Programming

(3) switch statement

SOLUTION FOR PROGRAM - 02

Aim:

Write a program to read number & to display the largest value between

Programming

Constructs used: Switch statement is a special multiway decision maker that tests whether an expression match one of the number of constant value, and braces accordingly. The expression whose value is being compared ,may be any valid expression including the value of the variable, an arithmetic s expression, logical comparison bitwise expression .but not a floating point expression. The constant in each of the case statement must obviously be of the same type. The expression value is checked against each of the specified case & when a match occur ,the statement following that is excuted . Commands used: The syntax of the suitable statement is: switch (expression){ case constant_1 statement case constant_2 statement ..

case constant_n statement MMCT,Raipur Department of Computer Science and Engineering Page 8

Unix & Shell Programming

default: statement }//end of switch statement

Source Code :#include <iostream.h> #include <conio.h> void main() { int a,b,c; cout<< enter the values of a,b& c: ; cin>>a; switch (a) { case1: cout<< enter the value of x& y : cin>>x>>y; if(x>y) { cout<< the greatest vaue is= <<x; } case2:

MMCT,Raipur Department of Computer Science and Engineering

Page 9

Unix & Shell Programming

cout<< enter the value of x,y&z ; cin>>x>>y>>z; if(x>y&&x>z) { cout<< the great value is = <<x; } cout3; cout<< enter the value of x&y ; cin>>x>>y>>z>>w; if (x>y&&x>y&&x>z&&x>>w) { cout<< the greatest value is= <<x; } } Output: Enter the value of a,b &c 2 Enter the value of x&y true Viva Questions and Answers: (1) Why used if statement ? Ans : The if statement used to express conditional expression. (2) What is the basic structure of if-statement? MMCT,Raipur Department of Computer Science and Engineering Page 10

Unix & Shell Programming

Ans: if(expression) { statement; statement; .

} (3) Why used of braces? Ans The braces are used to clearly indicate the proper association.

SOLUTION FOR PROGRAM - 03

Aim:

Write a program to find sum of first natural number :sum=1+2+3+4+

100 by using while

loop , do-while & for loop. Programming Constructs used: For loop:- For loop:- The for loop execute a section of code a fixed no. of times. It s usually used when you know before entering the loop. how many times you want to execute the code. The for statement control the loop. It consist of the keyword for, followed by parenthesis that contain 3 expression separated by semicolons: For(j=0;j<1;j++) These three expression are the initialization expression, the text expression & the increment expression. These three expression usually involve the same variable which we call the loop variable. Note that the for statement is not followed by a semicolon. That s because the for statement &the loop body are together consider to be a program statement. MMCT,Raipur Department of Computer Science and Engineering Page 11

Unix & Shell Programming

While Loop:- The second type of loop ,the while loop ,is used when we are not certain that the loop will be executed. After checking whether the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operation. Do-while:-The do-while loop is another repetitive loop used in C++ programs.Whenever one is certain about a test condition ,then the do-while loop can be used ,as it enters into the loop atleast once & then checks whether the given condition is true or false.As long as the test condition is true ,the loop operation s or statements will be repeated again & again. The general syntax of the do-while loop is: { statement_1 statement_2

} while(expression) ; Commands used:Using while statement : The general form of the while loop is:For a single statement, while (condition) statement; For a block statements, while (condition){ statement_1; statement_2; . MMCT,Raipur Department of Computer Science and Engineering Page 12

Unix & Shell Programming

.. }

Source code : #include<iostream.h> //while loop void main() { int sum,digit; sum=0; digit=1; while (digit<=100) { sum+=digit; digit++; } cout<< 1+2+3+ .100= <<sum<<; } Output 1+2+3+ .100=5050

Viva Questions and Answers: (1) What is while loop. Ans: the while loop ,is used when we are not certain that the loop will be executed. After

checking whether the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operation.

MMCT,Raipur Department of Computer Science and Engineering

Page 13

Unix & Shell Programming

(2) While loop contain the initialization or incrimination parts of loop? Ans No (3) Use of while loop for reading data and processing it untill the end of data is f found.

SOLUTION FOR PROGRAM - 04

Aim: Write a Program to find sum of the following series using function declaration. Sum=x-(x)3/3!+ (x)5/5!.................... (x)n/n!

Programming Constructs used: Functions are building blocks of the programs. They make the programs more modular and easy

to read and manage. All C++ programs must contain the function main( ). The execution of the program starts from the function main( ). A C++ program can contain any number of functions according to the needs.

The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore.

The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable. For example,

int factorial(int n, float j) Commands used: using function declaration & return statement. The general form of the function is: MMCT,Raipur Department of Computer Science and Engineering Page 14

Unix & Shell Programming

return_type function_name(parameter list) { body of the function } The function of consists of two parts function header and function body. The function header is:return_type function_name(parameter list) Source Code: #include<iostream.h> #include<conio.h> #include<math.h> void main()double fact(double k) { if(k==0||k==1) return 1; else return k*fact(k-1); } double coss(float x,int n) { double sum=0,sign=1,term=0; sum+=1; int I; for(i=2;i<=n;i+2) { sign*=-1; term=(sign*pow(x,i))/I;

MMCT,Raipur Department of Computer Science and Engineering

Page 15

Unix & Shell Programming

sum+=term; } return sum; } void main() { double num,n; cout<<"enter the value and accuracy"; cin>>num>>n; cout<<"value is"<<coss(num,n); getch(); }

Output: Enter the value and accuracy 1

Value is 0.83

Viva Questions and Answers: (1) What is return statement? Ans:- The keyword return is used to terminate and return a value to it s caller. (2)Define function. Ans: Functions are building blocks of the programs. They make the programs more easy to read and manage. (3) Explain function name. MMCT,Raipur Department of Computer Science and Engineering Page 16 modular and

Unix & Shell Programming

Ans: The function name can be any name conforming to the syntax rules of the variables. Normally, a function name is relevant to the function operation. For Example:Counter(); Square();

SOLUTION FOR PROGRAM - 05

Aim:

Write a program to read the element of the given two matrix & to perform the matrix

multiplication. Programming Constructs used: Like other variable in C++ ,an array must be defined before it can be used to store information .& like other definition ,an array definition specifies a variable type & a name . But it includes another feature a size .the size specifies how many data items the array will contain .it immediately follows the name & is surrounded by square bracket. Array element :- The item in an array are called elements

Generally, a collection of data items that can be selected by indices computed at run-time, including:
y y y

Array data structure, an arrangement of items at equally spaced addresses in computer memory Array data type, used in a programming language to specify a variable that can be indexed Associative array, an abstract data structure model that generalizes arrays to arbitrary indices

matrix arithmetic
Matrix arithmetic has special rules. Matrix addition and subtraction are conveniently defined as the sum or difference of the individual elements and this is the same as the simple array arithmetic operation described above, which therefore needs no further work on our part.

Matrix

MMCT,Raipur Department of Computer Science and Engineering

Page 17

Unix & Shell Programming

Dynamically allocates a zero-based 2D block of memory. This memory block is continuous, an Write a C++ searching program that declares an array matrix of type integer that prompts the user to input N numbers. Again prompt the user to input the number to be searched. If the number can be found, print its position, otherwise print It is not in the list.d is in column then row order Consider a two-dimensional data set, with dimensions m and n. In a computer, the data from this data set is stored in a one-dimensional set of memory addresses; what makes the data "twodimensional" is the way the individual elements are indexed by the software that accesses the data in memory. This topic is discussed in detail in Columns, Rows, and Array Majority; if you are unsure of your understanding of the process of mapping multidimensional data into onedimensional computer memory, please read that section carefully. There are two possible ways to depict a two-dimensional data set on paper row by row or column by column.
Commands used-For array in C++ ,using array element in square bracket & general format the array initialization is,

storage_class

data_type array__name[expression]={element_1,element_2..element_n};

Source Code #define MAX 100: #Include <iostream.h> #Include <conio.h> void main() { void output(float a[MAX][MAX],int n); Void mul (Float a[MAX][MAX],floatb[MAX][MAX],int n); float a[MAX][MAX],b[MAX][MAX]; int i,j,n; cout<< order of A matrix <<end l; cin>>n;

MMCT,Raipur Department of Computer Science and Engineering

Page 18

Unix & Shell Programming

cout<< enter the element of A matrix <<endl; for(i=0;i<=n-1;++i){ for (j=0;j<=n-1;++j) cin>>a[i][j]; } cout<< order of B matrix <<endl; cin>>n; cout<< enter the element of B matrix <<end1; for(i=0;i<=n-1;++i){ for(j=0;j<=n-1;++j) cin>>b[i][j]; }cout<< output A[i][j] ,,endl; output(a,n0 cout<< output B[i][j] <<endl; output(b,n); mul(a,b,n); } void mul(float a[MAX][MAX],float b[MAX][MAX], int n); { void output (float c[MAX][MAX], int n); float c[MAX][MAX]; int i,j,k;

MMCT,Raipur Department of Computer Science and Engineering

Page 19

Unix & Shell Programming

for (i=0;i<=n-1;++i){ for(j=0;j<=n-1;++j){ c[i][j]=0.0; for(k=0;k<=n-1;++k) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } cout<<end1; cout<< output of c[i][j] matrix <<endl; output(c,n); } void output(float X[max][max],int n0 { int i,j; for (i=0;i<=n-1;++i) { for(j=o;j<=n-1;++j) cout<<X[i][j]<< \t ; cout<<end1; } }

Output:

MMCT,Raipur Department of Computer Science and Engineering

Page 20

Unix & Shell Programming

Order of A matrix 3 Enter the element of a A matrix 3 3 3

3 3 3 3 3 3 Order of B matrix 3 Enter the element of B matrix 3 3 3 3 3 3 3 3 3 Output A[i][j] 3 3 3 3 3 3 3 3 3 Output B[i][j] 3 3 3 3 3 3 3 3 3 Output of C[i][j] matrix 27 27 27 27 27 27 MMCT,Raipur Department of Computer Science and Engineering Page 21

Unix & Shell Programming

27 27 27 Viva Questions and Answers: (1) What is array. Ans:- An array is a collection of identical data object which are stored in consecutive memory location under a common heading or a veriable name. (2)What is array dimention. Ans:- Declaring the name & type of an array & setting the number of element in the array is known as dimensioning the array (3)What is one & multidimensional array Ans:- in one dimensional array only one array element &in multidimensional array no of more then one array element.

SOLUTION FOR PROGRAM - 06

Aim: Write a Program to exchange the contents of two variable by using (a) call by value (b) Call by reference.

Programming Constructs used: When passing data by value, the data is copied to a local variable/object in the function. Changes to this data are not reflected in the data of the calling function. For larger objects, passing data by value can be very expensive. When passing data by reference, a pointer to the data is copied instead. Changes to the data pointed to by the pointer are reflected in the data of the calling function. Regardless of the size of the object, passing data by reference always has the same cost. by_ref() demonstrates the syntax used to pass data by reference using It's possible to pass by reference without passing with references, but passing with references always passes by reference. MMCT,Raipur Department of Computer Science and Engineering Page 22

Unix & Shell Programming

A reference provides an alias- an alternate name- for the variable. While passing Call by Value In the Call by Value method, the called function creates new variables to store the value of the arguments passed to it.reference arguments, a reference to the variable in the calling program is passed.

In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with pointers and C++ references being specific reference datatype implementations. . Commands used- Used swap function for call by value & call by refrence. Source Code#include<iostream.h> #include<conio.h>
//prototype declarations void swapv(int,int); voidswapv(int&,int&); voidswapv(int*,int*); void main() { int a=10,d=20; swapv(a,b); //call by value cout<<end1<<a<<"\t"<<b; swapv(a,b); //call by reference

cout<,ent1<<a<<"\t"<<b } void swap(int i,int j) { int t; t=i; i=j; MMCT,Raipur Department of Computer Science and Engineering Page 23

Unix & Shell Programming

j=t; cout<,i<<j; } void swapv(int &i,int &j) { int t; t=i; i=j; j=t; } Output: 5 6 5 6 6 5

Viva Questions and Answers: (1) What is call by value? Ans: call by value:The called function sends its value as call by value. (2)What is call by reference? Ans:Call by reference: The calling function sends address of variable to the called function.
(3) Basic difference between call by value & call by reference. Ans:-The basic difference is that when you pass a parameter by value, the function receives only a copy of the original object, so it can't do anything to affect the original object. With pass by reference, it gets MMCT,Raipur Department of Computer Science and Engineering Page 24

Unix & Shell Programming

a reference to the original object, so it has access to the original object, not a copy of it -- unless it's a const reference, it can modify the original object .

SOLUTION FOR PROGRAM - 07

Aim:

Write a program to perform the following arithmetic operation of a complex number using a

structure (a) Addition of the two complex number (b)Subtraction of the two complex number (c) Multiplication of the two complex number (d)division of the two complex number Programming Constructs used:

C++ Structure In this C++ tutorial, you will learn about Structure, declaring a Structure, how to declare structure Variable and how to access the structure members in C++. Structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name. Declaring a Structure: The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces { and }. Finally, the closed braces end with a semicolon denoted as ; following the statement. The above structure declaration is also called a Structure Specifier. Example: hree variables: custnum of type int, salary of type int, commission of type float are structure members and the structure name is Customer. This structure is declared as follows:

MMCT,Raipur Department of Computer Science and Engineering

Page 25

Unix & Shell Programming

When structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type in and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum, 2 bytes for salary and 4 bytes for commission. Access structure members in C++ To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly:
structure variable name.member name

Commands used: Structure statement arestruct sample { int x; float y; MMCT,Raipur Department of Computer Science and Engineering Page 26

Unix & Shell Programming

char s; }; Source Code // Complex number using function Struct complex{ Float real; Float imag; } Complex add (complex a, complex b); Complex sub (complex a, complex b); Complex mul (complex a, complex b); Complex div (complex a, complex b); #include<iostream.h> #include<stdio.h> { Complex a,b,c; Int ch; Void menu(void); Cout << enter a first complex number\n ; Cin>>a.real>> a.imag; Cout << enter a second complex number\n ; Cin>>b.real>> b.imag; Menu();

MMCT,Raipur Department of Computer Science and Engineering

Page 27

Unix & Shell Programming

While((ch=getchar() )= q ){ Switch(ch){ Case a : C=add(a,b); Cout << addition of two complex numbers\n ; Cout <<c.real << +I <<c.imag<<endl; Break; Case s : C=sub(a,b); Cout<< subtraction of two complex number \n ; Cout<<c.real<< I <<c.imag<<endl; Break; Case m : C=mul(a,b); Cout<< multiplication of two complex numbers\n ; Cout << c.real<< I <<c.imag<<endl; Break; } } } Void main(void) {

MMCT,Raipur Department of Computer Science and Engineering

Page 28

Unix & Shell Programming

Cout << complex number operations \n ; Cout<< menu()\n ; Cout << a->addition\n ; Cout<< s->substraction\n ; Cout<< m->multiplication\n ; Cout << d->division\n : Cout <<q->quit \n ; Cout << option ,please ?\n; } Complex add (struct complex a, struct complex b) { Complex c; c.real=a.real+b.real; c.imag=a.imag+b.imag; return(c); } Complex sub (struct complex a,struct complex b) { Complex c; c.real=a.real-b.real; c.imag=a.imag-b.imag; return(c);

MMCT,Raipur Department of Computer Science and Engineering

Page 29

Unix & Shell Programming

} Complex mul(struct complex a, struct complex b) { Complex c; c.real=(a.real*b.real)-(a.imag*b.imag); c.imag=(a.real*b.imag)+(a.imag*b.real); return(c); complex c; float temp; temp=(b.real*b.real)+(b.imag*b.imag); c.real=((a.real*b.real)+(a.imag*b.imag))/temp; c.imag=((b.real*a.imag)-(a.real*b.imag))/temp; return(c); Output: Enter a first complex number 2 Enter a second number 2 Complex number operations Menu() A-> addition S_>SUBTRACTION

MMCT,Raipur Department of Computer Science and Engineering

Page 30

Unix & Shell Programming

M->MULTIPLICATION D->division Q->quit Option A ddition of two complex numbers 3+i3 S Substraction of two complex numbers -1i-1 M Multiplication of two complex numbers 0i4 Division of two complex numbers 0.5i0 Viva Questions and Answers: (1) What is a structure?

A structure is a collection of pre-defined data types to create a user-defined data type. Let us say we need to create records of students. Each student has three fields: int roll_number; char name[30]; int total marks; This concept would be particularly useful in grouping data types. You could declare a structure student as:
(2)What is Deferencing operator * : MMCT,Raipur Department of Computer Science and Engineering Page 31

Unix & Shell Programming

This operator gives the value at the address pointed by the pointer .
(3) What is the use of typedef? typedef declaration helps to make source code of a C program more readable. Its purpose is to redefine the name of an existing variable type. It provides a short and meaningful way to call a data type.

SOLUTION FOR PROGRAM - 08

Aim:

Write a program to generate a series of Fibonacci nos using the constructor where the

constructor member function had been define (a) is the scope of the class definition itself (b) out of the class definition using the scope resolution operator .Also make this programe with the help of the copy constructor. Programming Constructs used: Fibonacci numbers are a sequence of numbers named after Leonardo of Pisa, known as Fibonacci. The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, thus creating the sequence 0, 1, 1, 2, 3, 5, 8, etc.

Fibonacci numbers are the numbers in the following integer sequence:

By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. List of Fibonacci numbers The first 21 Fibonacci numbers Fn for n = 0, 1, 2, ... , 20 are:[14]
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17 F18 F19 F20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Constructors (C++ only) A constructor is a member function with the same name as its class. For example:
MMCT,Raipur Department of Computer Science and Engineering Page 32

Unix & Shell Programming

class X { public: X(); };

// constructor for class X

Constructors are used to create, and can initialize, objects of their class type. You cannot declare a constructor as virtual or static, nor can you declare a constructor as const, volatile, or const volatile. If a class has a constructor, each object of that type is initialized with the constructor prior to use in a program. (For more information about initialization, see Initialization Using Special Member Functions.) Constructors are called at the point an object is created. Objects are created as:
y y y y y y y

Global (file-scoped or externally linked) objects. Local objects, within a function or smaller enclosing block. Dynamic objects, using the new operator. The new operator allocates an object on the program heap or "free store." Temporary objects created by explicitly calling a constructor. (For more information, see Temporary Objects.) Temporary objects created implicitly by the compiler. (For more information, see Temporary Objects.) Data members of another class. Creating objects of class type, where the class type is composed of other class-type variables, causes each object in the class to be created. Base class sub object of a class. Creating objects of derived class type causes the base class components to be created.

Command use- The general function of the constructor function in C++Class user_name { private:

. Protected:

Public:

MMCT,Raipur Department of Computer Science and Engineering

Page 33

Unix & Shell Programming

User_name(); //constructor ..

}; User _name::user _name() { .. .. }

Source Code// (a) :#include <iostream.h> class fibonacci { private: unsigned long int f0,f1,fib; public : fibonacci () { // constructor f0=0; f1=1; fib=f0+f1; }

MMCT,Raipur Department of Computer Science and Engineering

Page 34

Unix & Shell Programming

void increment (){ f0=f1; f1=fib; fib=f0+f1; }void display () { cout<< fib<< \t : } } //end of class construction void main (void) { fibonacci number: for (int i=0;i<=15;++i){ number .display(); number. Increment(); } } (b) #include<iostream.h> class Fibonacci { private: unsigned long int f0,f1,fib; public : fibonacci () {

MMCT,Raipur Department of Computer Science and Engineering

Page 35

Unix & Shell Programming

f0=0; f1=1; fib=f0+f1; } fibonacci ( Fibonacci & ptr) { f0=ptr.f0; f1=ptr.f1; fib=ptr.fib; } void increment() { f0=f1: f1=fib; fib=f0+f1; } void display() { cout << fib << \t ; } }; // end of class construction void main (void) { fibonacci number; for (int i=0;i<=15;++i) {

MMCT,Raipur Department of Computer Science and Engineering

Page 36

Unix & Shell Programming

number.display(); number.increment(); } } Output: 1 2 3 5 8 13 21 34 54 89 144 233 377 610 987 15971 2 3 5 8 13 21 34

viva Questions and Answers:

Q: What is a default constructor? A: A constructor that has no arguments. Q: What is a conversion constructor? A: A constructor that accepts one argument of a different type. Q: What is the difference between a copy constructor and an overloaded assignment operator? A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class. Q: What is an explicit constructor? A: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. Its purpose is reserved explicitly for construction.

SOLUTION FOR PROGRAM - 09

MMCT,Raipur Department of Computer Science and Engineering

Page 37

Unix & Shell Programming

Aim:

Write a program to demonstrate how ambiguity is avoided using scope resolution operator in

the following inheritance (a) single inheritance (b) Multiple inheritance

Programming Constructs used:


scope resolution operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class.
int count = 0; int main(void) {

Commands used: C++ Scope Resolution Operator ::


::count = 1; count = 2; return 0; } // set global count to 1 // set local count to 2

int count = 0;

The declaration of count declared in the main() function hides the integer named count declared in global namespace scope. The statement ::count = 1 accesses the variable named count declared in global namespace scope.

Source Code: (a) #include <iostream.h> class baseA { private : int i; public : void getdata(int x); void display(); };

MMCT,Raipur Department of Computer Science and Engineering

Page 38

Unix & Shell Programming

class baseB { private : int j; public : void getdata(int y); void display (); }; class derivedC : public baseA,public baseB { }; void baseA :: getdata(int x) { i=x: } void baseA :: display() { cout << value of i+ << i<<end1; } void baseB :: getdata(int y) { j=y; }

MMCT,Raipur Department of Computer Science and Engineering

Page 39

Unix & Shell Programming

void baseB :: display ( ) { cout << value of j= << j <<endl; } void main() { derivedC objc: int x,y; cout << enter a value for I ?\n ; cin>> x; objc.baseA :: ambiguous without scope cout<< enter a value for j?\n ; cin>>y; objc.baseB::getdata(y); objc.baseB::display(); objc.baseA::display(); }

(b)

#Include <iostream.h> class baseA { public : int a;

MMCT,Raipur Department of Computer Science and Engineering

Page 40

Unix & Shell Programming

}; class baseB { public: int a; }; class baseC{ public: int a; }; class derived : public baseA,public baseB,public baseC { int a; }; void main() { derived objd; objd .A=10; objd .baseA ::a=20; objd .baseB ::a=30; objd .baseC ::a=40; cout<< value of a in the derived class= <<objd.a; cout<<endl;

MMCT,Raipur Department of Computer Science and Engineering

Page 41

Unix & Shell Programming

cout<< value of a in baseA= <<objd.baseA::a; cout<<endl; cout<< value of a in baseB= <<objd.baseB::a; cout<<endl; cout<< value of a in baseC= <<objd.basec::a; cout<<endl; cout<<endl; } Output: value of a in the derived class =10 value of a in baseA=20 value of a in baseB=30 value of a in baseC=40 Viva Questions and Answers: (1) What is a scope resolution operator?

Ans: A scope resolution operator (::), can be used to define the member functions of a class outside the<br>class. (2) What is a base class? Explain with an example using C++. Ans: Inheritance is one of the important features of OOP which allows us to make hierarchical classifications of classes. In this, we can create a general class which defines the most common features................... Read answer (3) C++ - What are the advantages of inheritance?

Ans: Advantages of Inheritance:

MMCT,Raipur Department of Computer Science and Engineering

Page 42

Unix & Shell Programming

y y

Allows the code to be reused as many times as needed. The base class once defined and once it is compiled, it need not be reworked. Saves time and effort as the main code need not be written again.

SOLUTION FOR PROGRAM - 10

Aim:

Write a program to perform the swapping of two data item of integer,floating

point number & character type with the help of function overloading. Programming Constructs used: Swap contents of two strings

Swaps the contents of the string objects lhs and rhs, such that after the call to this function, the contents of rhs are those which were in lhs before the call, and the contents of lhs are those which were in rhs. Notice that string objects implement a member function also called swap; In fact, this global function effectively calls:

lhs.swap(rhs);

Swap

In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program, two variables may be defined thus data_item x := 1 data_item y := 0 To swap them one might do swap (x, y); After swap() is performed, x will contain the value 0 and y will contain 1; their values have been exchanged. Of course, this operation may be generalized to other types of values, such as strings, aggregated data types and possibly entire containers. Swap methods Swapping data is a very important component of numerous algorithms. For example, many of the sorting algorithms, especially comparison sorts, utilize swaps to change the positions of data. Using a temporary variable
function . MMCT,Raipur Department of Computer Science and Engineering Page 43

Unix & Shell Programming

Overloading Function -

C++ permits the use of two function with the same name. However such functions essentially have different argument list. The difference can be in terms of number or type of arguments or both. This process of using two or more functions with the same name but differing in the signature is called function overloading. But overloading of functions with different return types are not allowed. In overloaded functions , the function call determines which function definition will be executed. The biggest advantage of overloading is that it helps us to perform same operations on different datatypes without having the need to use separate names for each version.

command

using swap function swap (x, y) temp := x x := y y := temp A fuction for swapping two integer is Void swap_int(int &a,int &b) use:

Source Code: #include<iostream.h> void swap (int &ix,int &iy); void swap (float &fx,float &fy); void swap (char &cx,char &cy); //function declaration void main(void) { int ix,iy; float fx,fy; MMCT,Raipur Department of Computer Science and Engineering Page 44

Unix & Shell Programming

char cx,cy; cout << enter any two integers <<endl; cin >> ix >> iy; cout << enter any two floating point numbers <<endl; cin >> fx >> fy; cout << enter any two characters <<endl; cin >> cx >>cy; //swapping on integers cout << swapping of integers \n ; cout<< ix= <<ix<< iy= <<iy<<endl; swap(ix,iy); cout << after swapping\n ; cout << ix= << ix<< iy= <<iy<<endl; // floating point numbers cout<<endl; cout << swapping of floating points numbers \n ; cout<< fx= <<fx<< fy= <<fy<<endl; swap(fx,fy); cout << after swapping\n ; cout << fx= <<fx<< fy= <<fy<<endl; //swapping on characters \n ; cout << endl;

MMCT,Raipur Department of Computer Science and Engineering

Page 45

Unix & Shell Programming

cout<< swapping of characters \n ; cout << cx= <<cx<< cy= <<cy<<endl; swap(cx,cy); cout << after swapping\n ; cout << cx= <<cx<< cy= <<cy<<endl; }void swap (int &a,int &b) { int temp; temp=a: a=b; b=temp; } void swap (float &a,float &b) { float temp; temp=a; a=b; b=temp; } void swap (char &a,char &b) { char temp;

MMCT,Raipur Department of Computer Science and Engineering

Page 46

Unix & Shell Programming

temp=a; a=b; b=temp; } Output: enter any two integers 100 200

enter ant two floating point numbers -11 22.22

enter any two characters s t

swapping of integers ix = 100 iy =200 after swapping ix=200 iy=100 swapping of floating point numbers fx==11.11 fy=-22.219999 afterswapping fx=22.219999 fy=-11.11 swapping of characters cx=t cy=s

MMCT,Raipur Department of Computer Science and Engineering

Page 47

Unix & Shell Programming

Viva Questions and Answers:

(1)

What is overloading unary operator?

Ans: Unary operators are those which operate on a single variable. Overloading unary operator means extending the operators original functionality to operate upon object of the class. (2) What is function overloading and operator overloading? Ans: Function overloading: A feature in C++ that enables several functions of the same name can be defined with different types of parameters or different number of parameters. This feature is called function overloading..................... Read answer (3) What is function overloading? Explain with an example. Ans: Function overloading is the process of using the same name for two or more functions. The secret to overloading is that each redefinition of the function must use either different types of parameters or a...................... Read answer .
SOLUTION FOR PROGRAM - 11

Aim:

Write a program to generate a fiboncci series by overloading (a) Prefix operator (b) Post fix operator.

Programming Constructs used:

FIBONACCI SERIES The Fibonacci series begins with 0 and 1 followed by Fibonacci numbers which are the sum of the previous two Fibonacci numbers. For example, the first 26 numbers of the Fibonacci series are as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, and 75025.

Both the increment operator (++) and the decrement operator(--) come in two varieties: prefix and postfix. The prefix variety is written before the variable name (++myAge); the postfix variety is written after (myAge++). In a simple statement, it doesn't much matter which you use, but in a complex statement, when you are incrementing (or decrementing) a variable and then assigning the result to another variable, it matters very much. The prefix operator is evaluated before the assignment, the postfix is evaluated after.
MMCT,Raipur Department of Computer Science and Engineering Page 48

Unix & Shell Programming

The semantics of prefix is this: Increment the value and then fetch it. The semantics of postfix is different: Fetch the value and then increment the original. This can be confusing at first, but if x is an integer whose value is 5 and you write
int a = ++x;

you have told the compiler to increment x (making it 6) and then fetch that value and assign it to a. Thus, a is now 6 and x is now 6. If, after doing this, you write
int b = x++;

the compiler to fetch the value in x (6) and assign it to b, and then go back and increment x. Thus, b is now 6, but x is now 7.

Commands used : Overloading of an increment operator with prefix operator Class fibonacci { Public : Void operator++() .. .. }; Void Fibonacci :: operator ++() { .. .. } Void main()

MMCT,Raipur Department of Computer Science and Engineering

Page 49

Unix & Shell Programming

{ .. .. ++ obj; } Overloading of an increment operator with postfix operator Class Fibonacci { Public: Fibonacci operator++(int); }; Fibonacci Fibonacci :: operator++(int x) {

.. Return*this; } Void main() { Fibonacci obj;

..

MMCT,Raipur Department of Computer Science and Engineering

Page 50

Unix & Shell Programming

Obj++; } Source Code: #include<iostream.h. class Fibonacci { private : unsigned long int f0,f1,fib; public : fibonacci () ; // constructor void operator ++(); void display (); }; fibonacci :: Fibonacci () { f0=0; f1=1; fib=f0+f0+f1; } void Fibonacci :: display() { cout << fib << \t ; }

MMCT,Raipur Department of Computer Science and Engineering

Page 51

Unix & Shell Programming

void Fibonacci :: operator :: operator++() { f0 =f1; f1=fib; fib=f0+f1; } void main() { fibonacci obj; int n; cout << how many Fibonacci number are to be ; cout << dis played ?\n ; cin >> n; for ( int i=0;i<=n-1;++i) { obj .display(); ++obj; } } (b) // Post fix operator. include<iostream.h. class Fibonacci { private :

MMCT,Raipur Department of Computer Science and Engineering

Page 52

Unix & Shell Programming

unsigned long int f0,f1,fib; public : fibonacci ( ) ; // constructor fibonacci operator ++(int); void display (); }; fibonacci :: Fibonacci () { f0=0; f1=1; fib=f0+f1; } void Fibonacci :: display() { cout << fib << \t ; } fibonacci Fibonacci :: operator :: operator++(int x) { f0 =f1; f1=fib; fib=f0+f1; return * this ;

MMCT,Raipur Department of Computer Science and Engineering

Page 53

Unix & Shell Programming

} void main() { fibonacci obj; int n; cout << how many Fibonacci number are to be ; cout << dis played ?\n ; cin >> n; for ( int i=0;i<=n-1;++i) { obj .display(); obj ++; } } Output: 1 2 3 5 8 13 21 34 54 89 144 233 377 610 987 1597

Viva Questions and Answers: (2)What is pretfix operator?

Ans: The prefix increment operator (++) adds one to its operand; this incremented value is the result of the expression. The prefix decrement operator () is analogous to the prefix increment operator, except that the operand is decremented by one and the result is this decremented value.
--x;

denote prefix decrement operator.


MMCT,Raipur Department of Computer Science and Engineering Page 54

Unix & Shell Programming

(2)What is postfix operator?

Ans: the postfix form, the increment or decrement takes place after the value is used in expression evaluation.
x--;

denote postfix-decrement operator and (3) What is the difference between postfix & prefix operator? Ans: The difference between the two is that in the postfix notation, the operator appears after postfix-expression, whereas in the prefix notation, the operator appears before expression, for example

SOLUTION FOR PROGRAM - 12

Aim: Write a program to access the private data of a class by non member function through friend function where the friends function is declared (1) is the location of public category (2) is the location of private category (3) With in the scope of a class definition itself (4) Defined with inline code subtraction .

a class with private data members, for example that those data members are not accessible outside the class or they are not accessible outside the objects of that class.

A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and >) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

Commands used : declaration of friend function in public groupMMCT,Raipur Department of Computer Science and Engineering Page 55

Unix & Shell Programming

class first { int x; public: void getdata(); friend void getdata (); friend void disp(); }; friend function in the private grup class second { private : int x; friend void disp(); public : void getdata(); };

Source Code: (a) //declare friend function #include <iostream.h> class sample { private:

MMCT,Raipur Department of Computer Science and Engineering

Page 56

Unix & Shell Programming

int x; public : void getdata((); friend void display(class sample); }; void sample :: getdata () { cout << enter a value for x\n cin >> x; } void display (class sample abc) { cout << enter a value for x \n ; cin >> x; } void display (class sample abc) { cout << entered number is : <<abc.x; cout << end1; } void main() {

MMCT,Raipur Department of Computer Science and Engineering

Page 57

Unix & Shell Programming

sample obj; obj.getdata(); cout << accessing the private data by non member ; cout << function\n ; display (obj); } Output: enter a value for x 10 accessing the private data by non member function Entered number is : 10

(b) //declearing friend function #include <iostream.h> class sample { private : int x; friend void display (class sample); public : void getdata(); }; void sample :: getdata()

MMCT,Raipur Department of Computer Science and Engineering

Page 58

Unix & Shell Programming

{ cout<< enter a value for x \n ; cin >. X; } void display(class sample abc) { cout << entered number is : <<abc.x; cout << endl; } void main () { sample obj; obj.getdata(); cout<< accessing the private data by non member ; cout<< function \n ; display (obj); } Output: enter a value for x 10 accessing the private data by non-member function entered numer is :10

MMCT,Raipur Department of Computer Science and Engineering

Page 59

Unix & Shell Programming

(c) //friend function is defined within the scope of a class definition #include <iostream.h> class sample { private : int x; public : inline void getdata(); friend void display (sample abc) { cout << enter number is : <<abc.x; cout <<endl; } }; inline void sample :: getdata () { cout << enter a value for x\n ; cin >>x; } void main() { sample obj; obj.getdata(); cout<< accessing the private data by non-member :

MMCT,Raipur Department of Computer Science and Engineering

Page 60

Unix & Shell Programming

cout << function\n ; display (obj); } (d) //Declering friend function with inline code #include <iostream.h> class sample { private : int x; public : inline void getdata(); friend void display ( class sample ) ; }; inline void sample :: getdata () { cout << enter a value for x \n ; cin >>x; } inline void display(class sample abc) { cout << enter number is :<<abc.x ; cout end1; }

MMCT,Raipur Department of Computer Science and Engineering

Page 61

Unix & Shell Programming

void main() { sample obj; obj.getdata(); cout<< accessing the private data by non-member : cout << function\n ; display (obj); } Viva Questions and Answers:

(1) What is a friend function? Ans:A friend function is a function, which have a direct access to the class data members(either private or public) from outside the class. <br>It is declared within the class with a prefix " friend ".<br>
(2) Friend function can access the private data member of a single or more than two classes. Ans: Yes (3) What is a member & non member function? Ans: Member functions are operators and functions that are declared as members of a class. i.e declared inside the definition of the class. Non member functions are those declared outside the definition of the class............

SOLUTION FOR PROGRAM - 13

MMCT,Raipur Department of Computer Science and Engineering

Page 62

Unix & Shell Programming

Aim:

Write a program to demonstrate how a pure virtual function defined and invoked from the

object of derived class through the pointed of the base class


C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. The whole function body can be replaced with a new set of implementation in the derived class. The concept of c++ virtual functions is different from C++ Function overloading.

C++ Virtual Function - Properties:


C++ virtual function is, y y y y A member function of a class Declared with virtual keyword Usually has a different functionality in the derived class A function call is resolved at run-time

n object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP)

Commands used : In a pure virtual function Void base :: getdata () // pure virtual definition and Void base :: display()//pure virtual function definition Source Use.

Source Code: #include <iostream.h> class base { private : int x; float y; public : MMCT,Raipur Department of Computer Science and Engineering Page 63

Unix & Shell Programming

virtual void getdata (); virtual void display(); }; class derivedB : public base { private : long int r0llno; char name[20]; public : void getdata(); void display(); }; void base :: getdata() { } void base :: display() { } void derivedB :: getdata() { cout<< enter roll number of a student ? \n cin >> rollno; cout << enter name of student ? \n ; ;

MMCT,Raipur Department of Computer Science and Engineering

Page 64

Unix & Shell Programming

cin >> name; } void derivedB :: display() { cout << Roll number student`s name \n ; cout << rollno << `\t` << name << endl; } void main() { base *ptr; derivedB obj ; ptr = &obj; ptr->getdata(); ptr->display(); } Commands used: Implementations of conditional statement(switch statement) & form series in C++. Output: Enter roll number of a student ? 95001 Enter name of a student ? Umesh Roll number student`s name

MMCT,Raipur Department of Computer Science and Engineering

Page 65

Unix & Shell Programming

95001

umesh

Viva Questions and Answers: (1) What is a virtual function? Ans: a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature. (2)What is derived class ? Ans: class that was created based on a previously existing class (i.e., base class). A derived class inherits all of the member variables and methods of the base class from which it is derived.

SOLUTION FOR PROGRAM 14

Aim: Write a program to Bubble Sort Using template function.

Programming Constructs used:

A wrapper class for the bubblesort, where the constructor takes three parameters: (a number array or a string array), the number of elements in the array and a static compare function. This function does not need to be passed in case you are using float, double, int, etc as first parameter.

The main class shows two scenarios: 1.) bubble sort an array of ints 2.) bubble sort an array of strings the array of strings requires a comparison function, which is defined above main (grt). MMCT,Raipur Department of Computer Science and Engineering Page 66

Unix & Shell Programming

tor.

Bubble Sort Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive. Algorithm
1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. 2. If at least one swap has been done, repeat step 1.

Complexity analysis Bubble sort is adaptive. It means that for almost sorted array it gives estimation. Avoid implementations, which don't check if the array is already sorted on every step (any swaps made). This check is necessary, in order to preserve adaptive property

Commands used : The general syntax for declearing a function template . Template <class T> T function _name(T formal arguments) { ..

return(T); } Source Code: #include <iostream> using namespace std; template <class X> void bubble(X *items,int count) { MMCT,Raipur Department of Computer Science and Engineering Page 67

Unix & Shell Programming

X t; for(int a=1; a<count; a++) for(int b=count-1; b>=a; b--) if(items[b-1] > items[b]) { t = items[b-1]; items[b-1] = items[b]; items[b] = t; } } int main() { int iarray[7] = {7, 5, 4, 3, 9, 8, 6}; double darray[5] = {4.3, 2.5, -0.9, 10.2, 3.0}; cout << "Here is unsorted integer array: "; for(int i=0; i<7; i++) cout << iarray[i] << ' '; cout << endl; bubble(iarray, 7); cout << "Here is sorted integer array: "; for(int i=0; i<7; i++) cout << iarray[i] << ' '; cout << endl; cout << "Here is unsorted double array: "; for(int i=0; i<5; i++) cout << darray[i] << ' '; cout << endl; MMCT,Raipur Department of Computer Science and Engineering Page 68

Unix & Shell Programming

bubble(darray, 5);

cout << "Here is sorted double array: "; for(int i=0; i<5; i++) cout << darray[i] << ; cout << endl;

return 0; }

Output: Here is unsorted integer array: 7 5 4 3 9 8 6 Here is sorted integer array: 3 4 5 6 7 8 9 Here is unsorted double array: 4.3 2.5 -0.9 10.2 3 Here is sorted double array: -0.9 2.5 3 4.3 10.2

Viva Questions and Answers: (1) What is Bubble sort? Ans:- The entered integers are stored in the array A. Here, to sort the data in ascending order, any number is compared with the next numbers for orderliness.

(2) What is template function ? Ans: Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

MMCT,Raipur Department of Computer Science and Engineering

Page 69

Unix & Shell Programming

SOLUTION FOR PROGRAM - 15

Aim: Write a program for invoking for that Generate & Handle exception.

Programming Constructs used:

Exceptions are run-time anomalies, such as division by zero, that require immediate handling when encountered by your program. The C++ language provides built-in support for raising and handling exceptions. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code that is outside the normal flow of control.

In C++, the process of raising an exception is called "throwing" an exception. A designated exception handler then "catches" the thrown exception.

C++ exception handling is thread safe. Throwing on one thread (including rethrow) has no impact on any throw/catch in progress on another thread. A programming language is an artificial language designed to express computations that can be performed by a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely. A programming language is usually split into the two components of syntax (form) and semantics (meaning). Some languages are defined by a specification document (for example, the C programming language is specified by an ISO Standard), while other languages, such as Perl, have a dominant implementation that is used as a reference. exception specifications
When declaring a function we can limit the exception type it might directly or indirectly throw by appending a throw suffix to the function declaration:

float myfunction (char param) throw (int);

This declares a function called myfunction which takes one augment of type char and returns an MMCT,Raipur Department of Computer Science and Engineering Page 70

Unix & Shell Programming

element of type float. The only exception that this function might throw is an exception of type int. If it throws an exception with a different type, either directly or indirectly, it cannot be caught by a regular int-type handler. If this throw specified is left empty with no type, this means the function is not allowed to throw exceptions. Functions with no throw specifier (regular functions) are allowed to throw exceptions with any type:

1 int myfunction (int param) throw(); // no exceptions allowed 2 int myfunction (int param); // all exceptions allowed

Standard exceptions
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has the usual default and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null-terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

Command use :- Syntax of the exception handler isTry (expression) Catch(exception detector) { .. .. } Throw (expression){ ..

//error message }

Source code MMCT,Raipur Department of Computer Science and Engineering Page 71

Unix & Shell Programming

#include

<iostream.h>

#include <windows.h> using std::cout; using std::endl; struct EXCEPTION_REGISTRATION { EXCEPTION_REGISTRATION *prev; DWORD handler; }; EXCEPTION_DISPOSITION myHandler( EXCEPTION_RECORD *ExcRecord, void * EstablisherFrame, CONTEXT *ContextRecord, void * DispatcherContext) { cout << "In the exception handler" << endl; cout << "Just a demo. exiting..." << endl; exit(0); return ExceptionContinueExecution; //will not reach here } int g_div = 0; void bar() { //initialize EXCEPTION_REGISTRATION structure EXCEPTION_REGISTRATION reg, *preg = &reg; reg.handler = (DWORD)myHandler; //get the current head of the exception handling chain DWORD prev; _asm { mov EAX, FS:[0] mov prev, EAX } reg.prev = (EXCEPTION_REGISTRATION*) prev; //register it! _asm { mov EAX, preg mov FS:[0], EAX }
MMCT,Raipur Department of Computer Science and Engineering Page 72

Unix & Shell Programming

//generate the exception int j = 10 / g_div; } int main() { bar(); return 0; } Output: In the exception handler generate programe //Exception. Divide by 0.

Viva Questions and Answers: (1) What is a exception?

Ans:- Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. (2) What is Exception handling ? Ans:- Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program.
Bibliography:

(1)Progmming with C++: D ravichandran (2)OOP S with C++: E.balaguruswamy (3)Let us C++ : Yeswant kanetkar

MMCT,Raipur Department of Computer Science and Engineering

Page 73

You might also like