You are on page 1of 23

Q Name the header files that shall be needed for the following code: void main( ) { char String[

] = .Peace.; cout << setw(2)<<String; } Ans) iomanip.h iostream.h Q Explain different types of errors in C++. Ans Run Time Errors: Errors that occur during the execution of a program are called as run time errors. It is caused of some illegal operation taking place or in availability of desired or required conditions for the execution of the program. For instance, if a program is trying to open a file which does not exist or it could not be opened, it results into an execution error. Similarly, if enough memory is not available or an expression is trying to divide a number by zero are run-time errors. Eg: Division by zero. c=a/b ; User will give the values of a and b at the time of program execution. If the value of b as 0, then division by zero, i.e. a run time error occurs. Syntax Errors: Syntax errors occur when rules of a programming languages (syntax) is misused. i.e. when a grammatical rule of C++ is violated. Eg (i) c=a+b In this statement, since there is no semicolon at the end of the statement, there will occur a syntax error. (ii)cin<<a; In this statement, since stream insertion operator (<<) has given instead of stream extraction operation(>>), there will occurs a syntax error. Logical Error: A logical error is that error which causes a program to produce incorrect or undesired output. An incorrectly implemented algorithm or use of a variable before its initialization, or unmarked end for a loop, or wrong parameters passed are causes logical errors. These must be handled carefully. For instance, if we are trying to print the table of a number 5 and if we say counter=1; while(counter>8) { cout<<n*counter; counter=counter+1; } Here the loop would not be executed even once as the condition (counter>8) is not fulfilled at all. Therefore, no output will be produced. Such an error is logical error. Q Differentiate between a Call by Value and Call by Reference, giving suitable examples of each. Ans: Call by value: In call by value method, the called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the original variables (actual parameters) and can only work on the copies of values it created. Passing arguments by value is useful when the original values are not to be modified. In call by reference method, a reference to the actual argument (original variable) is passed to the called function. (Reference is an alias for a predefined variable. i.e. the same variable value can be accessed by any of the two names: the original variables name and the reference name.) Thus, in

call by reference method, the changes are reflected back to the original values. The call by reference method is useful in situations where the values of the original variables are to be changed using a function. Program to illustrate the call by value method of function invoking: #include<iostream.h> #include<conio.h> int change(int); void main( ) { clrscr( ); int orig=10; cout<<\nThe original value is<<orig<<\n; cout<<\nReturn value of function change()is<<change(orig)<<\n; cout<<\nThe value after function change() is over<<orig<<\n; getch(); } int change(int duplicate) { duplicate=20; return duplicate; } Ans: Output: The original value is 10 Return value of function change() is 20 The value after function change() is over 10 Program to illustrate the call by Reference method of function invoking: #include<iostream.h> #include<conio.h> int change(int&); void main( ) { clrscr( ); int orig=10; cout<<\nThe original value is<<orig<<\n; cout<<\nReturn value of function change()is<<change(orig)<<\n; cout<<\nThe value after function change() is over<<orig<<\n; getch(); } int change(int &duplicate) { duplicate=20; return duplicate; } Output: The original value is 10 Return value of function change() is 20 The value after function change() is over 20 Q What is the difference between global variables and local variables? Give an example to illustrate the same. Ans: The local variables are the variables defined within any function (or block) and are hence accessible only within the block in which they are declared. In contrast to local variables, variables declared outside of all the functions in a program are

called global variables. These variables are defined outside of any function, so they are accessible to all functions. These functions perform various operations on the data. They are also known as External Variables. Eg: #include<iostream.h> int a,b; void main() { float f; ---; ---; } In the above program segment, a and b are global variables, we can access a and b from any function. f is local variable to function main( ), we can access f from main( ) only. Q Why main( ) function is so special. Give two reasons? Ans: Execution of the program starts and ends at main( ). The main( ) is the driver function of the program. If it is not present in a program, no execution can take place. Q What is the difference between #define and const? Explain with suitable example. Ans: While they both serve a similar purpose, #define and const act differently. When using #define the identifier gets replaced by the specified value by the compiler, before the code is turned into binary. This means that the compiler makes the substitution when you compile the application. Eg: #define number 100 In this case every instance of .number. will be replaced by the actual number 100 in your code, and this means the final compiled program will have the number 100 (in binary). #define with different types of data:

Eg:

#define PI 3.14159

Eg: #define MAX 70 Before compilation, if the C++ preprocessor finds MAX as one word, in the source code, it replaces it with the number 70. Eg: #define SQUARE(x) x*x Before compilation, if the C++ preprocessor finds SQUARE(x), where x is any value in the source code, it replaces it with its square (ie x*x). Here a macro substitutes text only; it does not check for data types. On the other hand, when we use const and the application runs, memory is allocated for the constant and the value gets replaced when the application is run. Syntax: const type variable_name=value; Eg: const int a=10; The value of a constant is fixed and in the above example, the value for a in entire program is 10 only. You cannot change the value of a, since it is declared as constant. Difference between #define and const in declaration? 1.#define: #define symbolic_constant value. Eg: #define number 100 //No semicolon ,no equal to symbol. 2.const: const type variable_name=value; Eg: const number=100; //Semicolon, equal to symbol.

What is the purpose of using a typedef command in C++? Explain with suitable example. Ans: C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a new name for an existing type. This can increase the portability of a program as only the typedef statements would have to be changed. Typedef makes your code easier to read and understand. Using typedef can also aid in self documenting your code by allowing descriptive names for the standard data types. The syntax of the typedef statement is typedef type name; Where type is any C++ data type and name is the new name for this type. This defines another name for the standard type of C++. For example, you could create a new name for float values by using the following statement: typedef float amount; This statement tells the compiler to recognize amount as an alternative name for float. Now you could create float variables using amount. Amount_loan, saving, installment; Using typedef does not replace the standard C++ data type name with the new name, rather the new name is in addition to the existing name. You still can create float variables using float. Once a new name has been defined by typedef, it can be used as a type for another typedef also. Eg: typedef amount money; Now, this statement tells the compiler to recognize money as another name for amount, which itself is another name for float. Typedef does not create any new data types rather provides an alternative name for standard types. Reference provides an alias name for a Variable and typedef provides an alias name for a data type. Illustrate the use of #define in C++ to define a macro. Ans: The #define preprocessor can be used in the creation of macros (code substitution). Eg: #define SQUARE(x) x*x Before compilation, if the C++ preprocessor finds SQUARE(x), where x is any value in the source code, it replaces it with its square (ie x*x). Here a macro substitutes text only; It does not check for data types. #define CUBE(x) SQUARE(x)*x In the program, cout<<CUBE(5); Will replaced with SQUARE(5)*5 and ThenSQUARE(5) will be replaced with 5*5 so, the final substitution is cout<<5*5*5 ; What is polymorphism? Give an example in C ++ to show its implementation in C++. Ans: Polymorphism is the attribute that allows one interface to be used with different situation. C++ implements polymorphism through virtual functions, through overloaded functions and overloaded operators. An overloaded function refers to a function having (one name and) more than one distinct meanings. Similarly, when two or more distinct meanings are defined for an operator, it is said to be an overloaded operator. It is the compilers job to select the specific action as it applies to each situation. What do you understand by function overloading? Give an example illustrating its use in a c++ program. Ans: A function name having several definitions that are differentiable by the number or types of their arguments is known as an overloaded function and this process is known as function overloading. Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby makes the program run faster. Example program illustrating function overloading: //Program to find out area of a circle or area of rectangle using function overloading. #include<iostream.h> #include<conio.h>

void area(float r) { cout<<.nThe area of the circle = <<3.1415*r*r; } void area(float l,float b) { cout<<\nThe area of the rectangle = <<l*b; } void main( ) { float rad,len,bre; int n; clrscr( ); cout<<\n1. Area of a Circle.; cout<<\n2. Area of a Rectangle.; cout<<\n\nEnter your choice:.; cin>>n; switch(n) { case 1: cout<<\nEnter the radius: ; cin>>rad; area(rad); break; case 2: cout<<\nEnter the length and breadth: ; cin>>len>>bre; area(len,bre); break; default: cout<<\nYou have to enter either 1 or 2; } //end of switch getch( ); } Find the output of the following program: #include<iostream.h> #include<string.h> #include<ctype.h> void Change(char Msg[],int Len) { for(int Count=0;Count<Len;Count++) { if(islower(Msg[Count])) Msg[Count] = toupper(Msg[Count]); else if(isupper(Msg[Count])) Msg[Count] = tolower(Msg[Count]); else if (isdigit(Msg[Count])) Msg[Count]=Msg[Count]+1; else Msg[Count] = .*.; } } void main( ) { char Message[ ]=.2005 Tests ahead.; int Size=strlen(Message); Change(Message,Size); cout<<Message<<endl; for(int C=0,R=Size . 1; C<=Size/2;C++,R--)

{ char Temp=Message[C]; Message[C]=Message[R]; Message[R]=Temp; } cout<<Message<<endl; } Ans: Output: 3116*tESTS*AHEAD DAEHA*SSTEt*6113 Q Difference between if and switch.case. AnsThe if statement can be used to test conditions so that we can alter the flow of a program. In other words: if a specific statement is true, execute this instruction. If not true, execute this instruction. IF Statement: Checks the value of data is less than or greater than. (in ranges). example: can tell whether an input age is more than 18 and less than 60. If (age>18) cout<<Eleigible to vote; else cout<<\n not eligible to vote; The switch statement is almost the same as an if statement. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variables equals the condition, the instructions are executed. It is also possible to add a default. If none of the variable equals the condition the default will be executed. Switch Case: Checks the value of data that is pre specified only equal to =. switch(ch) cout<<\one; will be executed if value of ch is 1 { case 1: cout<<\n one; break; case 2:cout<<\two;break; default:cout<<error; default is the last case, & is executed if none of the }
value is present

Q What is the difference between entry control or exit control loop? Give example Or difference between while and dowhile loop? Ans Entry Controlled will check the Condition at First and doesn't execute if it is False eg. While and for loop while (condition) { Statements; } Exit Controlled will check the Condition at Last and at least once the statement will execute though it is False eg dowhile loop. do { Statements;

}while(condition); Q Define function and give example. Ans A function is a group of statements that is executed when it is called from some point of the program. Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. The following is its format: type name ( parameter1, parameter2, ...) { statements } where: type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. statements is the function's body. It is a block of statements surrounded by braces { }. Here you have the first function example: 1 // function example 2 #include <iostream> 3 using namespace std; 4 5 int addition (int a, int b) 6 { 7 int r; 8 r=a+b; 9 return (r); 10 } 11 12 int main () 13 { 14 int z; 15 z = addition (5,3); 16 cout << "The result is " << z; 17 return 0; 18 } Q What is function prototyping & function definition? Ans In C++, a function prototype is a declaration to the compiler that a certain function exists, without a full definition. This allows other functions to call that function. The linker will later make sure that a function definition actually exists (perhaps somewhere else), and will turn the call to the function to a call to the correct function. Function prototypes exist in C++ and essentially are initializations of functions, meaning that they define the type and the arguments of the function, they omit the contents. Most of the time these are located in a header (or .h) file, while the contents are in a C++ ( .cpp) file. Example: int add(int a, int b); //Function prototype.

int add(int a, int b) // Function Definition. { return a + b; } Q Differentiate between break, continue, exit & return Ans break - The break statement is used to jump out of loop. After the break statement control passes to the immediate statement after the loop. Passes control out of the compound statement. The break statement causes control to pass to the statement following the innermost enclosing while, do, for, or switch statement. The syntax is simply break; continue - Using continue we can go to the next iteration in loop. exit - it is used to exit the execution of program. Exit terminates the entire program. If you just want to stop looping, you use break. If you want to stop the current loop iteration and proceed to the next one, you use continue. note: break and continue are statements, exit is function. return: Exits the function. Return exits immediately from the currently executing function to the calling routine, optionally returning a value. The syntax is: return [expression];
Expression or value is optional a void function will not have an expression or value

For example, int sqr (int x) void display() { { return (x*x); cout<<hello; return; } } What is goto statement in c++. Give example Goto performs a one-way transfer of control to another line of code; in contrast a function call normally returns control. The jumped-to locations are usually identified using labels. A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label. A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be redeclared. #include<stdio.h> #include<conio.h> void main() { int x; printf("enter a number "); scanf("%f",&x); if (x%2==0) goto even; else goto odd; even : printf("\n %f is even no"); return; odd: printf("\n %f is odd no"); getch(); }

Q What is nested if? Ans It means one if statement inside another if statement or if in else. if( condition ) { if( some other condition) { } else { } } else { if( another condition) { } } Q cWhat are types of exit? Ans Exit are of 2 type:- normal & abnormal exit. Normal exit takes place when loops test condition fails. In this case\, control is transferred to first executable statement following the loop statement or nest statement of loop statement. Eg for(int i=0;i<10;i++) { cout<<i; } Abnormal exit takes place when the control from the loop to some other statement, the next statement of the loop or elsewhere even if the condition is true. Eg Loop will terminate when i=5, though loop for(int i=0;i<10;i++) { condition is still true. If (i==5) break; cout<<i; } Q Define manipulator & give example Ans A manipulator in C++ construct is used to control formatting of output and/ or input values. Manipulator can only be present in i-o statements like endl. endl is defined in iostream.h Q Differnetiate between get(), getchar(), getch(), getche(). Ans Get(): The get() input a single character from standard input device and waits for enter key cin.get(ch); it belong to iostream.h getchar() : It works differently from others two. Whenever you are pressing any key then the these are kept in Buffer. After hitting enter the first character gets processed. And it obviously echoes on the screen. Eg getchar(ch); Belongs to stdio.h getch() : It reads a character and never wait for Enter key.Just gets processed after getting any key pressed.And it never echoes the character on screen which u pressed. Eg ch=getch();Belongs to conio.h getche() : it works same as getch() but it echoes on screen. Eg ch=getche();Belongs to conio.h

A structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable and to its parts as members of that variable by using the dot (.) operator. The power of structures lies in the fact that once defined, the structure name becomes a user-defined data type and may be used the same way as other built-in data types, such as int, double, char. struct STUDENT { int rollno, age; char name[80]; float marks; }; void main() { STUDENT s1, s3; // declare two variables of the new type cin>>s1.rollno>>s1.age>>s1.name>>s1.marks; //accessing of data members cout<<s1.rollno<<s1.age<<s1.name<<s1.marks; STUDENT s2 = {100,17,Aniket,92}; //initialization of structure variable cout<<s2.rollno<<s2.age<<s2.name<<s2.marks; s3=s2; //structure variable in assignment statement cout<<s3.rollno<<s3.age<<s3.name<<s3.marks; } Defining a structure When dealing with the students in a school, many variables of different types are needed. It may be necessary to keep track of name, age, Rollno and marks point for example. struct STUDENT { int rollno, age; char name[80]; float marks; }; STUDENT is called the structure tag, and is your brand new data type, like int, double or char. rollno, name, age, and marks are structure members. Declaring Variables of Type struct The most efficient method of dealing with structure variables is to define the structure globally. This tells "the whole world", namely main and any functions in the program, that a new data type exists. To declare a structure globally, place it BEFORE void main(). The structure variables can then be defined locally in main, for example struct STUDENT { int rollno, age; char name[80]; float marks; }; Declaring Variables of Type struct The most efficient method of dealing with structure variables is to define the structure globally. This tells "the whole world", namely main and any functions in the program, that a new data type exists. To declare

a structure globally, place it BEFORE void main(). The structure variables can then be defined locally in main, for example struct STUDENT { int rollno, age; char name[80]; float marks; }; void main() { // declare two variables of the new type STUDENT s1, s3; } Alternate method of declaring variables of type struct: struct STUDENT { int rollno, age; char name[80]; float marks; } s1, s3; Accessing of data members The accessing of data members is done by using the following format: structure variable.member name for example cin>>s1.rollno>>s1.age>>s1.name>>s1.marks; Initialization of structure variable Initialization is done at the time of declaration of a variable. For example STUDENT s2 = {100,17,Aniket,92}; Structure variable in assignment statement The statement s3=s2; assigns the value of each member of s2 to the corresponding member of s3. Note that one structure variable can be assigned to another only when they are of the same structure type, otherwise complier will give an error eg. struct X { int x,y; }X1,X2; struct Y {

int x,y; }Y1,Y2; X1=X2; X1=Y1;

//Correct as the data type is same //invalid or incorrect as the data type is different

X1=X2; Will assign all the data of X2 to X1

X1

10

12

X2

10

12

Nested structure (Structure within structure) It is possible to use a structure to define another structure. This is called nesting of structure. Consider the following program struct DAY { int month, date, year; }; struct STUDENT { int rollno, age; char name[80]; day date_of_birth; float marks; }; typedef It is used to define new data type for an existing data type. It provides and alternative name for standard data type. It is used for self documenting the code by allowing descriptive name for the standard data type. The general format is: typedef existing datatype new datatype for example: typedef float real; Now, in a program one can use data type real instead of float. Therefore, the following statement is valid: real amount;

A RRAY

An array is a collection of data elements of same data type. It is described by a single name and each element of an array is referenced by using array name and its subscript no.

Declaration of Array Type arrayName[numberOfElements]; For example, int Age[5] ;

Initialization of One Dimensional Array

An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within braces. int A[5] = {11,2,23,4,15}; It is possible to leave the array size open. The compiler will count the array size. int B[] = {6,7,8,9,15,12}; Referring to Array Elements

In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as: name[index] Examples: cout<<age[4]; //print an array element age[4]=55; // assign value to an array element

cin>>age[4];

//input element 4

Using Loop to input an Array from user

int age [10] ; for (i=0 ; i<10; i++) { cin>>age[i]; }

Arrays as Parameters

At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address.

21

www.cppforschool.com

For example, the following function: void print(int A[]) accepts a parameter of type "array of int" called A. In order to pass to this function an array declared as: int arr[20]; we need to write a call like this:

print(arr);

Here is a complete example: #include <iostream.h> void print(int A[], int length) { for (int n=0; n<length; n++) cout << A[n] << " "; cout << "\n"; } void main () { int arr[] = {5, 10, 15}; print(arr,3); }

B ASIC OPERATION ON O NE DIMENSIONAL ARRAY

Function to traverse the array A

void display(int A[], int n)

{ cout<<"The elements of the array are:\n"; for(int i=0;i<n;i++) cout<<A[i]; }

Function to Read elements of the array A

void Input(int A[], int n) { cout<<"Enter the elements:"; for(int i=0;i<n;i++) cin>>A[i]; }

22

www.cppforschool.com

Function to Search for an element from A by Linear Search

int Lsearch(int A[], int n, int Data) { int I; for(I=0; I<n; I++) {

if(A[I]==Data) { cout<<"Data Found at : "<<I; return; } } cout<<"Data Not Found in the array"<<endl; }

Function to Search for an element from Array A by Binary Search

int BsearchAsc(int A[], int n, int data) { int Mid,Lbound=0,Ubound=n-1,Found=0; while((Lbound<=Ubound) && !(Found)) { Mid=(Lbound+Ubound)/2; if(data>A[Mid]) Lbound=Mid+1; else if(data<A[Mid]) Ubound=Mid-1; else Found++; } //Searching The Item

if(Found) return(Mid+1); else return(-1); //returning -1,if not present } //returning 1ocation, if present

Function to Sort the array A by Bubble Sort

void BSort(int A[], int n) { int I,J,Temp; for(I=0;I<n-1;I++) //sorting { for(J=0;J<(n-1-I);J++) 23 www.cppforschool.com if(A[J]>A[J+1]) { Temp=A[J]; //swapping A[J]=A[J+1]; A[J+1]=Temp; } } }

Function to Sort the array ARR by Insertion Sort

void ISort(int A[], int n) { int I,J,Temp; for(I=1;I<n;I++) //sorting { Temp=A[I]; J=I-1; while((Temp<A[J]) && (J>=0)) { A[J+1]=A[J]; J--; } A[J+1]=Temp; } }

Function to Sort the array ARR by Selection Sort

void SSort(int A[], int n) { int I,J,Temp,Small;

for(I=0;I<n-1;I++) { Small=I; for(J=I+1;J<n;J++) //finding the smallest element if(A[J]<A[Small]) Small=J; if(Small!=I) { Temp=A[I]; //Swapping A[I]=A[Small]; A[Small]=Temp; }

24 www.cppforschool.com } }

TWO DIMENSIONAL ARRAYS (C++ implementation)

Function to read the array A void Read(int A[][20], int N, int M) { for(int R=0;R<N;R++) for(int C=0;C<M;C++)

{ cout<<"(R<<','<<")?"; cin>>A[R][C]; } }

Function to display content of a two dimensional array A void Display(int A[][20],int N, int M) { for(int R=0;R<N;R++) { for(int C=0;C<M;C++) cout<<A[R][C]; cout<<endl; } }

Function to find the sum of two dimensional arrays A and B void Addition(int A[][20], int B[][20],int N, int M) { for(int R=0;R<N;R++) for(int C=0;C<M;C++) C[R][C]=A[R][C]+B[R][C]; }

Function to multiply two dimensional arrays A and B of order NxL and LxM void Multiply(int A[][20], int B[][20], int C[][20],int N, int L, int M) { for(int R=0;R<N;R++) for(int C=0;C<M;C++) { C[R][C]=0; for(int T=0;T<L;T++) 25 www.cppforschool.com C[R][C]+=A[R][T]*B[T][C]; } }

Function to find & display sum of rows & sum of cols. of a 2 dim. array A void SumRowCol(int A[][20], int N, int M) { for(int R=0;R<N;R++) { int SumR=0; for(int C=0;C<M;C++) SumR+=A[R][C]; cout<<"Row("<<R<<")="<<SumR<<endl; } for(int R=0;R<N;R++) {

int SumR=0; for(int C=0;C<M;C++) SumR+=A[R][C]; cout<<"Row("<<R<<")="<<SumR<<endl; } }

Function to find sum of diagonal elements of a square matrix A void Diagonal(int A[][20], int N, int &Rdiag, int &LDiag) { for(int I=0,Rdiag=0;I<N;I++) Rdiag+=A[I][I]; for(int I=0,Ldiag=0;I<N;I++) Ldiag+=A[N-I-1][I]; } Function to find out transpose of a two dimensional array A void Transpose(int A[][20], int B[][20],int N, int M) { for(int R=0;R<N;R++) for(int C=0;C<M;C++) B[R][C]=A[C][R]; }