PRESENTATION OF C++ BY KAMRUL AHMED Introduction to C++ Programming in C++ c.f. C and Java Programming language features Classes, constructors/destructors, virtual functions Single and multiple inheritance Operator overloading Templates and the standard library Runtime type identification and cast operators Exceptions Programming style and idioms You Should Know C Programming Basic language features. Control flow, variables, functions, defining and using types, pointers, malloc and free, casts. Java programming and O.O. design Basic language features Exceptions inheritance / interfaces / abstract classes Design Patterns (the Gang of Four book) The C++ Language Based on C Programming style is completely different Stricter than C, less strict than Java Large and complicated language Many warts and subtle gotchas Popular compilers incompatible (at best) or full of bugs (at worst). Most likely to find both! C lets you shoot yourself in the foot. C++ makes it harder, but when you do, you lose your whole leg Lesson On Programming I (C++) C++ is a high level language. But it is not hard to learn. Its a friendly language. C++ has function or classes. Class is more complicated than function.. One important thing for designing a function or class to give a name of it so that the Readers can easily understand what the function or class is going to do. Its called Identifiers . Identifiers can be combination of letters ,digits, underscores( _ ) selected According to the rule stated below. 2: RULES OF INDENTIFIERS . Identifiers can be combination of letters ,digits, underscores( _ ) selected According to the rule stated below:. 1) The first character of the name must be a letter or underscore( _ ) 2) Only letters , digits , underscores may follow the initial letter. Blank space is not allowed. 3) A function name cannot be one of the keywords listed below, because C++ Language Use that words for a special purposes. These words are as follows: Default, continue, break, auto, case, catch, char, class, const, int, delete, do, double, else, enum, extern , float, for, friend, goto, if , inline, new, overload, private, protected, public, Register, return, sizeof, static, struct, switch, template, this, typedef, this, union, unsigned, Virtual, void, volatile, while. EXERCIZE:1 Which of the following is key word. a) continue b) auto c)number d) new e) sum f) total g) float h)friend i) item j) switch k) this l) void m) element n) people o) student p) static q ) while Example of some valid C++ identifiers Number1, MultNum, Max etc. Example of some Invalid Identifiers: 6 lab Begins with a number which violate the rule. H*5 Contains special character which violates rule 2. Do is a key word for C++ EXERCIZE: 2 From the variable name state below which is the valid variable name. 1) sum 2) b145 3)$total 4) 4bd 5) while 6) old val 7) sin_o 8) p*9 8) average 9) _num1 10) new 11) sizeof 12) item 13) 56584 14) for 3: C++ FUNCTION NAME CONVENTION: C++ function name always be followed by parenthesis and also a good function name should be mnemonic . So that people can understand what you wanted to do with Function . Here is some valid function name : Findmax() , AddNum() Notes:: C++ is a case -sensitive language.For example if your write Addition and another place You write addition , compiler will give you an error. Because first time it was upper case (Addition) and next time it was Lower case (addition). The Main FUNCTION( ) The C++ language must have one and only one functions its called main function. The main function is called driver function, because its tell other function to be execute. int main() { return 0; } The braces determine the beginning and end of the function body. int main () means this function always return the integer value. If we write void main() { } Then we dont have to return any thing. Note: The statement inside the function determine what the function does. Each statement Inside the braces must ended up with semicolon(;). The cout Object The most commonly used object in C++ is named cout .(Pronounced see out) If the data Hi there! is passed to cout, this data is printed on your terminal screen. You need pass the cout object by simply putting the insertion symbol ,<<, before the message and after the cout object. #include / Is a preprocessor command ,begin with a pound sign (#) before the compiler translate the source program into machine code. int main() { cout < / Is a preprocessor command ,begin with a pound sign (#) before the compiler translate the source program into machine code. int main() { cout < int main() { cout<< hello every body;// This is a call to cout. return 0; } We can also write the program this way too. /* This is called block comment that spans across three lines.*/ 4: DATA VALUES AND ARITHMETIC OPERATIONS IN C++ C++ has different data types .The three data types C++ language mostly use are integers, Floating-point numbers, and character values. Integer Values: An integers value is zero or any positive or negative number without a decimal point There are some valid integers data type. 0 -2 , 3,-5 +8 Floating-Point Numbers: A floating point number, is any signed or unsigned number having a decimal point . Floating point number is also called a real number. Example of Floating point: 1.25, -6.2, 0.0, 0.23, +2. Character Values: A single character value is any one letter, digit, or special symbol enclosed by single quotes. These is some valid character values : N $ b ! 5: ARITHMETIC OPERATIONS Integers and real numbers can be added, subtracted, multiplied and divided . Although it is usually not to mix integer and real numbers when performing arithmetic Operations . Some time you may get unwanted result if u dont want same arithmetic expression. The operators used for arithmetic operations are called arithmetic operations and Are stated below: Operation Operator Addition + Subtraction - Multiplication * Division / Modulus division % Note: A simple arithmetic expression consists of an arithmetic operator connecting two operands The following forms: Operand operator operand Example of arithmetic expression are: 5+4 8-4 2.5+5.2 5*8 12/3 The value of any arithmetic expression can be displayed on the standard output device using cout . For example: If we want to display the result of 12/3; which is 3. we have to write it cout<<(12/3); The parenthesis surrounding the expression 12/3 are required to indicate that it is the value of the expression , which is 3, that is being placed on the out put stream. Precision: Precision typically refers to numerical accuracy . For example, if the number 11.4587 has been rounded to the 4th decimal place, it is correct to say that this number is precise (that is accurate) to the 4th decimal place. This statement means that all of the digits in the number are accurate except for the fourth digit, which has been rounded. The following program will display the results of an expression within the statements of an expression within the statements of a complete program. PROGRAM: #include int main( ) { cout<<" 12 plus 12 is "<<(12+12)< int main( ) { declaration statements; other statements; } Program 3: #include int main( ) { float number1; // declare number1 as float variable float number2; // declare number2 as float variable float total; // declare total as float variable. float average; //declare average as float variable number1=25.5; // initialize number1 with the value 25.5 number2=25.5; // initialize number2 with the value 25.5 total= number1+number2; average=total/2.00; // divide the total by 2.00 cout<<" The average of the two number is: " < int main( ) { char ch; // this declares a character variable ch='k'; //store a letter k into character variable ch. cout<<" The character stored in ch is :"< int main( ) { int value; value= 30; cout<< The contents store in the variable value is:<; 7) Incorrectly typing the letter O for the number zero(0) or vice versa 8) Forgetting to declare all the variables used in a program. This error is detected by the compiler and the assigned value is converted to the data type of the variable to which it is assingned. 10:ASSIGNMENT OPERATORS In C++ statements for assigning values to a variable and computes the result. The statement has the syntax as follows: Variable = expression. For example length= 10.2; Number=20.5; In this statement above meant that value 10.2 is assigned to variable length. In each of these assignment statements , the value of the constant to the right of the equal sign is assigned to the variable on the left of the equal sign. It is really understand able things to know that the equal sign (= ) in C++ does not have the same meaning as an equal sign in Algebra. In algebra value never changed but in C++ statement value can be frequently change. For example Total=25; Total=30; Here you noticed that first the value of Total was 25 after that its changed into 30. Because it happened first time value of Total was 25 , when we assigned new value 25 to it Then 25 was overwritten with value 30. This program stated in below will clarify you to understand the assignment operator. // This program will help you to understand the concept of assignment operator. PROGRAM: #include int main( ) { int number; number= 30; cout<<" The number you have written is :"< int main( ) { int number; number=0; // Assigning zero to variable number . cout<<"The initial value number is :"< int main( ) { cout<<5< 12: MATHEMATICAL LIBRARY FUNCTION IN C++ How to calculate square of a function. Or how could we calculate the square of a function. We are able to do that using C++ Mathematical library function . The argument to the sqrt function can be either an integer or real value. This is an example of C++ function overloading capabilities. Function overloading permits the same function name to be defined for different argument data types. The sqrt( ) function determines the square root of its argument and re-given it. Expression Value Returned ___________________________________ sqrt(4) 2.0 sqrt (16) 4.0 sqrt(6.45) 2.56 To access these functions in a program requires that the mathematical header file named math.h , which contains appropriate declarations for the mathematical header math.h contains appropriate declarations for the mathematical function, be included with the function. This done by the following preprocessor statement at the top of any program using a mathematical function : #include // no semicolon How the cin object works The cin object , which is used to enter a data while the program is executing. The cout object enter displays a copy of the value inside the variable. Cin object allows the users to enter the value at the terminal, which then Stored directly inside the variable. I am writing a short program it will show How the cin object works. PROGRAM #include int main( ) { int number1, number2, number3; int sum; cout<<"Enter three numbers: "; cin>>number1,number2, number3; sum= number1+number2+ number3; cout<<" The total of three numbers is :"< #include const float SALESTAX=0.05; int main( ) { float purchased_amount, taxes, totalBill; cout<<" Enter the amount you have purchased: "<>purchased_amount; // calculation of taxes and total bill taxes= SALESTAX*purchased_amount; totalBill=taxes+purchased_amount; //set the out put format cout< Greater than sum>90 >= Greater than or Equal to grade>=90 A relational expression that we would interpret as true evaluates to an integer value of 1, And a relational expression which evaluates to an integer value of 0 is false. For example, 4<5 is always true because it has an integer value of 1, 4>5 Is always false ,because it has an integer value of 0 which always evaluates false. Note: In C++ a zero value is always evaluates false condition, any nonzero value is Evaluates as true condition. AND,OR, NOT operators are called logical operators. These operators are represented by the symbols &&, || and !, respectively. When the AND operator, &&, is used with two simple expressions, the condition is true only if both individual expression are true . Mean that the both condition should be true. Here is a compound statement showing the AND operator. (grade>89 )&& (semester <3) is a true condition because both condition is evaluated a true condition . On the other hand ,for the logical OR (|| ) operators , the condition is satisfied if either one of the Two expression is true. Thus the compound condition (mile<40 || age>50) will be true if the mile is less than 40 or age is greater than 50 . In if-else statement , the if statement will be evaluated first, If the if statement is not True it will executed the else statement. Here is a form of if-else statement: if (expression) // no semicolon statement1; else statement2; Here is the program about if statement: #include int main( ) { char month; cout<<"Enter your month code:"; cin>>day; if (month= = 'J') cout<<"The month is January." int main( ) { int speed, distance; if (speed>75) if (distance<500) cout<<"You will reach there in time."<> in front of the instance of the class as if it were cout or cin. For example: #include #include int main() { char str[10]; //Used later ofstream a_file("example.txt"); //Creates an instance of ofstream, and opens example.txt a_file<<"This text will now be inside of example.txt"; //Outputs to example.txt through a_file a_file.close(); //Closes up the file ifstream b_file("example.txt"); //Opens for reading the file b_file>>str; //Reads one string from the file cout< #include int main() { int input; cout<<"1. Play game"; cout<<"2. Load game"; cout<<"3. Play multiplayer"; cout<<"4. Exit"; cin>>input; switch (input) { case 1: playgame(); break; case 2: loadgame(); break; case 3: //Note use of : not ; playmultiplayer(); break; case 4: return 0; default: cout<<"Error, bad input, quitting"; } return 0; } This program will not compile yet, but it serves as a model (albeit simple) for processing input. If you do not understand this then try mentally putting in if statements for the case statements. Note that using return in the middle of main will automatically end the program. Default simply skips out of the switch case construction and allows the program to terminate naturally. If you do not like that, then you can make a loop around the whole thing to have it wait for valid input. I know that some functions were not prototyped. You could easily make a few small functions if you wish to test the code. 17: Functions in C++ Now that you should have learned about variables, loops, and if statements it is time to learn about functions. You should have an idea of their uses. Cout is an example of a function. In general, functions perform a number of pre-defined commands to accomplish something productive. Functions that a programmer writes will generally require a prototype. Just like an blueprint, the prototype tells the compiler what the function will return, what the function will be called, as well as what arguments the function can be passed. When I say that the function returns a value, I mean that the function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four. For example: int a; a=random(5); //random is sometimes defined by the compiler //Yes, it returns between 0 and the argument minus 1 Do not think that 'a' will change at random, it will be set to the value returned when the function is called, but it will not change again. The general format for a prototype is simple: return-type function_name(arg_type arg); There can be more than one argument passed to a function, and it does not have to return a value. Lets look at a function prototype: int mult(int x, int y); This prototype specifies that the function mult will accept two arguments, both integers, and that it will return an integer. Do not forget the trailing semi-colon. Without it, the compiler will probably think that you are trying to write the actual definition of the function. When the programmer actually defines the function, it will begin with the prototype, minus the semi-colon. Then there should always be a bracket (remember, functions require brackets around them) followed by code, just as you would write it for the main function. Finally, end it all with a cherry and a bracket. Okay, maybe not a cherry. Lets look at an example program: #include int mult(int x, int y); int main() { int x, y; cout<<"Please input two numbers to be multiplied: "; cin>>x>>y; cout<<"The product of your two numbers is "< void CompareNum(int, int);// function protype int main( ) { int number1, number2; cout<>number1; cout<>number2; CompareNum(number1,number2); // The function is called here // number1 and number2 is called // actual parameter return 0; } // The following is the definition CompareNum( ) void CompareNum(int m, int n )// m and n is called formal parameter { // start of function body here int largest; if( m>=n) // find the largest number largest=m; else largest=n; cout< void AdditionNum(int x, int y) //function prototype here void main( ) { int firstNum, SecondNum; cout<>firstNum; cout<>secondNum; AdditionNum( firstNum, SecNum); // function call here // actuall firstNum and SecNum return ; } //Here is the function definition of AdditionNum void AdditionNum( int x, int y) { int sum; sum=x+y; cout< int main() { int x, y, anarray[8][8];//declares an array like a chessboard for(x=0; x<8; x++) { for(y=0; y<8; y++) { anarray[x][y]=0;//sets the element to zero; after the loop all elements == 0 } } for(x=0; x<8;x++) { for(y=0; y<8; y++) { cout<<"anarray["< const int MAXNUMBERS=6; int main( ) { int i, number[MAXNUMBERS]; for(i=1;i<=MAXNUMBERS; i++) //Enter the numbers { cout<>number[i]; } cout< const int MAXNUMBERS=6; int main( ) { int i, number[MAXNUMBERS]; int sum=0; for(i=1;i<=MAXNUMBERS; i++) //Enter the numbers { cout<>number[i]; } cout<