Chapter 2
Topic Contents The IO Stream class C++ Comments C++ Keywords Variable Declaration The const Qualifier The endl, setw, setprecision, manipulators The scope resolution operator The new & delete operator OOPS with C++ Sahaj Computer Solutions 2
What is C++? C++ is an object oriented programming language. It was developed by BjarneStroupstrup at AT&T Bell Laboratories in Murray Hills, New Jersey USA in 1979 Initially it was called as C with Classes However later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is augmented (incremented) version of C. OOPS with C++ Sahaj Computer Solutions 3
What is C++? C++ is superset of C. Most of what we already know about C applies to C++ also. C++ C Inheriatance Classes Function &Operator Overloading OOPS with C++ Sahaj Computer Solutions 4
Applications of C++ C++ allows us to create a hierarchical related objects, and object libraries. C++ will map the real world problem properly as well as it has the ability to get close to C part of middle level details. C++ programs are easily maintainable and expandable. It is expected that C++ will replace C as a general purpose language in the near future. OOPS with C++ Sahaj Computer Solutions 5
Comments C++ introduces a new comment symbol // (double slash). Comments start with double slash symbol and terminate at the end of the line. The comment may start anywhere in the line and whatever follows till the end of line is ignored. Note that there is no closing symbol The // comments is basically a single line comment The C comment symbol (/* */) is still valid and are known as multi line comments. OOPS with C++ Sahaj Computer Solutions 6
Comments Single Line Comments // This is an example of // C++ Program to illustrate // Comments Multi Line Comments /* This is an example of C++ program to demonstrate Multiline Comments */ OOPS with C++ Sahaj Computer Solutions 7
Keywords The keywords implement specific C++ language features and cannot be explicitly used as names for the program variables, functions, classes, structures or functions. Following are the keywords used in C++ asm auto break case catch operator private char class const continue default protected public delete do double else enum register return extern float for friend goto short signed if inline int long new sizeof static struct switch template this throw try typedef OOPS with C++ Sahaj Computer Solutions 8
Keywords union unsigned virtual void volatile while Added by Ansi C++ bool const_cast dynamic_cast explicit Export false mutable namespace reinterpret_c ast static_cast true typeid typename using wchar_t OOPS with C++ Sahaj Computer Solutions 9
Identifiers and Constants Identifiers refer to the name of variables, functions, arrays, classes, etc created by the programmers. Rules: Only alphabetic characters, digits and underscore are permitted The name cannot start with a digit. Uppercase and Lowercase letters are distinct Keywords cannot be used as variable name. Constants refer to fixed values that do not change during the execution of a program. OOPS with C++ Sahaj Computer Solutions 10
Program structure C++ program would contain four sections. The class declarations contains class definition with function declaration Member function definitions contains the definition of functions with a scope resolution operator which represents its class. Main Function is the start point of any c++ program Header Files Class Declaration Member Function definitions Main Function Program OOPS with C++ Sahaj Computer Solutions 11
First C++ Program // A simple C++ Program #include<iostream.h> intmain() { cout<< C++ is better than C.\n ; // C++ statement return 0; } //end of program OOPS with C++ Sahaj Computer Solutions 12
The iostreamfile # include<iostream.h> This directive causes the preprocessor to ass the contents of iostream file to the program. It contains declarations for cout and the operator <<. It should be included at the beginning of all programs that use input/output. OOPS with C++ Sahaj Computer Solutions 13
Output Operator C++ introduces two new features coutand <<. The identifier cout(pronounced as C out) is a predefined object that represents the standard output stream in c++. Here the standard output stream represents the screen. The couthas a simple interface. If string represents a string variable, then the following statement will display its content. cout<< string; OOPS with C++ Sahaj Computer Solutions 14
Output Operator The operator << represents the bitwise left shift operator and is known as Insertion operator. Example: cout<< This is my first c++ program ; Will display the string This is my first c++ program on the standard output device (screen). C++ << This is my first c++ program Object Insertion Operator Variable OOPS with C++ Sahaj Computer Solutions 15
Return type of main() In C++ main() returns an integral type value to the operating system. Therefore every main() in C++ should end with a return(0) statement; otherwise the compiler will throw and warning. The default return type of main function is int. OOPS with C++ Sahaj Computer Solutions 16
Input Operator The statement cin>>number1; is an input statement and causes the program to wait for the users to type in a number. The number keyed is placed in the variable number1. The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assigns it to the variable to the right Object Extraction Operator Variable cin 45.5 >> OOPS with C++ Sahaj Computer Solutions 17
Basic Data Types C++ Data Types User Defined type Structure Union Class enumeration Built-in type Derived type Array Function Pointer reference Integral type void Floating type int char float double OOPS with C++ Sahaj Computer Solutions 18
Datatypes Type Bytes Range char 1-128 to 127 unsigned char 1 0 to 255 signed char 1-128 to 127 int 2-32768 to 32767 unsigned int 2-32768 to 32767 signed int 2 0 to 65535 short int 2-32768 to 32767 unsigned short int 2 0 to 65535 signed short int 4-32768 to 32767 long int 4-2147483648 to 21474836487 signed long int 4-2147483648 to 21474836487 float 4 0 to 4294967295 double 8 1.7E-38 to 1.7E+308 long double 8 3.4-4932 to 1.1E+4932 OOPS with C++ Sahaj Computer Solutions 19
Another C++ Program #include<iostream.h> intmain() { int number1,number2,sum; float average; cout<< Enter two numbers <<endl; cin>>number1>>number2; sum=number1+number; average=sum/2; cout<< Average: <<average; return(0); } OOPS with C++ Sahaj Computer Solutions 20
User defined Data Types Structures and Classes C has user defined data types such as structand union These data types are legal in C++ and some more new features have been added to make them suitable for the object orientation programming C++ permits another user-defined data type known as class which can be used, just like any other basic data type, to declare variables. The class variables are known as objects, which are central focus of object orientated programming OOPS with C++ Sahaj Computer Solutions 21
Enumerated Data Type An enumerated data type is another user-defined data type which provides a way for attaching names to numbers. In other words enumeration data type is used for creating symbolic constants. The enumkeywords automatically enumerates a list of words by assigning them values 0,1,2,3 and so on. Example: enum shape{circle,square,triangle}; enum color{red,blue, green,yellow}; OOPS with C++ Sahaj Computer Solutions 22
Enumerated data type In C++ the tag name shape, color becomes new type names. By using the tag names we can declare variables. Example: shape ellipse; //ellipse is of type shape By default enumerators are assigned integer vales starting with 0 for the first enumerator, 1 for the second enumerator and so on. We can override the default values by explicitly assigning integers to enumerators OOPS with C++ Sahaj Computer Solutions 23
Enumerated data type Example: enum color{red,blue=6,green=9}; enum color{red=5,blue,green} In the first case, red is 0 by default, blue is 6 and green is 9. OOPS with C++ Sahaj Computer Solutions 24
Example Program enum shape { circle, rectangle, triangle }; void main() { cout<< Enter shape code: ; int code; cin>> code; while(code>=circle && code<=triangle) { switch(code) case circle: cout<< Shape is Circle <<endl; break; case rectangle: cout<< Shape is Rectangle << endl; break; case triangle: cout<< Shape is Triangle <<endl; break; default: cout<< Invalid Code <<endl; break; } break; } OOPS with C++ Sahaj Computer Solutions 25
Declaration of Variables We know that in C, all the variable s must be declared before they are used. This is true with C++ as well. However there is a significant difference in C++ with regard to place of declaration in the program. C requires all the variables to be defined at the beginning of the program. Before using the variable we need to go the beginning of the program to see whether it has been declared and if so, of what type OOPS with C++ Sahaj Computer Solutions 26
Declaration of Variables C++ allows us to declare a variable anywhere in the scope. This means that the variable can be declared right at the place of its first use. This makes programs easier to write and reduces errors that may be caused by having to scan back and forth. It also makes program easier to understand because the variables are declared in the context of their first use. Program : ch2pg4.cpp OOPS with C++ Sahaj Computer Solutions 27
Reference Variables C++ introduces a new kind of variable known as the reference variable. A reference variable provides an alias (alternative name ) for the previously defined variable For example, if we make the variable sum a reference to the variable total then sum and total can be used interchangeably to represent that variable. A reference variable can be created as follows: data-type & reference-name = variable-name Examples float total=100; float & sum =total; OOPS with C++ Sahaj Computer Solutions 28
Reference Variables Both the variables now refer to the same data object in the memory. Now the statement cout<<total; And cout<<sum; Both prints the value 100. A reference variable must be initialized at the time of declaration. OOPS with C++ Sahaj Computer Solutions 29
Operators in C++ C++ Operators Unary Operators Binary Operators TernaryOperators Increment Op ++ Decrement Op -- Conditional Operator? : Arithmetic Operators Relational Operators Bitwise Operators Boolean Operators OOPS with C++ Sahaj Computer Solutions 30
Operators in C++ Arithmetic Operators Operator Operation Syntax Example + Addition Result=op1+op2 Sum=5+6 _ Subtraction Result=op1-op2 Diff=a-3 * Multiplication Result=op1*op2 Mul=5*2 / Division Result=op1/op2 Div=sum/2 % Modulo Division Result=op1%op2 Rem=n%2 Program ch2pg7.cpp OOPS with C++ Sahaj Computer Solutions 31
Relational Operators In the term relational operator, relational refers to the relationships that values can have with one another. Some of the C++ relational operators are Operator Operation Syntax Example < Less than Op1<Op2 If(9<2) result=9; > Greater than Op1>Op2 If(a>1) result= a is large <= Less than or equal Op1<=Op2 If(a<=b) result=b; >= Greater than or equal Op1>=Op2 If(z>=y) z++; == Equal Op1==Op2 If(num1==num2) s=0;!= Not equal Op1!=Op2 If(a!=b)cout<< not equal ; OOPS with C++ Sahaj Computer Solutions 32
Logical Operators Logical operator provides a way of connecting two or more expressions. Operators Actions Syntax && AND Expr1&& Expr2 OR Expr1 Expr2! NOT! Expr OOPS with C++ Sahaj Computer Solutions 33
Logical Operators TRUTH TABLE P Q P &&Q P Q!P 0 0 0 0 1 0 1 0 1 1 1 0 0 1 0 1 1 1 1 0 Program: ch2pg8.cpp OOPS with C++ Sahaj Computer Solutions 34
Bitwise Operators Bitwise operation refers to testing, setting, or shifting the actual bits in a byte or word, which correspond to the char andintdatatypes and variants. You cannot use bitwise operations on float, double, long double, void, bool, or other, more complex types. Bitwise operations are applied to the individual bits of the operands. OOPS with C++ Sahaj Computer Solutions 35
Bitwise Operators Operator Action & AND OR ^ Exclusive OR (XOR) ~ One s Compliment(NOT) << Right Shift >> Left Shift Program: ch2pg10.cpp OOPS with C++ Sahaj Computer Solutions 36
Bitwise Operators The bit-shift operators, >> and <<, move all bits in a variable to the right or left as specified. The general form of the shift-right statement is variable >> number of bit positions The general form of the shift-left statement is variable << number of bit positions As bits are shifted off one end, 0's are brought in the other end. Program: ch2pg9.cpp OOPS with C++ Sahaj Computer Solutions 37
Conditional Operator The ternary operator? takes the general form Exp1? Exp2 : Exp3; where Exp1, Exp2, and Exp3 are expressions. The? operator works like this: Exp1 is evaluated. If it is true, Exp2 is evaluated and becomes the value of the expression. If Exp1 is false, Exp3 is evaluated and its value becomes the value of the expression. For example, in x = 10; y = x>9? 100 : 200; y is assigned the value 100. OOPS with C++ Sahaj Computer Solutions 38
Increment and Decrement C++ includes two useful operators not generally found in other computer languages. These are the increment and decrement operators, ++ and. The operator ++ adds 1 to its operand, and subtracts one. In other words: x = x+1; is the same as ++x; And x = x-1; is the same as x--; OOPS with C++ Sahaj Computer Solutions 39
Increment and Decrement Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand. For example, x = x+1; can be written or ++x; x++; Program : ch2pg11.cpp OOPS with C++ Sahaj Computer Solutions 40
Control Structures The general form of the if statement is if (expression) statement; else statement; Example: if(age<=18) cout<< Not Eligible to Vote else cout<< Eligible to Vote ; Program : CH2PG12.cpp OOPS with C++ Sahaj Computer Solutions 41
Control Structures Nested ifs : if inside another if is called nested if Syntax: if(expression) { } else if(expression2) statement1; else statement2 statement3; Program :CH2PG3.CPP OOPS with C++ Sahaj Computer Solutions 42
Switch Statement A switch statement is a multi branching statement where, based on a condition, the control is transferred to one of many possible points. Syntax: switch(expression) { case 1: action; case 2: action; : default: action; }; OOPS with C++ Sahaj Computer Solutions 43
Switch Statement There are three important things to know about the switch statement: Theswitchdiffersfromtheif inthatswitchcanonlytest for equality, whereas if can evaluate any type of relational or logical expression. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same. If character constants are used in the switch statement, they are automatically converted to integers. OOPS with C++ Sahaj Computer Solutions 44
Switch Case Example switch(i) { case 1: /* These cases have common */ case 2: /* statement sequences. */ case 3: flag = 0; break; case 4: flag = 1; case 5: error(flag); break; default: process(i); } OOPS with C++ Sahaj Computer Solutions 45
Iteration Statements In C/C++, and all other modern programming languages, iteration statements (also called loops) allow a set of instructions to be executed repeatedly until a certain condition is reached. This condition may be predefined (as in the for loop), or open-ended (as in the while and do-while loops). OOPS with C++ Sahaj Computer Solutions 46
The for Loop The general form of the for statement is: for(initialization; condition; increment) { statement; } Example: for(x=1; x <= 100; x++) cout<< x; Program : CH2PG14.CPP OOPS with C++ Sahaj Computer Solutions 47
The while Loop Its general form is while(condition) statement; where statementis either an empty statement, a single statement, or a block of statements. The conditionmay be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of code immediately following the loop. OOPS with C++ Sahaj Computer Solutions 48
The While Loop Example: while(ch!= 'A') ch = getchar(); return ch; Program: CH2PG15.CPP OOPS with C++ Sahaj Computer Solutions 49
The do-while Loop Unlike for and while loops, which test the loop condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop. This means that a do-while loop always executes at least once. The general form of the do-while loop is do{ statement; } while(condition); OOPS with C++ Sahaj Computer Solutions 50
The do-while Loop Example: do { scanf("%d", &num); } while(num > 100); Program: CH2PG16.cpp OOPS with C++ Sahaj Computer Solutions 51
Jump Statements C/C++ has four statements that perform an unconditional branch: return, goto, break, and continue. Of these, you may use return and gotoanywhere in your program. Youmay use the break and continue statements in conjunction with any of the loop statements. OOPS with C++ Sahaj Computer Solutions 52
The return Statement The return statement is used to return from a function. It is categorized as a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made. A return may or may not have a value associated with it. The general form of the return statement is return expression; OOPS with C++ Sahaj Computer Solutions 53
The gotostatement The general form of the gotostatement is goto label;... label: where label is any valid label either before or after goto. OOPS with C++ Sahaj Computer Solutions 54
The gotostatement For Example: x = 1; loop1: x++; if(x<100) goto loop1; OOPS with C++ Sahaj Computer Solutions 55
The break Statement The break statement has two uses. You can use it to terminate a case in the switch statement. You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. Program: CH2PG16.CPP OOPS with C++ Sahaj Computer Solutions 56
The continue Statement The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. Program: CH2PG17.CPP OOPS with C++ Sahaj Computer Solutions 57
Arrays An array is a collection of variables of the same type that are referred to through a common name. A specific element in an array is accessed by an index. The general form for declaring a array is Example: double balance[100]; type var_name[size]; Program : CH2PG18.cpp OOPS with C++ Sahaj Computer Solutions 58
Pointers Program: CH2PG19.cpp A pointer is a variable that holds a memory address. This address is the location of another object (typically another variable) in memory. For example, if one variable contains the address of another variable, the first variable is said to point to the second. The general form for declaring a pointer variable is type *name; where type is the base type of the pointer and may be any valid type. The name of the pointer variable is specified by name. OOPS with C++ Sahaj Computer Solutions 59
Const Qualifier The const modifier is used for creating symbolic constant in C++. Any value declared as const cannot be modified by the program in any way. In C++ we can use const in a constant expression such as const int size=10; char name[size]; As with long and short if we use the const modifier alone, it defaults to int. For example const size =10 ; means const int size=10; OOPS with C++ Sahaj Computer Solutions 60
Manipulators Manipulators are operators that are used to format the data display. The most commonly used manipulators are endland setw. The endl manipulator, when used in an output statement causes a line feed to be inserted. It has same effect as using the new line character \n. Example: cout<<endl; OOPS with C++ Sahaj Computer Solutions 61
Manipulator setw(w) : Set the field width to w. For example: cout<<setw(5)<<sum<<endl; setprecision() : Set the number of digits of precision. For example: cout<<setprecision(6)<<num; setfill(intch) : Set the fill character to ch. Example: cout<<setfill( * ); flush : Flush a stream. To access manipulators that take parameters (such as setw() ), you must include <iomanip> in your program. OOPS with C++ Sahaj Computer Solutions 62
Scope Resolution Operator C++ is also block structured language, this means blocks and scope can be used in constructing programs. A scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside that block is said to be local to that block. Consider the following example: OOPS with C++ Sahaj Computer Solutions 63
Scope Resolution :::::::::::::::::::::::: { int x=100; ::::::::::::::::::::::::::: } :::::::::::::::::::::: { int x=1; :::::::::::::::::::::::::::::; } The two declarations of x refers to 2 different memory locations containing different values. Statements in second block cannot refer to the variable x declared in first block and vice versa. Blocks in C++ are often nested. OOPS with C++ Sahaj Computer Solutions 64
Scope Resolution ::::::::::::::::::::: {// Block 1 int x=10; :::::::::::::::::::: { //Block 2 int x=1; :::::::::::: } :::::::::::::::::::::::::::::: } Block2 is contained in block1. The declaration in inner block hides a declaration of the same variable in an outer block and therefore each declaration of x causes it to refer to a different data object. OOPS with C++ Sahaj Computer Solutions 65
Scope Resolution Operator The global version of variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator :: called scope resolution operator. This can be used to uncover a hidden variable. It takes the following form: :: variable-name; For Example: cout<<::m Program: CH2PG21.cpp OOPS with C++ Sahaj Computer Solutions 66
Memory Management Operators C++ has two unary operators new and delete that perform the task of allocating and freeing the memory better and easier way. The new operator can be used to create objects of any type. It takes the following general form: pointer-variable =new data-type; When the data is no longer needed, it is destroyed to release the memory space for reuse. The general form of its use is: delete pointer-variable; OOPS with C++ Sahaj Computer Solutions 67
SahajComputer Solutions Near Gomatesh School, Hindwadi Belgaum-11, Phone no: 4200864,2481703 Get Certified in Microsoft Office 2010 Tally 9.2.NET 2008 J2EE CORE JAVA C PROGRAMMING OOPS WITH C++ JOOMLA WORDPRESS PHP AND MYSQL SQLSERVER UNIX AND LINUX ANDRIOD APPS Around 1800 students developed software projects and scored the top scores in exams. One stop shop for Software Projects Website Development Technology Training I.T Research Visit: www.sahajsolns.com OOPS with C++ Sahaj Computer Solutions 68