151
PRESENTATION OF C++ BY KAMRUL AHMED • WELCOME TO MY ONLINE TUTORIAL • HOPE YOU ENJOY IT

PRESENTATION OF C++ BY KAMRUL AHMED WELCOME TO MY ONLINE TUTORIAL HOPE YOU ENJOY IT

Embed Size (px)

Citation preview

PRESENTATION OF C++ BY KAMRUL AHMED

• WELCOME TO MY ONLINE TUTORIAL

• HOPE YOU ENJOY IT

What is 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”

1: INTRODUCTION

• 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:.

• The first character of the name must be a letter or underscore( _ )

• Only letters , digits , underscores may follow the initial letter. Blank space is not allowed.

• A function name cannot be one of the keywords listed below, because C++ Language

2: RULES OF INDENTIFIERS

• 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.

EXERCISE:1

• Which of the following is key word.• • 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.

EXERCISE:1

• 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.

• 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.

CONTINUED

• 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 don’t have to return any thing.

CONTINUED

• 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.

CONTINUED

• #include<iostream.h> / Is a preprocessor command ,begin with a pound sign (#) before the compiler translate the source program into machine code.

• int main()• { cout <<”Hi there”;• • return 0;• }• Output: Hi there

Example2:

• #include<iostream.h> / Is a preprocessor command ,begin with a pound sign (#) before the compiler translate the source program into machine code.

• int main()• { cout <<”The world is so beautiful”;• cout<<” \n I love this world”;• return 0;• }

CONTINUED

• If we run this program the following will be the Out Put.• The world is so beautiful • I love this world.• You could be wondering where the characters \ and n,

disappeared . When we used together,• are called new line escape sequence.• Its tell the program to execute in the next line. Otherwise

the output will be• The world is so beautiful I love this world.

Comments:

• Comments is really important for the program so that another person can understands

• your program. Its always nice to have comments in programs. Comments make the

• program to readable to another person. A line comment begin with two slashes(//) and

• continues to the end of the line .

CONTINUED

• For example:

• The following lines are all line comments.

• // This program calculates the sum of some integers

• //This program prints out a message.

• This a sample program with comments.

CONTINUED

• #include<iostream.h>• 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.

CONTINUED

• 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.

CONTINUED

• 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 don’t want same arithmetic

• expression.

CONTINUED

• 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

CONTINUED

• 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<iostream.h>• int main( )• {• cout<<" 12 plus 12 is "<<(12+12)<<endl• <<" 12 minus 10 is "<<(12-10)<<endl• <<" 12 divide 3 is "<<(12/3)<<endl• <<" 12 times 3 is "<<(12*3)<<endl;• return 0;• }•

CONTINUED

• OUTPUT:

• plus 12 is 24

• minus 10 is 2

• divide 3 is 4

• 12 times 3 is 36.

6:EXPRESSION TYPES AND A UNARY OPERATOR(NEGATION)

• An expression that contains only integer operands is called an integer expression,

• And the result of the expression is an integer value. Similarly , an expression containing only

• Floating -point expression, and the result of such an expression is a floating -point value.

• An expression containing both integer and floating -point operands is called a mixed-mode expression.

NOTES

• Its better not to mix integer and floating point operands together in an arithmetic

• Operation.• There is some conventions:• 1.If both operands are integers, the results of the operation is an integer.• 2.If one operand is a floating -point value, the result of the operation is a

double -precision value.• Besides the binary operators for addition, subtraction, multiplication and

division, C++• Also provides unary operators. That’ is the same symbol that is used for binary

subtractions( - ).• The minus sign in front of a single numerical operand negates (reverse the sign)

the number.

7 :OPERATOR PRECEDENCE AND ASSOCIATIVITY

• If you want to write complex arithmetic expression , you are required to follow some certain

• Rules . The rules are as follows:• 1)Two binary arithmetic operator symbols never be placed side

by side.• For example ,2+-3 is invalid because the

two operators - and + • Are placed next to each other.• 2) Parenthesis should be used to form grouping, and all

expressions enclosed within parenthesis are evaluated first. For example , in the expression(20+1)/ (6+1), the 20+1 and 6+1 are evaluated first to yield 21/7. The 21/7 is then evaluated to yield 3.

Cont

• 3) Sets of parentheses may also be enclosed by other parentheses .• For example, the expression (3*(5+2))/ 3 is valid. When the parentheses are

used within the parentheses the inner most parenthesis are always evaluated first. The evaluation continues from

• Innermost to outermost parentheses until the expressions of all parentheses have been evaluated.

• 4) Parentheses cannot be used to indicate multiplication . The multiplication operator ' * ' must be used to indicate multiplication. For example (2+5) (6+3) is a invalid, because we did not use

• any multiplication operation between the parentheses . The valid expression is (2+5)*(6+3).

Declaration Statements

• In order to use a variable u must declare it other wise, C++ will give a syntax error.

• A declaration statement has the general form:• Data -type variable name;• Thus the declaration statement • Int total;• declares total as the name of a variable capable of storing an integer value.• Such as we can declare • long int sum;• float value;• double secnum;

Cont

• Declaration may happen any where in the function body but condition is u cannot use

• A variable without declaring it.• If the declaration statements are placed after the opening function brace, a

simple main( ) function containing declaration statements would have the following general form:

• #include<iostream.h>• int main( )• {• declaration statements;• • other statements;• }

Cont

• Program 3:• • #include<iostream.h>• 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•

Cont.

• total= number1+number2;• • average=total/2.00; // divide the total by 2.00• cout<<" The average of the two number is: "

<<average<<endl;• • return 0;• }• OUTPUT:• The average of the two number is : 25.5

Cont.

• Program 4:• • #include<iostream.h>• • int main( )• {• • char ch; // this declares a character variable• ch='k'; //store a letter k into character variable ch.•

Cont.

• cout<<" The character stored in ch is :"<<ch<<endl;• ch='A'; // now store the letter A into ch• • cout<<" The character presently stored in ch

is :"<<ch<<endl;• }• OUT PUT: • The character stored in ch is : k• The character presently stored in ch is : A

8: HOW TO DISPLAY A VARIABLE’S ADDRESS

• Every variable has three major parts associates with its data type , the actual value stored in the variable and the address of the variable . The value store in the variable is called its

• Content and where the value store in is called address of the variable

Cont.

• Here is a Program:• #include< iostream.h>• int main( )• {• int value;• • value= 30;• cout<<” The contents store in the variable value

is:<<value<<endl;• return 0;• }

Cont.

• OUT PUT:• The contents store in the variable value is : 30• The program display in the above program is 30, which

is the content of the variable value.• • Now the variable value has its own address. This is

the physical address of the variable • value. The program stated below is showing the

address of the value.•

Cont.

• int main( )• {• int value;• • value= 22;• cout<<” The contents store in the variable value

is:<<value<<endl;• cout<<” The address of value is: “<< &value<<endl;• return 0;• }

Cont.

• Out Put:

• The contents store in the variable value is : 22

• The address of value is :0x8f5afff4.

• The address is so long , that’s why it has been expressed in hex number. Usually the address is always in binary number.

Cont.

• Determining Storage size:• C++ provides an operation to determine the amount of storage

your compiler allocates for• each data type. This operator is called sizeof( ) , which determine

how many bytes are determined by each data type.• The sizeof () operator itself is used as an argument to the cout

object.• Char data type uses 1 byte for storage area and integer data type

store 2 byte as storage • area.

9 :HERE IS SOME COMMON PRORAMMIN ERROR IN C ++

– Forgetting to close string sent to cout with a double quote symbol.

• For example instead of cout<< , your wrote cout<• Same thing happened for the cin statement.• 2)Forgot to give brace after main.• 3)Omitting or incorrectly typing the opening and closing braces.• 4)Misspelling the name of function , or variable.• For example, variable name Number , your

wrote it • somewhere number,• It was upper case for N , now u wrote lower

case.•

Cont.

• 5)Omitting semicolon at the end of each C++ statement.• 6)Adding a semicolon at the end of the

#include preprocessor command.• • For example #include<iostream.h>; •

– Incorrectly typing the letter O for the number zero(0) or vice versa– 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;

Cont.

• 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.

Cont.

• 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.

Cont.

• 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<iostream.h>• int main( )• {• int number;• number= 30;• cout<<" The number you have written is :"<<number<<endl;• number=35;

Cont.

• cout<<" The new number you have written is :"<<number<<endl;

• return 0;

• }

• Out Put:

• The number you have written is : 30

• The new number you have written is : 35.

Cont.

• ANALYSIS:• First the variable number has the value 30 as soon as we

assigned new value 35 in variable• number its overwritten with previous value.• If u assign any new value to same variable it will forget

its old value and contains the • latest value • COUNTING• An assignment statement is very similar to the

accumulating statement is the counting statement.

Cont.

• Examples of counting statements are:• j= j=1;• n=n+1;• p= p+1;• Expression Alternative• p=p+1; p++ or ++p• n= n+1 ++n or n++• count= count+1; ++count or count++

Cont.

• PROGRAM:• #include<iostream.h>• int main( )• {• int number;• number=0; // Assigning zero to variable number .• cout<<"The initial value number is :"<<number<<endl;• number++; // increasing the number by one.• cout<<"Now the value of number is:"<<number<<endl;• number ++;

Cont.

• cout<<"Now the value of number is:"<<number<<endl;• number++;• cout<<"Now the value of number is:"<<number<<endl;• number++;• cout<<"Now the value of number is:"<<number<<endl;• number++;• cout<<"Now the value of number is:"<<number<<endl;• return 0;• }

Cont.

• OUTPUT:• The initial value of number is : 0• • Now the value of number is :1• Now the value of number is :2• Now the value of number is :3• Now the value of number is :4• Now the value of number is :5

11: FORMATING NUMBERS

• We want to display our program correctly besides that we need to display our program

• attractively so that another person can evaluate your program nicely . For example , displaying

• a monetary result as 1.5989400 is not in keeping with accepted reporting conventions. The display should be either $1.59 or $ 1.60 depending on whether rounding or truncation is used.

Cont.

• Commonly Used Stream Manipulators• Manipulator Action• • • Setw(n) Set the field width to n• • setprecision(n) Set the floating point

precision to n places.• setiosflag(flags) Set the format flags.• dec Set out for decimal display.

• hex Set output for hexadecimal

display.• oct Set output for octal display.

Cont.

• Field width manipulators are useful in printing columns of numbers that

• Are correctly aligned . Here is a program without field width . Here is a program

Cont.

• PROGRAM• #include<iostream.h>• • int main( )• {• cout<<5<<endl• <<6<<endl • << 100<<endl• • <<"-------"<<endl• <<(5+6+100)<<endl;• • return 0;• }

Cont.

• Out put:• 5• 6• 100• -------• 111.• Since no field width manipulators are given , the cout object

allocates enough space for each number as it is received . To force the numbers to align on the units digit, we need to set a field width wide enough for the largest displayed number.

Cont.

• The same program with the field width.• int main( )• {• cout<< setw(3)<< 5<<endl• << setw(3)<< 6<<endl

• << setw<<3<< 100<<endl• • <<"-------"<<endl• <<(5+6+100)<<endl;• • return 0;• }

Cont.

• The new out put of the program is different from the previous one.

• OUTPUT :• Out put:• 5• 6• 100• -------• 111•

Cont.

• As we assigned the set field so the field width manipulator must be included for each occurrence of a number inserted onto the data stream sent to cout Also notice that if

• Manipulators are to be included within an output display , the iomanip.h header file must

• Be included as part of the program . This is done by the preprocessor command #include

• <iomanip.h>

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.

Cont.

– Expression Value Returned

– ___________________________________

– sqrt(4) 2.0

– sqrt (16) 4.0

– sqrt(6.45) 2.56

Cont.

• 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<math.h> // 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.

Cont.

• PROGRAM• #include<iostream.h>• 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 :"<<sum<<endl;• return 0;• }

Cont.

• Out Put

• Enter three numbers: 11 12 13

• The total of three numbers is: 36

Analysis:

• Cin object called a prompt. Our case prompt tells the used to type a number.• The Computer then executes the next statement , which is a call to cin. The cin

object• Puts the computer into a temporary wait state for as long as it takes the

user• To type a value. Then the user signals the cin object that the data entry is

finished• By pressing the return key after the value has been typed. • In our program we entered three integers number as cin , cin object stored

these three• • numbers into number1 , number2, number3 as well.

The constant Qualifier

• Some data is always constant , never will change is called const . For example

• Sales Tax, PI is always fixed. So if we declare the constant at the top

• Of the program we don’t have to write it again and again. If we try to write it again

• and again there could occur some error. That's why its better to write at the top

• of the program so that we can use it for the whole program.

Cont.

• Here is a program which will use the const variable.• #include<iostream.h>• #include<iomanip.h>• • const float SALESTAX=0.05;• • int main( )• {• float purchased_amount, taxes, totalBill;• cout<<" Enter the amount you have

purchased: "<<endl;• cin>>purchased_amount;

Cont.

• // calculation of taxes and total bill• taxes=

SALESTAX*purchased_amount;• totalBill=taxes+purchased_amount;

• • //set the out put format• cout<<setiosflags(ios::fixed)<<

setiosflags(ios::showpoint)• <<setprecision(2);

Cont.

• cout<<"The sales taxes is : "<<setw(4)<<taxes<<endl;• • cout<<"The total bill

for the amount you havepurchased:"•

<<setw(5)<<purchased_amount<<endl;• return 0;• }

Cont.

• Out put:• • Enter the amount you have purchased:36.00• The sales tax is :1.80• The total bill for the amount you have

purchased:37.80• • In above program we used const as Sales Tax , because its

always same so we declared it• top of the program and we can access it for the whole program.

13:IF -ELSE STATEMENT IN C++ AND THE LOGICAL

OPERATORS• The if-else statement in C++ is used to compare two

choices. Most commonly used psuedocode syntax is as follows:

• if (condition)• statement will execute if the

condition is "True"• else • • statement will execute if the

condition is "False"

Cont.

• When an executing program evaluates the if statement it evaluate as numerical value,

• if the value is positive or positive nonzero numerical value, the condition is treated as

• a "true" condition and the if statement will be executed. If the numerical value evaluated as

• " zero" then the if statement must be false condition. If the if statement evaluated as false

• the it will executed the else statement. •

Cont.

• The most commonly used expressions are called relational expression.

• Relational expression are sometimes know as conditionals or conditions . In relational expression the value of the expression can only be integer value of 1 or 0, which is interpreted

• as true or false respectively.

Cont.

• This is a table for Relational Operators• Operator Meaning Example• • == Equal to number = =52• != Not equal to total !=30• < Less than month <5• <= Less than or Equal to age<= 30• > Greater than sum>90• >= Greater than or Equal to grade>=90

Cont.

• 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.

Cont.

• 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.

Cont.

• 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;

Cont.

• Here is the program about if statement:• • #include<iostream.h>• int main( )• {• char month;• cout<<"Enter your month code:";• cin>>day;• if (month= = 'J')• cout<<"The month is January."<endl;• else if (month= = 'F')• cout<<"The month is February."<endl;• else if (month= = 'M')

Cont.

• cout<<"The month is March."<endl;• else if (month= = 'A')• cout<<"The month is

January."<endl;• else if (month= = 'm')• cout<<"The month is

May."<endl;• else if (month= = 'j')• cout<<"The month is

June."<endl;

Cont.

• else if (month= = 'J')• cout<<"The month is

January."<endl;• • else • cout<< "Invalid month code."<<endl;• • return 0;• }

Cont.

• out put: Enter your month code:M• The month is May.• Analysis: • When we enter the character M , it will

check all the possible condition,• As soon as it will find the character M it will print the

message ,The month is May.• If it did not satisfy any of those condition then it would

print the message.• Invalid month code.

Cont.

• Problem:• Solve the following program what will be the out put?• #include<iostream.h>• int main( )• { int speed, distance;• if (speed>75)• if (distance<500)

Cont.

• cout<<"You will reach there in time."<<endl;

• else

• cout<<"You will not reach there in time."<<endl;

• return 0;

• }

Cont.

• Find out the out put suppose speed=80 and distance 450.

• Which one is correct out?

• 1.You will reach there in time.

• 2.You will not reach there in time.

14: THE REPETITION STRUCTURE

• What happened if we start adding some numbers 1 through 1000.

• It might take more time to calculate it and wasting of memory space. We can also easily

• Do it by using loop. More commonly repetition structure is known as loop.

Cont.

• Constructing a repetitive section of code requires that four elements present. The first necessary element is a repetition statement. This repetition statement defines the boundaries containing the repeating section of code and also controls whether the code will be executed

• Or not. • The three different forms for the repetition

structures.• while structure• do-while structure• for structure

Cont.

• In C++ language , while loop is constructed using a while statements. The syntax of this statement is:

• While(expression)• Statement;• Considering just the expression and the statement

following the parentheses, the process used by the computer in evaluating a while statement is:

Cont.

• 1: Test the expression• 2: If the expression has a nonzero(true) value.• execute the statement following the parentheses.• Go back to step 1.• Else• Exit the while statement and execute the next• Executable statement following the while statement

15: C++ File I/O

• This is a slightly more advanced topic than what I have covered so far, but I think that it is useful. File I/O is reading from and writing to files. This lesson will only cover text files, that is, files that are composed only of ASCII text.

C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream.h. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files). The way to declare an instance of the ifstream or ofstream class is:

Cont.

• ifstream a_file;//orifstream a_file("filename");

The constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). It is generally a good idea to clean up after yourself and close files once you are finished.

Cont.

• The beauty of the C++ method of handling files rests in the simplicity of the actual functions used in basic input and output operations. Because C++ supports overloading operators, it is possible to use << and >> in front of the instance of the class as if it were cout or cin.

Cont.

• For example:

• #include <fstream.h>#include <iostream.h>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

Cont.

• 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<<str; //Should output 'this' b_file.close(); //Do not forget this! }

Cont.

• The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it. If necessary, you can give a second argument that specifies how the file should be handled. They are listed below:

ios::app -- Opens the file, and allows additions at the endios::ate -- Opens the file, but allows additions anywhereios::trunc -- Deletes everything in the file

Cont.

• ios::nocreate -- Does not open if the file must be createdios::noreplace -- Does not open if the file already exists

For example: • ofstream a_file("test.txt", ios::nocreate); The above code

will only open the file test.txt if that file already exists.

16: switch case

• Switch case statements are a substitute for long if statements. The basic format for using switch case is outlined below.

• Switch (expression or variable) { case variable equals this: do this;

break; case variable equals this: do this;

Cont.

• break; case variable equals this: do this; break; ... default: do this }

Cont.

• The expression or variable has a value. The case says that if it has the value of whatever is after that cases then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from testing the next case statement also.

Switch case serves as a simple way to write long if statements. Often it can be used to process input from a user.

Cont.

• Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.

• #include <iostream.h> #include <conio.h>int main(){ int input;

Cont.

• 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;

Cont.

• case 3: //Note use of : not ; playmultiplayer(); break; case 4: return 0; default: cout<<"Error, bad input, quitting"; } return 0;}

Cont.

• 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.

Cont.

• 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.

Cont.

• 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 functionis called, but it will not change again.

Cont.

• 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);

Cont.

• 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.

Cont.

• Lets look at an example program:

• #include <iostream.h>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 "<<mult(x, y); return 0;}

Cont.

• int mult(int x, int y){ return x*y;}This program begins with the only necessary include file. It is followed by the prototye of the function. Notice that it has the final semi-colon! The main function is an integer, which you should always have, to conform to the standard. You should not have trouble understanding the input and output functions. It is fine to use cin to input to variables as the program does.

Cont.

• Notice how cout actually outputs what appears to be the mult function. What is really happening is that mult acts as a variable. Because it returns a value it is possible for the cout function to output the return value.

The mult function is actually defined below main. Due to its prototype being above main, the compiler still recognizes it as being defined, and so the compiler will not give an error about mult being undefined, although the definition is below where it is used.

Cont.

• Return is the keyword used to force the function to return a value. Note that it is possible to have a function that returns no value. In that case, the prototype would have a return type of void.

The most important functional (Pun semi-intended) question is why. Functions have many uses. For example, a programmer may have a block of code that he has repeated forty times throughout the program. A function to execute that code would save a great deal of space, and it would also make the program more readable.

Cont.

• Another reason for functions is to break down a complex program into something manageable. For example, take a menu program that runs complex code when a menu choice is selected. The program would probably best be served by making functions for each of the actual menu choices, and then breaking down the complex tasks into smaller, more manageable takes, which could be in their own functions. In this way, a program can be designed that makes sense when read.

Cont.

• Defining a function:• • A function is defined when it is written. Each function

is defined once in a program• and can then be used any other function in the program

that suitably declares it.• Like the main( ) function , every C++ function

consists of two parts, a function• header and a function body.

Cont.

• #include<iostream.h>• • void CompareNum(int, int);// function protype• int main( )• { • int number1, number2;• • cout<<”Enter a number: “<<endl;• cin>>number1;• cout<<”Please enter the second number:”<<endl;• cin>>number2;

Cont.

• 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;

Cont.

• if( m>=n) // find the largest number• largest=m;• • else• largest=n;• cout<<”The largest number of the two numbers is: “• <<largest<<endl;• • return;• }

Cont.

• Out put of the program is:

• Enter a number :30

• Please enter the second number:25

• The largest number of the two numbers is:30

EXERCISE ON FUNCTION

• What will be the output of the function stated below:• #include<iostream.h>• void AdditionNum(int x,

int y) //function prototype here• • void main( )• {• int firstNum,

SecondNum;

Cont.

• cout<<”Enter the first number :”<<endl;• cin>>firstNum;• • cout<<”Please the second the

number:<<endl;• cin>>secondNum;• AdditionNum( firstNum, SecNum); //

function call here • • // actuall firstNum and

SecNum• return ;• }

Cont.

• //Here is the function definition of AdditionNum• void AdditionNum( int x, int y)• {• int sum;• sum=x+y;• • cout<<”The sum of the first Number and Second Number: “<<sum• <<endl;• return 0;• }• Suppose that firstNumber is 30 and Second number is 15.•

18: Array basics

• Arrays are useful critters because they can be used in many ways. For example, a tic-tac-toe board can be held in an array. Arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.

Think about arrays like this:

[][][][][][]

Cont.

• Each of the bracket pairs is a slot(element) in the array, and you can put information into each one of them. It is almost like having a group of variables side by side. Lets look at the syntax for declaring an array.

int examplearray[100]; //This declares an array

Cont.

• This would make an integer array with 100 slots, or places to store values(also called elements). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. 0-99 in a 100 element array, for example.

Cont.

• What can you do with this simple knowledge? Lets say you want to store a string, because C++ has no built-in datatype for strings, at least in DOS, you can make an array of characters. For example:char astring[100];

Cont.

• will allow you to declare a char array of 100 elements, or slots. Then you can receive input into it it from the user, and if the user types in a long string, it will go in the array. The neat thing is that it is very easy to work with strings in this way, and there is even a header file called string.h. There is another lesson on the uses of string.h, so its not necessary to discuss here. The most useful aspect of arrays is multidimensional arrays.

Cont.

• How I think about multi-dimensional arrays.[][][][][][][][][][][][][][][][][][][][][][][][][]

Cont.

• This is a graphic of what a two-dimensional array looks like when I visualize it.

For example:

int twodimensionalarray[8][8];

declares an array that has two dimensions. Think of it as a chessboard. You can easily use this to store information about some kind of game or to write something like tic-tac-toe.

Cont.

• To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can even make a three dimensional array, though you probably won't need to. In fact, you could make a four-hundred dimensional array. It would be confusing to visualize, however. Arrays are treated like any other variable in most ways. You can modify one value in it by putting:

Cont.

• arrayname[arrayindexnumber]=whatever; //or, for two dimensional arraysarrayname[arrayindexnumber1][arrayindexnumber2]=whatever;

Cont.

• However, you should never attempt to write data past the last element of the array, such as whenyou have a 10 element array, and you try to write to the 11 element. The memory for the arraythat was allocated for it will only be ten locations in memory, but the twelfth could be anything, which could crash your computer.

Cont.

• You will find lots of useful things to do with arrays, from store information about certainthings under one name, to making games like tic-tac-toe. One suggestion I have is to use for loops when access arrays.

Cont.

• #include <iostream.h>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 }

Cont.

• } for(x=0; x<8;x++) { for(y=0; y<8; y++) {cout<<"anarray["<<x<<"]["<<y<<"]="<<anarray[x][y]<<" ";//you'll see } } return 0;}

Cont.

• Here you see that the loops work well because they increment the variable for you, and you onlyneed to increment by one. Its the easiest loop to read, and you access the entire array.

One thing that arrays don't require that other variables do, is a reference operator whenyou want to have a pointer to the string. For example:

Cont.

• char *ptr;char str[40];ptr=str; //gives the memory address without a reference operator(&)

//As opposed to

int *ptr;int num;ptr=&num;//Requires & to give the memory address to the ptr

ONE DIMENSIONAL ARRAYS

• A one –dimensional array, which is also referred to as either single-dimensional

• array or a vector , is a list of related values with the same data type that is stored

• using a single group name.

• Here is sample program about the array.

Cont.

• #include<iostream.h>

• const int MAXNUMBERS=6;

• int main( )

• {

• int i, number[MAXNUMBERS];

Cont.

• for(i=1;i<=MAXNUMBERS; i++) //Enter the numbers• {• cout<<”Enter a number :”;• cin>>number[i];• }• cout<<endl<<endl;• for(i=1; i<MAXNUMBERS;i++)// Print the numbers• cout<<”Number ”<<number[i]<<”is”

<<NUMBERS[i]<<endl;• return 0;• }

Cont.

• OUTPUT:• Enter a number:5• Enter a number:6• Enter a number:7• Enter a number:8• Enter a number:9• Enter a number:10• Number 1 is 5• Number 2 is 6• Number 3 is 7• Number 4 is 8• Number 5 is 9• Number 6 is 10

Cont.

• #include<iostream.h>• • const int MAXNUMBERS=6;• int main( )• {• int i, number[MAXNUMBERS];• int sum=0;• for(i=1;i<=MAXNUMBERS; i++) //Enter the numbers• {• cout<<”Enter a number :”;• cin>>number[i];• }• cout<<endl<<endl;

Cont.

• for(i=1; i<MAXNUMBERS;i++)• {• cout<<”Number ”<<number[i]<<”is”

<<NUMBERS[i]<<endl;• sum=sum+number[i];• }• cout<<”The total of the numbers

is :”<<sum<<endl;• return 0;• }• Suppose the respectively is 5 4 8 9 7 2 5 6 8

Conclusion

• This is the end

• Thanks to professor Netiva Caftori