UNIT 1 Expected No of Questions : 02ehelp.yolasite.com/resources/c++ study meterial.doc · Web...

56
- 1 - UNIT 1 ( Expected No of Questions : 02) Chapter 1 : C++ Programming Basics: Introduction to object orientation (Refer unit 5 ) Functions (Refer unit 3) History and evolution: 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 1980’s. C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the class was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However in later in 1983, the name was changed to C++. The idea of C++ comes from the increment operator ++, thereby suggesting that C++ is an incremental version of C++. Let us begin with a simple example of c++ program: #include <iostream> using namespace std; int main() { // this is an example of c++ program to illustrate some of its features cout << “c++ is better than c”; return 0; Introduction and C++ Programming Basics Introduction to object orientation, history and evolution, Functions, Program Statements, White spaces, Output using cout, string constants, Preprocessor directives, Constants, Integer Variables, Character variables, input with cin, cascading using <<, expressions, precedence, floating point constants and variables, type conversion, Arithmetic

Transcript of UNIT 1 Expected No of Questions : 02ehelp.yolasite.com/resources/c++ study meterial.doc · Web...

- 1 -

UNIT 1 ( Expected No of Questions : 02)

Chapter 1 : C++ Programming Basics:

Introduction to object orientation(Refer unit 5 )Functions (Refer unit 3)History and evolution: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 1980’s. C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the class was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However in later in 1983, the name was changed to C++. The idea of C++ comes from the increment operator ++, thereby suggesting that C++ is an incremental version of C++. Let us begin with a simple example of c++ program:

#include <iostream>using namespace std; int main() { // this is an example of c++ program to illustrate some of its features cout << “c++ is better than c”; return 0; }

Program Featuers:Comments:C++ supports two types of comments

1. c style comment ( /* */) or multi line comment Anything enclosed within a pair of /* and */ is treated as comment.

E.g: /* this is an example of c++ program to illustrate some of its features cout << “c++ is better than c”;

*/

Introduction and C++ Programming Basics Introduction to object orientation, history and evolution, Functions, Program Statements, White spaces, Output using cout, string constants, Preprocessor directives, Constants, Integer Variables, Character variables, input with cin, cascading using <<, expressions, precedence, floating point constants and variables, type conversion, Arithmetic operators, Library Functions – header files, library files.

- 2 -

during compilation ,compiler just ignores the code between /* and */

2. // (double slash) or single line commentC++ introduces a new comment symbol //(double slash). Comment starts with a double slash and terminate at the end of the line. A comment may start anywhere in the line, and whatever follows till the end of the line is ignored.

Eg: // this is an example of c++ program to illustrate some of its features

Return type of main()

In C++, main() returns an integer type value to the operating system. There fore every main() in c++ should end with return(0) statement; otherwise a warning error might occur. Since main() returns an integer type value, return type for main() is explicitly specified as int. Note that that the default return type for all functions in c++ is int. the following main without type and return will run with a warning:main(){

………..……….

}Namespace:using namespace std;This tells the compiler to use the std namespace. Namespaces are recent addition to C++. A namespace creates a declarative region in which various program elements can be placed. The using statement informs the compiler that you want to use std namespace. This is the namespace in which the entire Standard C++ Library is declared. By using the std namespace you simplify access to the standard library.

The iostream fileWe have used the following #include directive in the program:#include <iostream>This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <<. Some old versions of C++ use a header file called iostream.h. this is one of the changes introduced by ANSI C++. ( we should use iostream.h if the compiler does not support ANSI C++ features)

Output operatorThe above program has only one output statement i.e is cout << “c++ is better than c”;causes the string in quotation mark to be displayed on the screen. This statement uses two C++ features, cout and <<. The identifier cout is a predefined object that represents the standard output stream. In C++ standard output stream represents the screen. Note: it is also possible to redirect the output to other output devices. That we will discuss in unit 6.

- 3 -

The operator << is called the insertion operator. It inserts the contents of the variable on its right to the object on its left.

Input operatorThe Statementcin >> number1; is an input statement and causes the program to wait for the user to type a number.The identifier cin is a predefined object in c++ that corresponds to the standard input stream.The operator >> is known as extraction operator. It extracts the value from the keyboard and assigns it to the variable on its right.

Cascading I/O operator:If we use more than one insertion or extraction operator in one statement then that operator is said to be cascaded.Example1: cascading of input operatorcin >> number1>>number2; Here the values are assigned from left to right . That is , if we key in two values, say 10 and 20 then 10 will be assigned to number1 and 20 to number2.Example2: cascading of output operatorcout<<”sum=”<<sum<<”\n”;

Screen

cout “C++ “

<<

Insertion varibalevariable

OBJECT extraction operator

cin >>

12.35

keyboard

- 4 -

first sends the string “sum=” to cout and then sends the value of sum. Finally, it sends the newline character so that the next output will be in the new line.

Constants:A constant is an quantity that does not change .This quantity can be stored at a location in the memory of the computer. A variable can be consider as a name given to the location in memory where this constant is stored. Naturally the contents of the variable can change. For example in the equation3x+y=20since 3 and 20 cannot change, they are called constants, whereas the quantities x and y can vary or change hence are called variables. Constants can be classified as integer, floating point, character, string and enumeration constants.1) Integer Constants:C++ allows to represent the integer constants in three forms.

Octal number system. Decimal number system. Hexadecimal number system.

Octal numbers are specified with a leading zero. Rest of the digits being between 0 and 7.e.g: 0175 0123Decimal number system is represented by using digits 0 - 9e.g:129Hexadecimal numbers are specified with 0x or 0X in the beginning .The digits that follow 0x must be numbers in the range 0 – 9 or one of the letters a – f or A – F.e.g:0xa10XB4The size or sign qualifier can be appended at the end of the constant. The suffix u is used for unsigned int constants.l for long int constants, s for signed int constants. It is not case sensitive.e.g:567u567U2)floating point constants:Decimal notation here the number is represented as a whole number, followed by a decimal point and a fractional part.e.g:3.444241.67Exponential notation is useful in representing nos whose magnitude is very large or very small.3.4e4

- 5 -

3e83) Character constants:A character constant is enclosed in single quotes.e.g:‘a’‘s’‘\n’4)String literals:A string literal is a sequence of characters enclosed in double quotes.The characters may be letters, numbers, escape sequences or clank spaces.Note: A String always ends with a null character or ‘\0’

VariablesA variable is an quantity whose value can be changed during program execution. Variable names are names given to the locations in memory of a computer where different constants are stored.The general form of variable declaration istype variable_list;here type must be a valid data type.Example:int a,b;float f1,f2;DataTypes in C++

C++ data types

Built in type/ Basic data types

User defined type

structureunionclassenumeration

Derived Data Type

arrayfunctionpointerreference

void Floating typeIntegral type

int char float double

- 6 -

Built-in Data Types/ basic data types /Primary data Types:are:1.char2.int3.float4.double5.void

Type Modifiers:Different type modifiers are long, short, unsigned and signed. Type modifiers are used to derive another data type from primary data types. But we cannot apply all type modifiers to all data types.

Data Type Range Byteschar -127 to +128 1signed char -127 to +128 1unsigned char 0 to 255 1int -32767 to +32768 2signed int -32767 to +32768 2unsigned int 0 to 65535 2short int -32767 to +32768 2short signed int -32767 to +32768 2short unsigned int 0 to 65535 2long int -2147483647 to 2147483648 4long signed int -2147483647 to 2147483648 4long unsigned int 0 to 4294967295 4Float -3.4e308 to +3.4e308 4Double -1.7e308 to +1.7e308 8long double -1.7e4932 to +1.7e4932 10

*Note: these data types are also called as Variable types.

Type conversions:There is automatic type conversion in C++; you can multiply an int by float etc.The operands of different types when executed in the same expression, the lower-type variable is converted to the type of higher type variable.

Data Type orderlong double (highest)

(lowest)

DoubleFloatIntChar

When the automatic data conversion do not takes place the programmer needs to convert a value from one type to another.

- 7 -

C++ permits explicit type conversion of variables or expressions using the type cast operator.C++ supports following two types of typecast operator:(type name) expression // C notationtype name (expression) // C++ notation

Examples: Avg=sum/(float)i; Avg=sum/float(i);

Arithmetic operators:

Operator Meaning Example Result+,- Unary Positive,

Negative+500-100

500-100

+ Addition 5+10 15

- Subtraction 5 – 10 -5* Multiplication 5 * 10 15

/ Division 22 / 7 3.14159% Modulus 5 mod 2 1++ Increment operator-- Decrement operator

The Remainder Operator / modulus operator( %).This operator finds the remainder when one number is divided by another.Example:int main(){

cout << 6%8<<endl;cout << 7%8<<endl;cout << 8%8<<endl;cout << 9%8<<endl;cout << 10%8<<endl;

return 0;}This program would display the values:67012Increment and Decrement operators( ++ , --):The operator ++ adds 1 to its operand, and – subtracts one, in otherwords

- 8 -

x=x+1;is same as ++x;andx=x-1;is same as x--;Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand. For example,x=x+1; can be written ++x or x++There is , however, a difference between the prefix and postfix forms when you use these operators in an expression. When an increment or decrement operator precedes its operand, the increment and decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, the value of the operand is obtained before incrementing or decrementing it. For examplex=10;y= ++x;sets y to 11. However if you write the code asx=10;y=x++;y is set to 10. Either way, x is set to 11.

Here is the precedence of the arithmetic operators

Highest

Lowest

++ ---(unary minus) + (unary minus)* / %+ -

Operators on the same level of precedence are evaluated by the compiler from left to right.

ManipulatorManipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw.

The endl manipulators, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character “\n”. For example:…………cout << “m = “ <<1000<<endl;cout << “n = “ <<20 <<endl;cout << “p = “ <<3 <<endl;…….…….

- 9 -

Would cause three lines of output, one for each variable as follows:

1 0 0 02 03

Note that By default outputs are left-justified. It displays the output from the left hand side. The manipulator setw(n) specifies the field width n for displaying the value. Here the output is Right-justified. It displays the output from the right hand side.

For example…………cout << “m = “ <<setw(5)<<1000<<endl;cout << “n = “<< setw(5) <<20<<endl;cout << “p = “<< setw(5)<<3 <<endl;…….…….Would cause the following output:

1 0 0 02 0

3

The manipulator setw(6) specifies a field width 5 for displaying the values of the variables.

White Space or escape sequences in C++

The following table shows some of the Escape sequences in C++

Code Meaning\b Backspace\f Form feed\n New Line\r Carriage return\0 Null\a Alert\\ Backslash\v Vertical tab\t Horizontal tabtypedef statementtypedef statement is used to redefine the name of an existing variable type.For example, consider the following statement in which the type unsigned long int is redefined to be of type TWOWORDS:

m =n =p =

m =n =p =

- 10 -

unsigned long int TWOWORDS;now we can declare variables of the type unsigned long int by writingTWOWORDS var1,var2Instead ofunsigned long int var1,var2;thus, typedef provides a short and meaningful way to call a data type.

Preprocessor DirectivesPreprocessor Directives are not the program statements .These are instructions to the compilers. The preprocessor contains the following directives:

#define #elif #else #endif #error #undef #if #ifdef # ifndef #include #line #pragma

All preprocessor directives directives begin with # sign. Preprocessors is the part of the compiler and deals with these directives before it begins the real compilation process.

a) #define Directive

consider the program

#include <iostream> #define LIMIT 25 int main() { for ( int i=0 ;I < LIMIT ; i++) cout << I;

return 0;

}

#define LIMIT 25This statement is called “macro definition” (or macro). During the preprocessing, the preprocessor replaces every occurrence of LIMIT in the program with 25.

When we compile the program, before the source code passes to the compiler it is examined by the C++ preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in search of the macro templates; whenever it finds one, it replaces the macro template with the appropriate macro expansion.

b) #include Directive

#include tells the compiler to insert another file into your source file.

- 11 -

E.g #include <iostream> instruct the compiler to read and compile the header for the c++ I/ system library functions.

C) #undef Dirctive

In order to undefined a macro which has been earlier defined, the directive

#undef macrotemplate

can be used.

E.g: #undef LIMITWould cause the definition of LIMIT to be removed from the system.

D) #ifdef and #endif

General Form:

#ifdef macroname stmt 1 stmt 2 stmt 3 #endif

e.g:

#ifdef LIMIT stmt 1 stmt 2 stmt 3 #endif

If the macroname has been #defined , the block of code (stmt 1,stmt 2, stmt 3) will be processed as usual; otherwise not.

E) #if, #else , #elif, #endif

The general form is

#if constant-expression statement sequence#endif

- 12 -

if the constant expression following #if is true, the code that is between it and #endif is compiled. Otherwise, the intervening code is skipped. The #endif directive marks the end of an #IF block.

E.g:

The #elif directive means “else if” and establishes an if-else-if chain for multiple compilation options.

The general form is

#if expression statement sequence#elif expression1 statement sequence

#elif expression2 statement sequence…--#elif expression n statement sequence

#endif

------------------------------------------------------------------------------------------------------------University questions:

1.What is the output of the following program segment.int *I;void *p=*I;

a) error b) address of pointer I is stored in pointer pc) value of i is stored in p d)value of I is stored in the location where the pointer p points to

2) cout<<width(10)<<no1;cout<<no2 // this statement willa) displays the nos with a width of 10 b)produces errorc)displays the no1 with width 10 d)result unpredictable.

3) which of the following is a manipulatora)setw() b)endl c)ios::left d)fill()

(6+4)

- 13 -

Explain the integer variables and character variables along with suitable example programs.What is the use of const qualifier and #define directive.

(4+6)Along with suitable example program explain manipulatorsExplain—a)Arithmetic assignment operators b) Increment operators.App/ May 2004a) Explain escape sequences.b) Explain—a)Arithmetic assignment operators b) Increment operators.App/ May 2004a)Explain the integer variables and character variables along with suitable example programs.b)What are preprocessor directives?explainNov 2003

a) what are the advantages of OOPs?b) Explain the general structure of C++ program.

Nov 2003a) Explain the different data types supported by C++ with examples.b) Write a C++ program to read two integers and compute their bitwise NAD,

OR ,EXOR and complement and output the result in a neat format with suitable labels.

- 14 -

UNIT 2 ( Expected No of Questions : 01)

Relational Operators

The Relational operators are used to construct a relational expression.The complete set of C+ relational operators are given in the following table.

Operator Comparison Example Meaning== Equal to X==Y Is X equal to Y?> Greater than X>Y Is X Greater than

Y?< Less tan X<Y Is X less than Y?>= Greater than OR

Equal toX>=Y Is X Greater than or

equal to Y?<= Less than Or Equal

to X<=Y Is X less than Y?

!= Not Equals X != Y Is X not equal to Y?

Logical Operators

Logical operators are used to combine one or more relational expressions. They compare two relational expressions and return true or false value based on the result of the comparison.The following table lists the commonly used Logical operators to construct a logical expression.For Example: ( X < 10) and (Y > 10)

Operator Example Result after Evaluation&& X && Y true if both X and Y are

true; false Otherwise|| X || Y true X or Y , or both of

them, are true; false only if both X and Y are false.

! !X true if X is false, false if X is true.

Programming ConceptsLoops and decisions, relational operators, for, while and do loops, if, if-else, switch, conditional operator, logical operators, precedence, break, continue and goto statements, structures and enumerated data types

- 15 -

C++ fully supports the zero\non-zero concept of true and false. However, it also defines the bool data type and the boolean constants true and false. In C++ , a 0 value is automatically converted into false, and a non-zero value automatically converted into true. The reverse also applies: true converts to 1 and false converts to 0. In c++ outcome of a logical expression is true or false.e.g:cout << (5>2); would display “true”

Precedence of Arithmetic, Relational and Logical operators. Arithmetic Relational/comparison

operatorsLogical Operators

++ --- > >= < <= !

- (Unary Minus) == != &&* / % ||+ -

Bitwise OperatorsBitwise operators can be applied only to char and int data types. You cannot use bitwise operators on float, double, long double, void, bool, or other, more complex types.

Operator Action& AND| OR^ XOR~ NOT (one’s complement)>> Shift right<< Shift left Bitwise Operators

Highest

Lowest

- 16 -

- 17 -

Conditional Statements or Selection Statements or Branching Statements :

C/C++ supports three types of selection statements:1. if2. switch3. turnary (?) operator

if:The if statement may be implemented in different forms depending on the complexity of the conditions to be tested:

1. Simple if statement2. if…..else statement3. Nested if…else statement.4. else if ladder.

Simple if:The general form of a simple if statement is

The ‘statement_block’ may be a single statement or a group of statements. If the test expression is true , the statement_block will be executed; otherwise the statement_block will be skipped and the execution will jump to the statement-x’.E.g:………………………………if( category == SPORTS){

marks = marks + bonus_marks;}cout<<marks;…………………….…………………….The program tests the type of category of the student. If the student belongs to the SPORTS category, then the additional bonus_marks are added to his marks before they are printed. For others bonus_marks are not added.

The if….else statement:

if ( test expression){

Statement_block;

}statement-x;

- 18 -

The if…else statement is an extension of the simple if statement. The general form is

If the test expression is true, then the true-block statement(s) immediately following the if statement, are executed, otherwise, the false-block statement(s) are executed. In either case either true-block or false-block will be executed, not both.

Let us consider an example of counting the number of boys and girls in the class. we use code 1 for boy and 2 for girl. The program statement to do this may be written as follows:………………………………………..if(code==1)

boy=boy+1;else girl = girl+1;;xxx;if the code is equal to 1, the statement boy=boy+1; is executed and the control is transferred to the statement xxx, after skipping the else part. If the code is not equal to 1, the statement boy = boy+1; is skipped and the statement in the else part girl = girl+1; is executed before the control reaches the statement xxx.Nesting of if else statements:When a series of conditions are involved, we may have to use more than one if….else statement in nested form as follows:

if (test expression){ True-block statement(s)}else{ False-block statement(s)}statement-x;

If (test-condition1 ){ If (test-condition2){ Statement-1;

} else{ Statement-2 } } else{

Statement -3 } Statement-x;

- 19 -

Here if the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be executed; otherwise statement-2 will be executed and then the control transferred to the statement-x;

E.g:(left as an assignment)

The else if ladderThe general form is

This construct is known as else if ladder,. The conditional are evaluated from the top (of the ladder), downwards. As soon as the true condition is found , the statement associated with it is executed and the control is transferred to the statement-x(skipping the rest of the ladder). When all n conditions becomes false, then the final else containing the default statement will be executed.

Exercise:

Write an else if ladder for finding the grade.The grading is to be done according to the following rules:Average marks Grade80 to 100 Honours60 to 79 First Division50 to 59 Second Division40 to 49 Third Division0 to 39 Fail

if (condition 1) statement 1; else if (condition 2) statement 2 else if (condition 3) statement 3 …………………….

else if (condition n) statement n else default statement;statement x;

- 20 -

The Switch Statement:The switch statement tests the value of a given variable (or Expression) against a list of case values and when a match is found , a block of statements associated with that case is executed. The general form of the switch statement is shown below:

The expression is an integer expression or characters. value-1, value-2…. are constants or constant expressions and are known as case labels. Each of these values are should be unique within a switch statement. When the switch is executed the value of each expression is successively compared against the values value-1, value-2,…If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.E.g:switch (marks){case 90:case 80:case 70: grade=”Firsht class with distinction”; break;case 60: grade=”First class” break;case 50: grade=”Second class” break; case 40:grade=”pass class” break; default : grade=”Fail “

switch (expression){

case value-1: block-1; break; case value-2: block-2; break; ………….. ..…………. default: default-block; break;

- 21 -

}cout << “Result :”<<grade;The ?: operatorThe operator is popularly known as the conditional operator. The general form of the conditional operator is as follows:

The conditional expression is evaluated first. If the result is true, expression1 is evaluated and returned as the value of the conditional expression. Otherwise expression2 is evaluated and its value is returned.

For exampleThe segment If (x < 0) Flag=0; Else Flag1=0;

can be written as flag = (x<0) ? 0:1;Looping Statements:

A Looping process in general would include the following four steps:1. Setting and initialization of a counter.2.Execution of the statements in the loop.3.Test for a specified condition for execution of the loop.4.Incrementing the counter.

The C/C++ Language provides for three constructs for performing the loop operations. They are1.The while statement2. The do statement.3. The for statement.

1.The while statementThe simplest structure of all the looping structure in C/C++ is the while statement. The general format of the while statement is

conditional expression ?: expression1 : expression2

Initialization;while ( test-condition){

body of the loop}

- 22 -

The while is an entry-controlled loop statement. The test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop.E.g:………….………….sum=0;n=1while( n <= 10){

sum = sum + n*n; n=n+1;}cout << “sum = “<<sum;………………………………

The body of the loop is executed 10 times for n =1,2,….,10 each time adding the squre of the value of n, which is incremented inside the loop.

2. The do statement.The general format of the do statement is

On reaching the do statement, the program proceed to evaluate the body of the loop first. At the end of the loop, the test condition in the while statement is evaluated. if the condition is true, the program continuous to evaluated the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement.

Since the test condition is evaluated at the bottom of the loop , the do…while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.

Initialization;do{

body of the loop}while (test-condition);

- 23 -

Consider an example:………….………….sum=0;i=1do{

sum = sum + 1; i=i+2;;} while( n < 40 || I < 10);………………………………the loop will be executed as long as one of the two relation is true.

3. The for statement.

The general form of the for loop is

The execution of the for statement as follows:1.Initialization of the control variables is done first.2. The value of the control variable is tested using the test condition. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is incremented and the new value of the control variable is tested to see whether it satisfies the loop condition . if the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test condition.

E.g:Consider the following code fragment,

for ( x=0 ; x<=9;x=x+1){cout <<x;}

for (initialization ; test condition ; increment){

Body of the loop

}

- 24 -

This for loop is executed 10 times and prints the digits 0 to 9 in one line.

Additional Features of For Loop:

1. More than one variable can be initialized at a time in the for statement.e.g :for ( x=0,y=1 ; x<=9;x=x+1){cout <<x<<y;}

2. Like initialization section More than one variable can be incremented at a time in the for statemente.g :for (x=0,y=1 ; x<=9;x=x+1,y=y+1){cout <<x<<y;}3. Variables can be defined inside the for loop

e.g :for ( int x=0 ; x<=9;x=x+1){cout <<x<<y;}

Structures and Enumerated Data types:Structures:A structure is a collection of simple variables. The variables in a structure can be of different types: some can be int, some can be float so on.

Declaring the structure:

The general form for structure declaration statement is given bellow:

struct structure_name{ type member_name; type member_name; type member_name; . . .}[structure variables];

- 25 -

E.g:To store information about a book, we can declare a structure as follows

struct book {

char Name[20]; structure structure deffination.int Price; members int Pages;

} ;

This statement defines a new data type called struct book. Each variable of this data type will consists of a string variable called name, a integer variable Price, a integer variable called Pages.

Defining the structure variable:Once, the new data type has been defined one or more variables can be declared to be of that type.general form is

[struct ] structure_name structure variables;

here struct key word is optional.

E.g:For example the variables b1,b2,b3 can be declared to be of the data type struct book asbook b1,b2,b3 orstruct book b1,b2,b3

Note:We can combine the declaration of the structure type and the structure variables in one statement as

struct book {

char Name[20]; int Price;int Pages;

} b1,b2,b3 ;

Accessing structure members:Once a structure variable has been defined, its members can be accessed using the dot operator.e.g: b1.price=100

- 26 -

note the following points while using the structures:a) The closing brace in the structure type declaration must be followed by a

semicolon.b) It is important to understand that a structure type declaration does not tell the

compiler to reserve any space in memory. All structure declaration does is, it defines the ‘form’ of the structure.

c) Memory resources are allocated only during the definition of a structure variable. whatever be the elements of a structure, they are always stored in contiguous memory locations.

Exercise:Write a program to enter the details of students and display it using the structure concept:( ref class notes)

Nested structures:Structures within structures called as nested structures.One structure can be nested within another structure. Using this facility complex data types can be created.e.gstruct book {

char Name[20]; int Price;int Pages;struct date{

int date;int month; ORint year;

}reprint;

} b1,b2,b3 ;

Accessing nested structure members:Because one structure is nested inside another, we must apply the dot operator twice to access the structure members.

b1.reprint.date=10;b1.reprint.month=01;b1.reprint.year=99;

Exercise: Write the program to demonstrate the use of nested structures.( left as an assignment)

struct date{int date;int month;

int year; }

struct book{ char Name[20]; int Price; int Pages;

date reprint; } b1,b2,b3;

Nested structure variable

- 27 -

Enumerated Data types:Def: Enumeration is a set of named integer constants that specify all the legal values a variable of that type may have.

E.g: An enumeration of the coins used in the United States isPenny, nickel, dime, quarter, half-dollar, dollar

Enumerations defined much like structures, the key word enum signals the start of an enumeration type. The general form for enumeration is

The following code fragment defines an enumeration called coin.enum coin {

penny, nickel, dime, quarter, half-dollar,

dollar}Defining the enumeration variable:The general form is[enum] enum_name enumeration_variable list;

e.g. coin money ;

this enumeration variable i.e money can take only the values defined in the enumeration_list(i.e , Penny, nickel, dime, quarter, half-dollar, dollar)

Given these declarations following types of statements are perfectly valid:

money = dimeif (money == quarter) cout << “money is a quarter”;

Remember we can’t use values that aren’t in the enumeration_list. Thus the expression,

enum enum_name{

enumeration_list

} [enumeration_variable list];

- 28 -

Money = rupeesWould cause an compile time error.Internally, the compiler treats the enumerators as integers. ordinarily the first name in the list is given the value 0, the next name is given the value 1 one more than the previous value . So on.e.g : The statement cout << nickel; would display 1 on the screen.

You can specify the value of one or more of the symbols by using an initializer.Consider an example enum coin {

penny, nickel, dime=100, quarter, half-dollar,

dollar}

cout << penny << nickel << dime << quarter << half-dollar <<dollar ;would display 0 1 100 101 102 103 on the screen.

break, continue and goto statements:

The break statement:The break statement has two uses.1. To terminate case in the switch statement. (Ref switch statement for details)2. To force immediate termination of a loop When a break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.For example# include<iostream.h>int main(){

int x;for ( x=0 ; x<100;x=x+1){

cout <<x;if( x==10) break;

}return 0;}

- 29 -

Prints the number 0 to 10 on the screen. Then the loop terminates because break causes immediate exit from the loop, overriding the conditional test x<100,

The continue statement:The continue statement forces the next iteration of the loop to take place, skipping any code in between, For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while an do..while loops the program control passes to the conditional tests.(ref next page for more details)The goto Statement: The goto Statement is an unconditional transfer statement.The goto statement requires a label for operation. (A label is a valid identifier followed by a colon.) Furthermore, the label must be in the same function as the goto that uses it – you cannot jump between functions.The general form is

Where label is any valid label either before or after goto. For Example, you could create a loop from 1 to 100 using the goto and a label , as shown here:

x=1;loop1:

x++; if( x <100 ) goto loop1;

------------------------------------------------------------------------------------------------------------University questions:

(5+5)Write the program to show the usage of switch statement. The program should also show the usage of getche() library function.What are structures? Write the program to demonstrate nested structures. (4+6) April/may 2004write a note on enumerated data typeswhat are structures ? write a program to demonstrate nested structures.(6+4)nov 2003Explain with examples various loop control structures supported by c++Wrire c++ prog to generated ‘N’ prime numbers.

goto label;……….lablel:

- 30 -

- 31 -

UNIT 3 ( Expected No of Questions : 01)

Functions:A function is a set of program statements that can be processed independently. A function can be invoked which behaves as through its code is inserted at the point of the function call.The communication between a caller (calling function) and the callee (called function ) takes place through parameter.Why use functions?

1. Writing functions avoids rewriting the same code over and over.2. Program and Function debugging is easier.3. Separating the code into modular functions also makes the program easier to

design and understand.Important points:

Any C++ program contains at least one function. If a program contains only one function, it must be main(). There is no limit on the number of functions that might be present in the

C++ program. After each function has done its thing, control returns to main(). When

main() runs out of function calls, the program ends. Components of a function:

There are five components / elements involved in using a function: Function declaration or function prototype. Function definition Function parameters Return statement

Functions Definitions, arguments, return values, reference arguments, overloaded functions, default arguments, Variables and storage classes

# include <iostream>void printLine(char , int );int main(){

printLine (‘*’,60);return 0;

} void printLine(char ch, int n){

for(int i-0; i<n;i++)cout << ch;

}

Function call

Function prototype/ Function declaration

Actual Parameters

Formal Parameters

Function declerator

Function defination

- 32 -

Function call.

1. Function prototype/ declaration:Syntax

It provides the following information to the compiler The name of the function The type of the value returned. The total number and types of these arguments that must be supplied in a call to

the function.The function can return any data type, except array , if there is no return value, a keyword void is placed before the function name.C++ makes prototyping mandatory if functions are defined after the function main.C++ assumes void return type in case no arguments are specified in the argument list; the default return type is an integer.

2.Function Defination:

The function itself is referred to as function definition. First line of the function definition is known as function declerator & is followed by the function body.The declerator & declaration must use the same function name, the number of arguments, the arguments type and the return type. The body of the function is enclosed in bracess. C++ allows the definition to be placed anywhere in the program. If the function is defined before its invocation then its prototypes declaration is optional.

3.Function parameter:

The parameters specified in the function call are known as actual parameters and those specified in the function declarator are known as formal parameters. When a function call is made, a one-to-one correspondence is established between the actual and formal parameters.

4.Return statement:

There can be more than one return value. It can occur anywhere in the function body and as soon as it is encounted, execution control will be returned to the caller.

5.Function call:

A function is a entity which gets life when a call to the function is made. A function call is specified by the function name followed by the arguments enclosed in paranthesis and terminated by a semicolon. The return type is not mentioned in the function call.

ret_value function_name(arguments list);

- 33 -

Executing the call statement causes he control t be transferred to the first statement in the function body and after execution of the function body the control is returned to the statement following the function call.

Parameter Passing:Parameter passing is a mechanism for communication of data and information between the calling function (caller) and the called function ( callee ).It can be achieved either by passing the value or address of the variable.C++ supports the following three types of parameter passing schemes:1.Pass by value / Call by value2.Pass by address.3.Pass by reference. (only in C++)

1.Pass by value / Call by valueThis method copies the value of an actual argument into the formal parameter of the function. In this case changes made to the formal parameter have no effect on the actual arguments.

e.g:# include<iostream.h>void swap(int a,int b){

cout<<”before interchange (within function) “<<a<<” “<<b; temp x =a; a= b; b=x; cout<<”after interchange (within function) “<<a<<” “<<b;}int main(){

int x,y;x=10;y=20;cout<<”before swap “<<x<<” “<<y;

main() swap() 1000 x 1250 a

1500 y 1450 b

10

20

10

20

PASS BY VALUE METHOD

- 34 -

swap(x,y) cout<<”after swap “<<x<<” “<<y;return 0;

}This program would display

before swap 10 20before interchange(within function) 10 20after interchange (within function) 20 10

after swap 10 20 Here changes made to the parameter within the function will effect only the copy (formal parameters) , & will have no effect on the actual argument.

2.Pass by address.Instead of passing the value, the address of the variable is passed.In the function address of the argument is copied into a memory location instead of value.The dereferencing operator is used to access the variable in the called function.Here changes made to the formal argument affect the actual arguments.

E.g:# include<iostream.h>void swap(int *a,int *b){

cout<<”before interchange (within function) “<<a<<” “<<b; temp x =*a; *a= *b; *b=*x; cout<<”after interchange (within function) “<<a<<” “<<b;

}int main(){

int x,y;x=10;y=20;cout<<”before swap “<<x<<” “<<y;swap(&x,&y)

main() swap() 1000 x 1250 a

1500 y 1450 b

10

20

1000

1500

PASS BY Address METHOD

- 35 -

cout<<”after swap “<<x<<” “<<y;return 0;

}

This program would display before swap 10 20before interchange(within function) 10 20after interchange (within function) 20 10

after swap 20 10

3.Pass by reference.Passing parameters by reference has the functionality of pass by address and the syntax of call by value. Any modification made through the formal parameter is also reflected in the actual parameter. Therefore the function body and call to it is identical to that of call by value, but has the effect of call be address.To pass an argument by reference the function call is similar to that of call by value.In the function decelerator, those parameters which are to be received by reference must be preceded by the &operator. The reference type formal type parameters are accessed in the same way as normal value parameter. However any modification to them will also be reflected in the actual parameter.

e.g:

# include<iostream.h>void swap(int &a,int &b){

cout<<”before interchange (within function) “<<a<<” “<<b; temp x =a; a= b; b=x; cout<<”after interchange (within function) “<<a<<” “<<b;

}int main()

1000 x 1250 a

1500 y 1450 b

10

20

1000

1500

PASS BY Reference METHOD

- 36 -

{int x,y;x=10;y=20;cout<<”before swap “<<x<<” “<<y;swap(x,y) cout<<”after swap “<<x<<” “<<y;return 0;

}This program would display

before swap 10 20before interchange(within function) 10 20after interchange (within function) 20 10

after swap 20 10

Default Arguments:

C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.E.g:# include <iostream>void printLine(char =”-“, int =7 );int main(){

printLine ();printLine(“+”,4);printLine(“#”);return 0;

}void printLine(char ch, int n){

for(int i-0; i<n;i++)cout << ch;

}

output-------++++#######

Remember that missing arguments must be the trailing arguments-those at the end of the argument list. You can leave out the last three arguments, but you cannot leave out the next-tolast and then put in the last.For EgConsider the above program and following function call

- 37 -

printLine(5);would generate the compile time error because Here the first argument is missing, not the trailing arguments.

Inline Functions:An Inline function is a function that is expanded inline when it is invoked. That is, the compiler replaces the function call with the corresponding function code.The Inline functions are defined as follows:

Here inline keyword is a request, not a command to the compiler. The compiler may ignore this request if the function definition is too long or too complicated and compile the function as a normal function.Some situations where inline functions may not work are:

1. If a function contain static variable.2. If inline functions are recursive.3. For function returning values, if a loop, a switch, or a goto exists.

E.g:

When will you make a function inline ? why?When a function is called, it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments in to the stack, and returning to the calling function. When a function is small, a substantial percentage of execution time may be spent in such overheads.To overcome these problems in C++, declare the function as an inline.

Inline functions makes a program run faster because the overhead of a function call and return is eliminated. However it makes the program to take up more memory because the statements that define inline function are reproduced at each point where the function is called.

inline function-header{ function body

}

# include <iostream>inline int max(int a, int b){

return a > b ? a : b;}int main(){cout << max (99,98);return 0;}

# include <iostream>inline int max(int a, int b){

return a > b ? a : b;}int main(){cout <<(99 > 98 ? 99 : 98);return 0;}

As for the compiler is concerned, the preceding program is equivalent to this one:

- 38 -

Overloaded Functions:In C++, two or more functions can share the same name as long as their parameter declarations are different. In this situation, the functions that share the same name are said to be overloaded, and the process is referred to as function overloading.E.g:In C abs() function returns the absolute value of an integer, fabs()function returns the absolute value of a double, labs()function returns the absolute value of a long. Here all these functions perform identical actions but the function names are different. This makes the language more complex. In C++ , you can use just one name for all three functions:int Abs(int );long Abs(long );double Abs(double);int main(){

cout << Abs(-10)<<endl;cout << Abs(-9L)<<endl;cout << Abs(-5.5)<<endl;

return 0;}int Abs(int a){

cout <<”using integer abs”;return i < 0 ? –i : i;

}long Abs(long a){

cout <<”using long abs”;return i < 0 ? –i : i;

}double Abs(double a){

cout <<”using double abs”;return i < 0 ? –i : i;

}

output:using integer abs 10using long abs 9using double abs 5.5This program creates three similar but different functions called abs(), each of which returns the absolute value of its argument. The compiler knows which function to call in each situation because of the type argument.Consider another program:display(long);display(double);int main(){

A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. The function selection involves the following steps:1. The compiler first tries to find an exact match in which the types of actual arguments are the same, and use that function.2. if an exact match is not found, the compiler uses the integral promotions to the actual arguments such aschar to intint to longfloat to double etcto find a match3. still an exact match is not found, then the compiler will generate the compile time error.

- 39 -

display(1);display(5.5);return 0;

}void display(double l){

cout << l;}

void display(double d){cout << d;

}

In this example the first function call is an display with integer parameter. Compiler first searches for the exact match .But there is no functions with integer integer parameter. Then the compiler uses an integral promotion to the actual arguments (int to long) again it searches for the exact match. In the above example compiler executes display with long parameter for display with integer parameter.

Storage Classes in C++There are four storage classes in C++

1. Automatic storage Class2. Register storage Class3. Static storage Class4. External storage class

1. Automatic storage Class

The features of a variable defined to have an automatic storage class as under:Storage : MemoryDefault initial value: Garbage value (Unpredictable value)Scope : Local to the block in which the variables are defined.Life :Till the control remains within the block in which it is defined.

Automatic storage class is defined by using the keyword auto. The scope and life of a variable is local to the block within which it is defined. This is illustrated in the following example:int main(){

auto int i=1;{ cout <<i; { cout << i; { auto int i=2; cout << i; } cout << i; } }

The output of this program is1121

This is because the innermost block defines another variable i with value 2 whose scope and life is only within that block. That i variable is not available outside that block.

- 40 -

return 0;}

2. Register storage Class

The features of a variable defined to have an automatic storage class as under:Storage : CPU registersDefault initial value: Garbage value (Unpredictable value)Scope : Local to the block in which the variables are defined.Life :Till the control remains within the block in which it is defined.

Value stored in a CPU register can always be accessed faster than the one which is stored in memory. Therefore, if a variable is used at many places in a program it is better to declare its storage class as register. The storage class is defined by using the keyword register.E.g:int main(){

register int i;for(i=0;i<=10;i++)cout<<i;

return 0;}We cannot use register storage class for all types of variables. For example, the following declarations are wrong:register float f;register double r;register long l;

3. Static storage class

The features of a variable defined to have an automatic storage class as under:Storage : MemoryDefault initial value: ZeroScope : Local to the block in which the variables are defined.Life :Value of the variable persists between different function calls.

Compare the two programs and their output given in below fig. to understand the difference between the storage classes automatic and static.

Note: Number of CPU registers are limited. if all the registers are full or busy doing some other task, then compiler treats that variable as auto.

int main(){ increment(); increment(); increment();

return 0;}void increment(){ auto int i=1; cout << i; i++;}output:111

int main(){ increment(); increment(); increment();return 0;}void increment(){ static int i=1; cout << i; i++;}output:123

- 41 -

Like auto variables, static variables are also local to the block in which they are declared. The difference between them is that static variables don’t disappear when the function no longer active. Their values persist. If the control comes back to the same function again the static variables have the same values they had last time around.

In the above example, when variable is auto, each time increment () is called it is re-initialized to one. On the other hand, if i is static. It is initialized to 1 only once. It is never initialized again.

4.External storage Class:

The features of a variable defined to have an automatic storage class as under:Storage : MemoryDefault initial value: ZeroScope :Global.Life :As long as the program execution does not comes to end.

E.g:

int i ;int main(){ cout << i

increment(); increment(); increment();

return 0;}void increment(){ i++; cout << i;<<endl; }

output:0123

Friend Functions: Ref UNIT 5Virtual Functions:

Strictly speaking the function that uses an external variable should declare the variable external via the keyword extern, as shown below int i ;int main(){extern i ; cout << i

increment(); increment(); increment();

return 0;}void increment(){ extern i; i++; cout << i;<<endl; }

extern key word tells the compiler that the variable already declared outside that block.

- 42 -

UNIVERSITY QUESTIONS:

What is the main advantage of passing arguments by reference? Write c++ program to swap two values by call by reference.When do we need to use default arguments in a function? Explain with example.When will you make a function inline ? why? How does a inline function differ from a preprocessor macro?*

Nov 2003: What are friend functions? Mention a special characteristics of a friend function.What are inline functions? How they are useful?Define static data members and static member functions.May 2004What are friend functions? Mention a special characteristics of a friend function.What is meant by call by reference and call by value? Explain with example. *According to the old syllabus