Vous êtes sur la page 1sur 16

Notes for Class XI

Q1a) 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 b) Explain different types of errors in C++. Ans An error or a bug, is anything in the code that prevent a program from compiling and running correctly. There are three types of errors:1. compile time errors 2. run time errors 3. logical errors Compile time Errors:- Errors that occurs during compile-time, are compile-time errors. When a program compiles its source code is checked for whether it follows the programming languages rules or not. Types of compile-time errors are:i. Syntax errors ii. Semantic error 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. Semantic Errors: Semantic refer to the set of rules which give menaing of a statement. Semantic errors occurs when statements are not meaningful. Eg : X+Y=Z; Will result in sematic eror as an expression cannot come on the left side of an assignment statement. 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. 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. c) 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 d) 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; Global variable void main() { Local float f; variable ---; ---; } 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. e) 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. 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: The #define preprocessor allows u s to define symbolic names and constants. Eg: #define PI 3.14159

The #define allows you to make text substitutions before compiling the program. 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. 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. 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. f) 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. g) 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. h) 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. i) 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. A virtual function is used to specify the interface in abstract class, but its implementation details are made available by the concrete class(es). 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 compiler.s job to select the specific action as it applies to each situation. j) 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( ); } Q2 a)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 b)Difference between if and switch.case. The 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 prespecified. 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

c)What is the difference between entry control or exit control loop? Give example Or difference between while and dowhile loop? AnsEntry 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 while loop : do { Statements; }while(condition); d) Define function and give example. 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // function example #include <iostream> using namespace std; int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; }

e) What if 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; } d) 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]; For example, int sqr (int x) { return (x*x); } void display() { cout<<hello; return; }
Expression or value is optional a void function will not have an expression or value

f) What is goto statement in c++. Give example Ans: 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(); }

Q3 a) What is nested if? It means one if statement inside another if statement. if( condition ) { if( some other condition) { } else { } } else { if( another condition) { } }

b) What 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 else where even if the condition is true. Eg for(int i=0;i<10;i++) { If (i==5) break; cout<<i; }
Loop will terminate when i=5, though loop condition is still true.

c) Define manipulator & give example 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 d) Differnetiate between get(), getchar(), getch(), getche(). 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 e) What is the purpose of header file? What will happen in absence of header file? Ans: A library is a collection of subprograms used to develop other programs and software. The c++ standard library contains file containing the standard functions that the program may use. These files are called heard files. Header files provide function prototypes, definition for library functions. In the absence of header file program would not compile. f) Define comment. Give brief description about types of comments.

Ans: A comment is a line or paragraph of text in a file such that that line or paragraph is not
considered when the compiler (or the parser) is decoding the code of the file. The C++ language accepts two types of comments: Single line comment entry- To write a comment on one line, type two forward slashes // and type the comment. Anything on the right side of both forward slashes would not be read by the compiler (actually the parser) Here are examples:
// This are various examples of a one-line comment

Multiple line comment entry- To write a comment, you can start it with a forward slash / followed by an asterisk *, write the comment. To end the comment, type an asterisk * followed by a forward slash /. This type of comment can be spread on various lines Here are examples:
/* This are various examples of a forward slash asterisk comment *///

g) What are reference variable? Where they are used? How they are declared Ans: C++ references allow you to create a second name for the a variable that you can use to read or
modify the original data stored in that variable. Declaring a variable as a reference rather than a normal variable simply entails appending an ampersand to the type name, such as this "reference to an int".

Eg. int x; int& foo = x; // foo is now a reference to x so this sets x to 56 foo = 56; std::cout << x <<std::endl;

They are used in function called using call by reference.


void swap (int first, int& second) { int temp = first; first = second; second = temp; } void main() { int a = 2; int b = 3; swap( a, b ); }

Changes will be reflected in b as second is a reference variable of b sharing memory with b.

h) What is type conversion? Give its type. Ans: Data needs to be converted from one type to another type. This is called type
conversion. Type conversion is the process of converting one predefined type into another. Implicit type conversion is done automatically by the compiler whenever data from different types is intermixed. When a value from one type is assigned to another type, the compiler implicitly converts the value into a value of the new type. For example: 1 double dValue = 3; // implicit conversion to double value 3.0 2int nValue = 3.14156; // implicit conversion to integer value 3 Most binary operators require their operands to be of the same type. If operands of mixed types are used, the compiler will convert one operand to agree with the other. To do this, it uses a hierarchy of data types: Long double (highest) Double Float Unsigned long int Long int Unsigned int Int (lowest) Char and short are always implicitly promoted to integers (or unsigned integers) before evaluation. This is called widening or type promotion.

Explicit type conversion or type Casting represents a request by the programmer to do an


explicit type conversion. In standard C programming, casts are done via the () operator, with the name of the type to cast to inside. For example: int nValue1 = 10; 1 int nValue2 = 4; 2 3float fValue = (float)nValue1 / nValue2;

Q4a) How many times will the following program will print examination? #include<iostream.h> void main( ) { while(1) { cout<<examination } } ANS 2>Unless ^C is pressed ,program will print examination infinitely. b) What is structure in c++?

Ans:- Structures form a very large building block with which to collect like data into one collective

unit. They are a versatile data structure in which to clump data together in convenient little packages. Arrays are one of the most widely used data structures in programming languages. One downfall of using such a data type is that one must use homogeneous data types, an array can only hold multiple items of the same type. Structures overcome this problem by allowing the programmer to have an unlimited number of items of different data types. struct name { type1 Member1; type2 Member2; typeXMemberx; } copyname,listname[x] ; Eg. struct Games { char Name[80]; char Rating; long NumberOfKills; };

c) what is the size of following structure struct Game { int game_code; char player_name[20]; float score; char result; } Ans: 2+20+4+1=27 bytes d) Define nested structure. Give suitable example. Ans: Structures can also be nested so that a valid element of a structure can also be in its turn another structure. Nesting of structures is placing structures within structure.
struct movies_t { string title; int year; };

struct friends_t { string name; string email; movies_t favorite_movie; } charlie, maria;

favorite_movie is a nested structure of movies_t

After the previous declaration we could use any of the following expressions:

1 charlie.name 2 maria.favorite_movie.title 3 charlie.favorite_movie.year 4 pfriends->favorite_movie.year

e) What is scope and life time of a variable?


Ans: The variables used in a program are always declared. The location you declare a variable controls its visibility and role in a program. The area where a variable is declared and can be accessed is referred to as its scope. This area usually has delimiters. The most used delimiter of scope is the curly bracket. If a variable is declared after an opening curly bracket }, that variable is available and accessible until the first and next closing bracket }. Such a variable is referred to as local. If a variable is declared outside of any function, such a variable is qualified as global. If a variable, mostly a constant is part of the operating system or the compiler, such a variable has the widest scope; it can be seen and accessible by any function and any program, provided the right header file is included. Type of scope: 1 Local or block scope - A scope starts with an opening curly bracket and ends with a closing curly bracket. This scope is called a block. The following program will produce an error because the side of the shape is confined to one scope and being accessed from outside. { int x=2 }

x is accessible here only

2. Function scope - If a variable is declared inside of a function or a method but outside of any block, such a variable has a function or a method scope because it is accessible by any other variable that is inside of the same function or method. void abc() { x is accessible inside int x=2; } 3. Global variable Variable which is accessible throughout the program, by all the functions is called global variable. Eg x is accessible to both abc() & int x=2; main() void abc() { } void main() { }

The Lifetime of a particular variable is the range within an executing program in which that variable is instantiated and retains its' value. When lifetime rules are violated, no compiler errors result, rather the program will demonstrate logic errors. Logic errors are typically much more difficult to isolate than compiler errors.

f) What is the significance of exit()?

Ans: The exit function, declared in the standard include file STDLIB.H, terminates a C++ program. The value supplied as an argument to exit is returned to the operating system as the program's return code or exit code. By convention, a return code of zero means that the program completed successfully.
g) In the following program, if the value of N given by the user is 20, what maximum and

minimum value the program could possibly display ()? #include<iostream.h> #include<stdlib.h> void main() { int N, Guessme; randomize(); cin>>N; Guessme = random(N-10) + 10 ; cout<<Guessme<<endl; } Ans: random() will generate value between 0 to 9 (20-10) Minimum value of Guessme: 0+10=10 Maximum value of Guessme :9+10=19 Therefore, output is a value between 10 to 19

storage class specifiers in C++.


The storage class specifiers are used to change the way of creating the memory storage for the variables.

auto:
This auto specifier tells the compiler that the variable declared will go out of scope once the program exits from the current block. The program block can be a function, a class or a structure.

This is the most widely used and non-used storage class specifier in C++. Because, all the variables declared in C++ are of the type auto by default. So no one need to worry about specifying this one. The declarations, auto int var1; // declared with auto specifier for the c++ tutorial int var1; //declared without the storage class specifier Both the above declarations will produce the same result.

static:
This static specifier when used will preserve the value for a particular variable upon reentry into the same function. For example //C++ Tutorial - Example code for demonstrating static variable void static_function_example() { static int x = 0; //variable for C++ tutorial example x++; cout << x <<endl; } If this function is called 10 times, the output will be 1,2,3,4..etc., The value of the variable x is preserved through function calls. If this static variable is declared as a member of a class, then it will preserve the value for all the objects of the class.i.e, one copy of this data variable will be shared by all objects of the class.

extern:
This extern keyword is used to specify that the variable is declared in a different file. This is mostly used to declare variables of global scope in C++ projects. When the keyword extern is used, the compiler will not allocate memory for the variable. Programmers in C++ would have very frequently faced linker errors because of wrong external linking.

register storage specifier:


This register keyword tells the C++ compiler to allocate some storage in the registers. Any operations using the register is bound to be the fastest. But a mere specification of register keyword won't get the variable a place in the register. If the compiler finds no space in the register, it'll use the cache memory also.

Vous aimerez peut-être aussi