Vous êtes sur la page 1sur 27

C++ Notes What is C++? C++ is an object-oriented programming language.

It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980s. Conversion of source program to executable file The conversion of a source file into an executable file is a two step process: 1. First you compile your source file into an object file. 2. Link it with necessary library routines. Source Code/File: The program written in a programming language like C++ is called a source file, or source code. It is not an executable file. In C++ it has .CPP extension. Object Code/File: Object code/file is the representation of codes that compiler or assembler generates by processing a source code/file. Object files contain compact code, often called binaries. Its extension in DOS is .OBJ. Executable Code/File: Executable code/file, in computer science, is as file whose contents are meant to be interpreted by operating system. Its extension in DOS is .EXE. Prog1.CPP SOURCE FILE

COMPILER

Prog1.OBJ

OBJECT FILE

LINKER

Prog1.EXE

EXECUTABLE FILE

Compiler: It is a program which converts the program written in a programming language to a program in machine language. Every programming language has its own compiler. Linker: It is a program which takes a compiled program to the necessary library routines, to make it an executable program. Compiling: The process of converting the source program into an object program is called compiling. In this, program written in any programming language is converted into the machine language with the help of compiler. Linking: The process of converting the object program into an executable program is called linking. In this the program in machine language instruction is linked with necessary library routines, with the help of linker.

Vibhor Kaushik || vibhor_kaushik@india.com

Page 1 of 6

C++ Notes C++ Character set: It is a set of characters that can be used in C++ program. It consists of alphabets (A..Z, a..z), digits (0 ...9), and special characters (&, :, ;, *, space etc). C++ Tokens: A Token is a group of characters that logically belong together. It is the smallest individual unit in a program. C++ supports the following types of tokens: a) Identifier: It is a symbolic name given by a programmer for any data item or function. The identifier is a sequence of characters takes from C++ character set. The rules for formation of identifier are: Can consist of alphabets, digits and special character underscore ( _ ). Can start with an alphabet or underscore, but not with digit. C++ is case sensitive. Blank space not allowed b) Variable: It is a location in the computer memory which can store data and is given a symbolic name for easy reference. Its value can change during program execution. The syntax for declaring a variable: <data type> <variable name> [ = <initial value>],. ; Example : char grade; int a, b=10, c; Data type has to be any one of the data types present in C++. The basic data types available in C++ are: Data Types char int long float double long double Range 0 to 255 -32768 to 32767
-2,147,483,648 to 2,147,483,647

Size (Bytes) 1 2 4 4 8 10

Usages For storing Characters For storing numbers without decimal For storing numbers without decimal For storing floating point numbers. It has seven digits of precision. For storing floating point numbers. It has fifteen digits of precision. For storing floating point numbers. It has nineteen digits of precision.

- 3.4 x 10 to 3.4 x 10 - 1
308 308

38

38

- 1.7 x 10

to 1.7 x 10

-1

- 3.4 x 10

4932

to 3.4 x 10

4932

-1

c) Keywords: A keyword is a reserved word that has a predefined meaning and purpose in the language. It cannot be used as an identifier by the user in this program. e.g. float d) Constant: It is an identifier whose value does not change during program execution. The syntax for declaring a constant is const <data type of constant> <name of constant> = <constant value> ; For e.g. const float pi = 3.14;

Vibhor Kaushik || vibhor_kaushik@india.com

Page 2 of 6

C++ Notes e) Operators: An operator is a symbol or letter used to indicate a specific operation on variable or value in a program. There are three types of operators in C++: Unary operators: Operators which operate on one operand. For e.g. The increment (++), the decrement (--), and logical NOT (!) are the unary operator. Binary operators: Operators which operate on two operands are called binary operators. For example, all arithmetic operators, all relational operators and logical AND (&&), and OR (||) are the binary operators. Ternary Operators: Operators which operate on three operands are called ternary operators. For example, the conditional (? : ) operator is a ternary operator. f) Punctuators/Separators: The following characters are used as punctuators/separators in C++: ( ) { } , ; : * # [ ] # : It is called the preprocess directive in C++. A preprocessor directive is an instruction to the compiler itself. A part of the compiler called preprocessor, deals with these directives, before real compilation process. The #include directive: The preprocessor directive #include tells the compiler to insert another file into your source file. In effect, the #include directive is replace by the contents of the file indicated. Output using cout: cout statement is used to display a value on screen. The cout is always used with the insertion operator ( << ). The insertion operator displays the constant value/variables value/result of expression following it on the screen. Syntax: cout<<value/variable/expression; Example: cout<<Hello; int c = 10; cout<<c; cout<<(c+10); Input using cin: cin statement is used to take input for a variable. The cin is always used with the extraction operator ( >> ). The extraction operator extracts the value entered by the user and assigns it to the variable on it right hand side. Syntax: cin>>variable; Example: int num; cout<<Enter a number : ; cin>>num; Cascading of insertion ( << ) and extraction ( >> ) operators: When more than one insertion operator is used in a single cout statement, or more than one extraction operator is used in a single cin statement, then it said insertion operator(<<) is cascaded with cout, and extraction operator ( >> ) can cascaded with cin.

Vibhor Kaushik || vibhor_kaushik@india.com

Page 3 of 6

C++ Notes For example: cout<<Enter value of a, b, and c <<endl; cin>>a>>b>>c;

Assignment Operator ( = ): The equal sign, causes the value on right to be assigned to be assigned to variable on the left. The statements which assign values to variables are called assignment statements. Syntax: Variable = value/variable/expression Example: a = 10; Arithmetic Operator: The arithmetic operators available in C++ are: Operator Usage + * / % For e.g. int a=10, b=3; cout<<Sum=<<a+b<<endl; cout<<Difference=<<a-b<<endl; cout<<Product=<<a*b<<endl; cout<<Quotient=<<a/b<<endl; cout<<Remainder=<<a%b<<endl; Used for Addition Used for Subtraction Used for multiplication Used for division This operator is called the remainder or the modulus operator. It is used to find the remainder when one integer value/variable is divided by another value/variable. This operator cannot be used with floating type variables/values. Output Sum=13 Difference=7 Product=30 Quotient=3 Remainder=1

Relational Operators: Relational operators are used to relate two values/variables and result either true or false. The relational operators present in c++ are: Operator < > <= >= == != Usage Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to Example A<B A>B A<=B A>=B A==B A!=B Explanation A is less than B A is greater than B A is less than or equal to B A is greater than or equal to B A is equal to B A is not equal to B

Vibhor Kaushik || vibhor_kaushik@india.com

Page 4 of 6

C++ Notes Logical Operators: Two conditions can be logically combined with the help of logical operators. The logical operators present in C++ are: Operator && AND Usage The compound condition evaluates to true, if both the conditions in the compound condition evaluate to true. The compound condition evaluates to true, if any or both the conditions in the compound condition evaluate to true. It negates the condition. That is: If the condition evaluates to true, it makes it false. If the condition evaluates to false, it makes it true. Example ((a>b) && (a>c))

||

OR

((a>b) || (a>c))

NOT

!(a>b)

Arithmetic Assignment Operators (Shorthand Operators): Arithmetic assignment operator, is one,, which combines arithmetic operator and an assignment operator. The arithmetic assignment operators present in C++ are: Operator += -= *= /= %= Example A += B; A -= B; A *= B; A /= B; A %= B; Meaning A = A + B; A = A - B; A = A * B; A = A / B; A = A % B;

Increment/Decrement Operators (Unary Operator): Increment ( ++ ) Operator: It is used to increment the value of variable by 1. It can be used in the following two ways: Pre Increment In this, the operator precedes the variable. Example: ++a b = ++a; Example: a++ b = a++; Post Increment In this, then operator follows the variable.

This statement is equivalent to the following This statement is equivalent to the following two statements: two statements: a = a + 1; b = a; b = a; a = a + 1;

So, in pre increment the value of the variable So, in post increment the value of the is incremented, before it is used in any other variable is incremented, after it is used in operation (Assignment in this case) any other operation (Assignment in this case)

Vibhor Kaushik || vibhor_kaushik@india.com

Page 5 of 6

C++ Notes Decrement (--) Operator: It is used to decrement the values of variable by 1. It can be used in the following two ways: Pre Decrement In this, the operator precedes the variable. Example: --a b = --a; Post Decrement In this, then operator follows the variable. Example: a-b = a--;

This statement is equivalent to the following This statement is equivalent to the following two statements: two statements: a = a - 1; b = a; b = a; a = a - 1;

So, in pre decrement the value of the So, in post decrement the value of the variable is decremented, before it is used in variable is decremented, after it is used in any other operation (Assignment in this any other operation (Assignment in this case) case) Conditional Operator (? : ): The question marks (?) and the colon (: ) make up the conditional operator. The operator operates on three operands that are why it is called the ternary operator. The whole expression is called the conditional expression. The expression before the question mark is called the test expression. If the test expression is true, then the entire conditional takes on the value of the operands after the question mark. If the test expression evaluates to false, then the conditional expression takes on the value of the operand following the colon. Syntax: <test expression> ? <true expression> : <false expression> Example: res = ( x < y ) ? x : y; (Test Expression) (Operands)

In the above example, if the test expression evaluate to true the variable res will be assigned the value of the variable after the question mark, i.e. x else it will be assigned the value of the variable after the colon i.e. y. Example: cout<<( (a>b) ? (a-b) : (b-a) ); // displays a-b if the condition is true, else displays b-a Comments: Comments can start at the beginning of a line or on the same line following a program statement. In C++ comments can be given in two ways: a) Single line comments start with // (double slash) symbol and terminate at the end of the line. b) Muliline comments start with /* symbol and terminate with */ symbol. For example: /* Program to find the sum of two Numbers */ int a; //declares a variable of integer type

Vibhor Kaushik || vibhor_kaushik@india.com

Page 6 of 6

C++ Notes Conversion: Automatic Type conversion: When two operands of different data types are encountered in the same expression, the variable of lower data type is automatically converted to the data type of variable with higher data type, and then the expression is calculated. For Example: int a=98; float b=5; cout<<a/3.0; // Converts a temporarily to float type, since 3.0 is of float type cout<<a/b; // Converts a temporarily to float type, since b is of float type, // and gives the result 19.6 Explicit Type Conversion (Type Casting): Type casting refers to the data type conversions specified by the programmer, as opposed to automatic type conversions. This can be done when the compiler does not do the conversions automatically. Type casting can be done to higher or lower data type. For Example: cout<<(float)12/5; // Display 2.4, since 12 is converted to float type. Conditional Constructs: They help us to execute a set of statements based on a condition. There are two conditional construct present in C++. if .. else construct switch case construct if .. else construct: If there is only one statement associated with case the curly braces are optional. else is always optional with a particular is. Syntax if (<condition>) statement ; if (<condition>) { Statement 1; Statement 2; : Statement N; } if (<condition>) Statement ; else Statement ; if (<condition>) { Statement 1; : Statement N; } Example if (a>b) cout<<a; if (a>b) { cout<<Diff=<<a-b<<endl; cout<<Quotient=<<a/b<<endl; cout<<Product=<<a*b<<endl; cout<<Sum=<<a+b<<endl; } if (a>b) cout<<a<<endl; else cout<<b<<endl; if (a>b) { cout<<Diff=<<a-b<<endl; cout<<Quotient=<<a/b<<endl; } else

Vibhor Kaushik || vibhor_kaushik@india.com

Page 1 of 8

C++ Notes else { Statement 1; : Statement N; } Nested if .. else a) ifelse Ladder ( The last else if optional) if(<condition 1>) Statement 1; else if (<condition 2>) Statement 2; else Statement 3; b) if (<condition1>) if(<condition 2>) if(<condition 3>) : If(<condition n>) Statement 1; else Statement 2; : else Statement 3; else Statement 4; else Statement 5; { cout<<Diff=<<b-a<<endl; cout<<Quotient=<<b/a<<endl; }

if((a>=b) && (a>=c)) cout<<Largest = <<a; else if((b>=a) && (b>=c)) cout<<Largest=<<b; else cout<<Largest=<<c; if( per >= 50 ) if( per >= 60 ) if( per >= 70 ) if( per >= 80 ) if( per >= 90 ) grade = A; else grade = B; else grade = C; else grade = D; else grade = E; else grade = F; // One // Two // Three // Four // Five // Five // Four // Three // Two // One

Backslash character constants: C++ allows certain non-graphic characters i.e. characters that cannot be typed directly from the keyboard. The following are some backslash character and string constants. Backslash character constant Usage \n Escape sequence for new line character \t Escape sequence for tab (eight spaces) These are called escape sequence, since the backslash causes an escape from the normal way characters are interpreted. They can be used in both character and string constants. For e.g. cout<<Run\nspot<<\n<<run<<\n; Syntax for switch case construct: In a switch case construct the value of the switch variable is compared against a set of constant values. Wherever, a match is found, the statements associated with that particular case are executed. If the value of the switch variable does not match any of the case constants, then the default case is executed.

Vibhor Kaushik || vibhor_kaushik@india.com

Page 2 of 8

C++ Notes

Syntax switch ( <switch variable> ) { case <constant 1> : Statement 1; : Statement n; case <constant 2> : Statement 1; : Statement n; case <constant 3> : Statement 1; : Statement n; case <constant 4> : Statement 1; : Statement n; : : default : Statement 1; : Statement n; } Note: default case is optional.

Example switch(color) { case 3: cout<<Red; case 2: cout<<Orange; case 7: cout<<Black; } switch (choice) { case 1: cout<<Sum=<<a+b<<endl; break; case 2: cout<<Difference=<<a-b<<endl; break; case 3: cout<<Product=<<a*b<<endl; break; case 4: cout<<Quotient=<<a/b<<endl; break; case 5: cout<<Remainder=<<a%b<<endl; break; default: cout<<Invalid choice; }

Break statement in switch case construct: The break keyword causes the entire switch statement to exit, and the control is passed to statement following the switch.. case constructs. Without break, the control passes to the statements for the next case. The break statement is optional in the switch case construct. Use of default case in switch case construct: This keyword gives the switch case construct a way to take an action if the value of the witch variable does not match with any of the case constants. No break statement is necessary after default case, since the control is already at the end of switch.. case constructs. The default case is optional in the switch case construct. Difference between ifelse construct and switchcase construct Ifelse construct Switchcase construct 1. Any kind of relation can be checked in any This construct checks only for equality. condition of this construct. The condition can be include any relational operator (<, >, <=, >=, ==, !=). 2. Float values/variables can be used in the Float variable cannot be used as switch condition. variable. 3. Example: Example: if(a>=b) switch(a) cout<<a; { case 1: cout<<red; break; else default: cout<<Orange; cout<<b; }

Vibhor Kaushik || vibhor_kaushik@india.com

Page 3 of 8

C++ Notes Manipulators: Manipulators are operators used with the insertion operator (<<) to modify or manipulate the way data is displayed. The header file iomanip.h is required for the manipulator setw ( ): setw (n): The setw manipulator causes the variable or consonant that follows it in the stream to be printed within field n characters wide, where n is the argument to setw (n). The value is right justified within the field. Note: The setw () manipulator has no effect if the value of n is less than the number of characters in the value to be printed. Also, it has no effect on character data type. Type modifiers: Type modifiers are used to modify the type and range of data that can be stored in a variable. The type modifiers present in c++ are: Type Modifier long unsigned int unsigned long Number of bytes required 4 2 4 Range Usage

Low High -2,147,483,648 2,147,483,647 For storing integer data 0 65,535 For Storing positive integer 0 4,294,967,295 For Storing positive integer

Control Structures Loops A loop causes a program section to be executed a number of times depending on a specified condition. The repetition continues till a specified condition is true and terminates as soon as the specified condition turns false. At the termination pf the loop, the control of the execution is passed on to the statement following the loop. There are three types of loops in C++ for while do while for loop The for loop is used to execute a program section a fixed number of times. The condition is always checked first before the loop is executed. Syntax: for ( <initialization>; <condition>; <increment/decrement expression> ) { statement 1; statement 2; Loop Body statement 3; : } Initialization: It is used to initialize the loop variable and is executed only once at the start of the loop. As shown in the example 1 (a) loop variable a is initialize to 1. Condition: It is evaluated every time before the execution of the statements in the loop body. The loop is executed if the condition evaluates to true, if evaluated to false the control of execution is passed to the statement immediately after the loop. As shown in the Vibhor Kaushik || vibhor_kaushik@india.com

Page 4 of 8

C++ Notes example 1(a) the loop continues if the value of a <= 10 and stops the moment the value becomes 11. Increment/decrement expression: This statement is executed after each execution of the statements in the loop body and therefore makes the loop variable attain the final value, after which the condition turns false and the loop execution stops. In the following example 1(a) the value of a is incremented after each execution of the loop body and keeps on getting incremented by one till it attains the value 11, at which the condition turns false and the loop stops. Similarly, in the example in 1(b) the value of a is decremented by 1 each time and loop stops when the value of a becomes 0, at which the condition turns false. Examples: 1 (a) 1 (b) for (int a=1; a<=10; a++) for (int a=10; a>=1; a--) cout<<a<< ; cout<<a<< ; Output 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1 A for loop can have initialization and increment/decrement of more than one variable but there can only be one test expression. Multiple statements in a loop needs to be enclosed in a pair of curly braces, on the other hand a single statement belonging to a loop does not require a pair of curly braces ( As shown in examples 2 (a) and 2 (b)). 2 (a) 2 (b) for (int i=1, j=8,sum=0; i<=4; i++, j-=2) for (int i=1, j=2, k=5; i<=5; i++, j+=2, k+=5) { cout<<i<< : <<j<< : <<k<<endl; cout<<i<< <<endl; sum+=j; } cout<<sum is: <<sum; Output 1 8 1: 2:5 2 6 2 : 4 : 10 3 4 3 : 6 : 15 4 2 4 : 8 : 20 sum is: 20 5 : 10 : 25 Some more examples of for loop are as follows, which are not considered as good programming practices to be followed: 3 (a) 3 (b) for (int a=1; a<=10; a++); int i=1, sum=0; for ( ; i<=5; ) cout<<a<<endl; // Outside the loop { /* The value of a is incremented from 1 to sum+= i; 11 and loop is terminated as the condition i++; turns false */ } cout<<i<<\t<<sum<<endl; Output 11 6 15

Vibhor Kaushik || vibhor_kaushik@india.com

Page 5 of 8

C++ Notes While Loop: The while loop executes a section of the program till a specified condition is true. While loop is used when the number of times the loop is to be executed is not known. The condition is always checked first before the loop is executed. Syntax: while(<condition>) { statement 1; statement 2; Loop Body : statement n; } Examples: 1. while-loop with a single statement 2. The execution of the following loop depends on the value of Ans, therefore the number of times the loop is executed is not known. int a=1; char Ans; while (a<=4) cout<<Want to find the square of a number cout<<a++<<endl; (Y/N) ?; cout<<The final value of a: <<a<<endl; cin>>Ans; int N; Output while(Ans == Y) 1 { 2 cout<<Enter a no: ; cin>>N; 3 cout<<Square=<<N*N<<endl; 4 cout<<Repeat (Y/N): ; cin>>Ans; The final value of a: 5 } dowhile Loop: The do..while loop executes a section of the program till the specified condition is true. The do..while loop is used when number of times the loop is to be executed is not known. The body of the do while loop is executed at least once, since the condition is placed at the end of the loop. Moreover, the statements written in this loop have to be always enclosed in a pair of curly braces, even if there is only a single statement in the loop. Syntax: do { statement 1; statement 2; : statement n; }while (<condition>);

Loop Body

Vibhor Kaushik || vibhor_kaushik@india.com

Page 6 of 8

C++ Notes 1. int a=1; do { cout<<a++<<endl; } while (a<=4); Output 1 2 3 4 2. char Ans; int N; do { cout<<Enter a no: ; cin>>N; cout<<Square=<<N*N<<endl; cout<<Repeat (Y/N): ; cin>>Ans; } while(Ans == Y); Entry and Exit controlled loops Entry Controlled Loops: These loops have a test expression/condition in the beginning of the loop, the test expression (condition) is therefore evaluated first, the loop is executed if the condition holds true. The control then moves back to test the condition for the next time and the process continues as long as the test expression evaluates to be true. If the condition is false right in the beginning the loop will not be executed even once. Examples: for and while loops. Exit Controlled Loops: These loops have a test expression/ condition at the end of the loop, thus having a control for exiting from the loop. The loop is executed at lease once before the test expression is evaluated. If condition holds true, the loop is executed again, otherwise, it exits the loop. Example: do .. while loop In Entry controlled loops for and while, the body of the loop may not execute even once if the test expression evaluates to be false the first time, whereas in do .. while, the loop is executed at least once whether the condition holds true the first time or not. Example: 1. In the following example after the initialization of x with value 1, the control moves to test expression (x>=10), the result evaluates to be false, and hence the body of the loop will not execute even for once. for(int x = 1; x >= 10; x++) cout<<x<<endl; 1. In the following example, first the body of the loop will execute with the value of x taken as 1, and then only the test expression (x>=10) shall be evaluated to be false, so that the control does not go back for the second iteration. int x = 1; do { cout<<x++<<endl; } while (x >= 10);

Vibhor Kaushik || vibhor_kaushik@india.com

Page 7 of 8

C++ Notes Nested Loops: When a for, while or do..while loop is used inside another looping construct, the concept is called a nested loop. This concept is used whenever for each repetition of a process many repetitions of another process are required. Some sample skeletal structures of Nested Loops for( .. ) while( .. ) Do do { { { { for( .. ) while( .. ) while( .. ) for( .. ) <statement> <statement> <statement> <statement> } } } } while( .. ); while( .. ); Example: for( int p = 1; p<=3; p++) // Outer Loop Output: { for(int q = 10; q<=20; q+=10) // Inner Loop 10 20 cout<<q<< ; 10 20 cout<<endl; // Statement belong to outer loop 10 20 }

Vibhor Kaushik || vibhor_kaushik@india.com

Page 8 of 8

C++ Notes [Function] Function: A function is a named unit of a group of statements that can be invoked from other parts of the program. The advantages of using functions are: Functions enable us to break a program down into a number of smaller and smaller and simpler units. This makes the program more organized and structured and easier to debug. It helps in reusability of code and thus reduces program size. If similar code is required at several places in the program, the use of a function allows this code to be written just once, and to be called wherever it is required. It helps to execute the same set of statements with different set of values.

Function Declaration/Prototype: Just as any variable is declare before it is used in a program, it is necessary to declare a function to inform the compiler that the function would be referenced at a later point in the program. Function declaration is also called function prototype. Syntax for function declaration: <return type> <function name> ( <data type of parameter> [<parameter name>], . ); Example: int sum ( int, int); A declaration (prototype) tells the compiler that later on in our program we are going to write a particular function. It also informs the compiler about: 1. the type of result to be returned; 2. the identifier of the function; 3. the number and types of parameters; It is terminated by a semicolon. <return type>: It is the data type of the value that is returned to the calling function after the function is executed. It can be any of the data types, available in C++. <function name>: It is the name of the function, which is given with accordance to the naming conventions used for naming an identifier. A function is called with the help of its name. <data type of parameter>: These are the data types of the parameters/inputs that the function receives when it is called. In function declaration it is optional to give the name of the parameters. The different data types specify to the compiler, the total number of parameters, and the data type of these parameters that the function will receive, when it is called (invoked). Function definition: The function definition contains the function header and the function body i.e. the set of statements which are executed when the function is called. Syntax for function definition: <return type> <function name> (<data type of parameter> <name of <parameter>, . ) { Statement 1; Statement 2; : Vibhor Kaushik || vibhor_kaushik@india.com Page 1 of 8

C++ Notes [Function] return ( value / variable / expression ); } Example: int sum ( int a, int b) { int s = a + b; return s; } Note: The return statement is used to return a value to the calling function. It is always the last statement in the function definition (if the function has return type). The data type of the value returned should match with the return type of the function. // Example 1 // Program to find the factorial of a number using a function Fact () #include<iostream.h> #include<conio.h> long Fact( long); // Function Prototype

void main() { long num; clrscr(); cout<<\n\tEnter a No. : ; cin>>num; cout<<num<<! = <<Fact(num); // Function call with num as an actual parameter getch(); } // Definition of function long Fact (long N) // Function header with N as a Formal parameter { long I, f=1; for( i=1; i<=N; i++) Function Body f = f * i; return f; } Order of Execution in the above program main() // Execution starts from the main() Function call to Fact() // Control is passed to the function definition of Fact() Execution of the Fact() // All the statements in the function Definition of Fact() are executed Execution of statement getch() // Control returns to the main(), to the statement which follows the function call statement of Fact()

Vibhor Kaushik || vibhor_kaushik@india.com

Page 2 of 8

C++ Notes [Function] Function Header: It is the first line of the function definition, which specifies the following: Return type of the function Name of the function Name of the parameters, along with their data types Note: It is not terminated with semicolon. Function Body: It is the set of statements, which are executed when the function is called. Function Call: It is the statement in the calling function, through which the control is passed to the function definition of another function. This will execute the statements is the called function and then the control is returned back to the statement in the calling function, which follows the function call statement. The function call consists of the function name, followed by actual parameters, if any, enclosed in parentheses. Calling Function: The function, which calls a function is called the calling function. In the above example main() is the calling function. Called Function: The function which is called by anther function is known as the called function. Formal Parameter: The parameters mentioned in the function header are called formal parameter. Actual Parameter: Values/Variables which are used while making a call to the function are called actual parameter. Difference between call by value and call by reference Call by Reference Call by Value 1) The changes made to the formal 1) The changes made to the formal parameters are reflected back to the actual parameters are not reflected back to the parameters. actual parameters. 2) It provides a mechanism of returning 2) Not Available more than one value. 3) The reference parameters require an 3) Not Available ampersand (&) sign before their name. 4) The Formal and Actual parameters share 4) The formal and actual parameters have the same memory location. different memory location. 5) void Swap(int & a, int & b) 5) void Swap(int a, int b) { { int temp = a; int temp = a; a = b; a = b; b = temp; b = temp; } } // Program to illustrate the invoking of a function using call by value // and call by reference methods #include<iostream.h> #include<conio.h> // Function to swap the values of two variables, // where both the parameters are value parameters void swapv ( int a, int b) { int temp = a; a = b;

Vibhor Kaushik || vibhor_kaushik@india.com

Page 3 of 8

C++ Notes [Function] b = temp; cout<< Displaying the formal parameters of swapv () function <<endl; cout<<a<<\t<<b<<endl; } // Function to swap the values of two variables, // where both the parameters are variable parameters void swapr( int&b, int&b) { int temp = a; a = b; b = temp; cout<< Displaying the formal parameters of swapr () function <<endl; cout<<a<<\t<<b<<endl; } void main() { clrscr(); int x=5, y=7; swapv(x,y); cout<<The values of actual parameters after calling the swapv() function<<endl; cout<<x<<\t<<y<<endl; swapr(x,y); cout<<The values of actual parameters after calling the swapr() function<<endl; cout<<x<<\t<<y<<endl; getch(); } OUTPUT Displaying the formal parameters of swapv() function 7 5 The values of actual parameters after calling the swapv() function 5 7 Displaying the formal parameters of swapr() function 7 5 The values of actual parameters after calling the swapr() function 7 5 Returning values from Functions: When a function completes its execution it can return a single value to the calling function. // Program to explain return statement #include<iostream.h> int Sum(int x, int y) int Sum(int x, int y) { { int z; OR return(x+y); z = x+y; } return z; } Vibhor Kaushik || vibhor_kaushik@india.com

Page 4 of 8

C++ Notes [Function] void main() { clrscr(); int a,b,c; cout<<\n Enter 2 numbers : ; cin>>a>>b; c = Sum(a,b); // Function call statement, the returned value is stored in the variable c cout<<\n Sum = <<c; } Default Parameters: A function can assign a parameter a default value. So, a function can be called with less number of parameters than that defined if values have been set. These default values are used when no value corresponding to these parameters are specified in the call to that function. The default values have to be specified in the function prototype, and not in the function definition. For example: int Change(int, int &, int c=9); The following points should be considered while using the default parameters: If a function consists of value, reference and default parameters, then the default parameters are specified in the end of the parameter list, i.e. If a parameter has a default value, then all the parameters appearing to its right must have a default value. Reference parameter cannot have a default value. // Program to show the usage of default parameters #include<iostream.h> int Calculate(int, int b=20); void main() { int x=5, y=15; cout<<Calculate(x); Output cout<<endl; 4 cout<<Calculate(x,y); 3 } int Calculate(int a, int b) { return(b/a); } Difference between Local and Global Variables Local Variables Global Variables 1) They are declared in a function, and can 1) They are declared outside all the be used only in the function in which they functions, and can be used in all the are declared. functions after its declaration. 2) If a local variable has the same name as 2) To access the global variable explicitly, that of a global variable, then the local scope resolution operator(::), is used. variable is given preference. 3) For example 3) For example void Show () int m = 50; // Global Variable { int m =5; // Local Variable void Show () cout<<m<<endl; { int m =5; // Local Variable } cout<<m<<::m<<endl; } Vibhor Kaushik || vibhor_kaushik@india.com

Page 5 of 8

C++ Notes [Function] In-Built functions in Header File <math.h> Usage Example Calculates the absolute value cout<<fabs(-7.5); of the floating point number x. cout<<fabs(8.25); Calculates the absolute value of cout<<abs(-12); the integer x. cout<<abs(25); cout<<abs(-17.25); cout<<abs(25.77); Calculates natural logarithm of cout<<log(100); y. cout<<log(2); Calculates the base 10 cout<<log10(100); logarithm of y cout<<log10(2); Calculates the power x to y. cout<<pow(10,2); cout<<pow(125,1/3.0); Calculates the square root of x cout<<sqrt(25); cout<<sqrt(144); Computes the sine of x. The cout<<sin(90); angle is specified in radians. cout<<sin(90/(22/7.0)); Computes the cosine of x. The cout<<cos(270); angle is specified in radians. cout<<sin(90/(22/7.0));

1. 2.

Function fabs(x) abs(x)

3. 4. 5. 6. 7. 8.

log(y) log10(y) pow(x, y) sqrt(x) sin(x) cos(x)

Result 7.5 8.25 12 25 17 25 4.60517 0.693147 2 0.30103 100 5 5 12 0.893997 0.540834 0.984382 0.841129

1.

2.

3.

4.

5.

In-Built functions in Header File <ctype.h> Usage Example Result Check if character x is A-Z or a-z char x=B; if(isalpha(x)) Albhabet cout<<Alphabet; else cout<<Not alphabet; isdigit( x) Check if character x is 0-9 char x=9; if(isdigit(x)) Digit cout<<Digit; else cout<<Not digit; islower( x) Check if character x is lower char x=b; case alphabet a-z if(islower(x)) Lowercase cout<<Lowercase; else cout<<Not lowercase; isupper( x) Check if character x is Upper char x=B; case alphabet A-Z if(isupper(x)) Uppercase cout<<Uppercase; else cout<<Not uppercase; Isalnum( x) Check if character x is an alpha- char x=b; numeric i.e. A-Z, a-z, 0-9 if(isalnum(x)) alphabet/ cout<<alphabet/digit; digit else Function isalpha( x) Page 6 of 8

Vibhor Kaushik || vibhor_kaushik@india.com

C++ Notes [Function] cout<<other; Converts the character x to its char x=H; lower case value i.e. if character if(isupper(x)) is A-Z then it convert it to a-z. cout<<(char)tolower(x); All other characters are left unchanged. It return ASCII of the lower case equivalent. Converts the character x to its char x=h; upper case value i.e. if if(islower(x)) character is a-z then it convert cout<<(char)toupper(x); it to A-Z. All other characters are left unchanged. It return ASCII of the upper case equivalent. In-Built functions in Header File <conio.h> Usage Example To clear the screen clrscr();

6.

tolower(x)

7.

toupper(x)

1.

Function clrscr()

Result Places the text cursor at first row, and first column on the screen Places the text cursor at third column and sixth row on the screen

2. 3.

getch() gotoxy(c,r)

Wait for a character input getch(); To place the text cursor at gotoxy(3,6); column c and row r on the screen.

1.

2.

In-Built functions in Header File <stdlib.h> Function Usage Example Result randomize() It is used to initialize the randomize(); random number generator, so that each time a new random number is generated. random(n) It returns a random integer cout<<random(7); Will display any between 0 to n-1, both integer number inclusive. between 0-6.

// Program find LCM of two number using function. #include<iostream.h> int LCM( int a, int b) { int i, lcm; for(i=a*b; i>=a; i--) { if(i%a==0 && i%b==0) { lcm=i; Vibhor Kaushik || vibhor_kaushik@india.com Page 7 of 8

C++ Notes [Function] } } return lcm; } int GCD(int a, int b) { int i, gcd; for(i=1; i<=a; i++) { if(a%i ==0 && b%i==0) { gcd=i; } } return gcd; } void main() { int a, b, l,g; cout<<\n Enter 2 number : ; cin>>a>>b; l = LCM(a,b); cout<<\n LCM = <<l; g = GCD(a,b); cout<<\n GCD = <<g; }

Vibhor Kaushik || vibhor_kaushik@india.com

Page 8 of 8

What is difference between Actual Parameters and Formal Parameters? Give an example in C++ to illustrate both types of parameters. Actual Parameter A parameter used in a function call is known as actual parameter. It is used to send data to function. Void abc(int a) // a is formal parameter { Int x=9; x=x+a; } Void main() { Int p=6; abc(p); } // p is actual parameter What do you mean by function prototyping? Write down the advantages of function prototypes in C++? Ans. Function prototyping means writing the function prototypes before their function call occurs. A function prototype is a declaration of the function tells the program about the type of the value r et ur ned by the function and the number and type of arguments. The advantage of function prototyping is that it enables a compiler to compare each use of function with the prototype to determine whether the function is invoked properly or not. The number and types of arguments can be easily com pared and any wrong number of types of the argument is reported. Therefore, function prototyping makes C++ straightaway point to the error. How is global prototype different from a local prototype? Ans. If a function prototype is placed in the body of another function, it is local prototype and the function is locally available to the function that declares it. If a function prototype is placed outside all the functions, it is global prototype and the function is globally available to all the functions. Formal Parameter A parameter used in a function definition is known as formal parameter. It is used to accept data from actual parameters.

Sample Paper Computer science Class: XI


-----------------------------------------------------------------------------------------------------------Time Duration: 3 Hours Maximum Marks: 70 -----------------------------------------------------------------------------------------------------------Instructions: All Questions are Compulsory. I. 1. Name different types of digital computers based on their size and performance. 2. What is system software? 3. Explain first come first served (FCFS) scheduling. 4. Explain multiprocessing operating system. [1] [1] [2] [2]

II.

III.

(Total: 6M) 1. Differentiate between syntax error and semantics error. Give example for each. [2] 2. What do you mean by robustness of a program? What is guard code? [2] 3. What is a base class? What is a derived class? How are these two interrelated? [3] 4. Explain: a.) Encapsulation b.) Transitive nature of inheritance c.) portability [3] (Total: 10M) 1. Convert the following binary number to decimal: a) 101.1001 b) 11101.111 2. Convert the following octal values to decimal a) 1204.3 b) 743 3. Convert the following decimal values to hexadecimal: a) 314.21 b) 2048 4. Convert the following decimal values to binary: a) 57.31 b) 29.2 5. Convert the following binary number to hexadecimal: a) 1010110110111 b) 10110111011011 (1M X 5 =5M) 6. Differentiate between: a) RAM and ROM b) impact printer and non impact printer. [4] 7. What is a port? [1] (Total: 10M) 1. Determine then output if the input is: ( a ) 2000 ( b ) 1900 ( c ) 1971 void main( ) { int year; cin>>year; if ( year%100 = =0) -------------------------------------------------------------------------------------------------------

IV.

{ if ( year % 400 = =0) cout<< LEAP; } else cout<< not century year; } 2. Write a short program that subtracts two matrices A [4][4] and B [4][4]. [3] [3]

3. Determine the output for the following code fragment if the input is: new york void main( ) { char city [35]; cout<< enter city name \n; cin>>city; cout<< you entered << city<<endl; cout<<\n Enter the same city name again \n; cin.getline(city, 35); cout<< this time you entered <<city<<endl; } [2] 4. Name the header files to which the following built-in functions belong: a) write( ) b) getch( ) c) gets( ) d) strlen( ) 5. Write two benefits of header file.

[2] [2] (Total: 12M)

V.

1. Determine the total bytes required to store the following array: a) int marks[5][3] b) char name[20] 2. Write a short program to print the following series: 3 6 9 12.33. 3. Write a flowchart to find smallest of three numbers. 4. Write the function prototypes for the following: a) Average ( ) take two arguments of type integer and return a float value. b) Sum ( ) takes an int array and an int value and returns a long result. 5. What is an array and how many types of arrays are there? 6. Explain event driven programming.

(2M X 6=12M)

VI.

1. Explain characteristics of auto and register storage class specifiers. 2. What is scope of a variable? Write the names of all scopes present in c++? 3. Differentiate between call by value and call by reference mechanism. -------------------------------------------------------------------------------------------------------

4. What is the effect of absence of break in a switch statement? Can the case labels in a switch have identical values? 5. Rewrite the following code fragment using switch: void main ( ) { if (ch = = E) cout<< Eastern Zone; else if ( ch = = W) cout << Western Zone; else if (ch = = N) cout<< North Zone; else if (ch = =S) cout << South Zone; else cout<< Invalid Zone; } (2 X 5 = 10)

VII

1. Determine the output: #include<iostream.h> void func(int num, b=5) { auto int total=0; static int sum=0; for ( int i=num; i>0 ; i--) total+=i; sum+=total; cout<<total<< <<sum<<b<<endl; } void main( ) { int x=8; for(int j=1; j<3; j++) func(i); } 2. What are the outputs of the following two code fragments? Justify your answer.

//version 1 int f =1, i = 2; while(++i <5)

//version 2 int f =1, i = 2; do{

-------------------------------------------------------------------------------------------------------

f * = i; cout<<f ;

f * = i; }while(++i<5); cout<<f ;

(5X 2 = 10)

-------------------------------------------------------------------------------------------------------

Vous aimerez peut-être aussi