01 Manual C++
01 Manual C++
01 Manual C++
1.0
1.0.1 Computer Is a machine that stores data (numbers, words, pictures), interacts with device (the monitor, printer) and executes program. Is a device capable of performing computations and making logical decisions at speed millions, and even billions, of times faster than human beings can. Example: personal computer, supercomputer. 1.0.2 Program Are sequences of instructions and decisions that the computer carries out to achieve a task. 1.0.3 Computer Programming A computer program tells a computer, in a minute detail, the sequence of steps that are needed to fulfill a task. The act of designing and implementing these programs is called computer programming. Computers process data under the control sets of instruction called computer programs. These computer programs guide the computer through orderly sets of action specified by people called computer programmers. The computer programmer does a great deal of programming. They must be expert in certain language. There are many programming languages such as Fortran, C, C++, Java, Cobol and many others. Every language has their own advantages and disadvantages. The choice of programming language is sometimes a complex decision. It depends on the needs of the program you are creating.
1.1
Elements of Computer Program The following example present a simple C++ program: /*This is a program to calculate the sum of 2 integer numbers*/ #include <iostream.h> main() { int num1, num2, sum; cout<<Enter cin>>num1; cout<<Enter cin>>num2; sum = num1 + cout<<Sum = return 0; } first number:; second number:; num2; <<sum;
Function Body
End Block
1.1.1 Comments Programmers always placed comments, explanations or messages in their program to help them and others to read and understand the programs. Comments in C++ are not executable.
1.1.2 The include Directive and Header Files #include <iostream.h> is called an include preprocessor directive. This directive enables the program to use certain functions contained in the external file. Example: iostream.h. As the file is placed before the program proper, it is called a header file (with the extension .h). C++ provides many predefined functions or routines that are stored in header files. Programmers will use one or more header files to simplify programming and to reduce programming time. Each header file stores functions that are related to a particular application. Example file iostream.h are cin and cout. There are other preprocessor directives. Example: define
1.1.3 Functions All C++ programs are written in terms of functions. Functions are in fact the basic building blocks in C++. In C++, the program must have at least the function main(). Every function must have a body enclosed in braces { }. The function body (also called block) can be of any size. 1.1.4 Declaration All variables in C++ must be declared prior to their use. Variables are simply references to memory locations. In addition to declaring variables we must also specify their types. 1.1.5 Reserve Words Reserve words are special words that have special meaning and they cannot be used for any other purpose. 1.1.6 Console Input/Output We enter data into computer via the system console (the keyboard) by using the function cin (console input) and the redirection operator >>. The function cout (console output) and the redirection operator << sends the output from a variable (some memory location) to the system console (the monitor). 1.1.7 C++ Statements An executable statement in C++ must be followed by a semicolon (;).
1.2
The Importance of Programming Programming will help users to understand the computer. Programming will help users to increase the level of confident. It will help users to appreciate with what computer and programming can be done to solve any problems.
1.3
Good Programming Styles Good programming style is very important in order to make the program easier to read and for maintenance process, especially when other persons try to understand the program. The following guidelines are some tips that you can follow when you write the program: Tabs are set every three spaces. Variable and method names are lowercase, with occasional uppercase characters in the middle. Class names start with an Uppercase letter. Constant names are UPPERCASE, with an occasional UNDER_SCORE. There are spaces after keywords and surrounding binary operators. Braces must line up horizontally or vertically. No magic numbers may be used. Every method, except for main and overridden library methods, must have a comment. At most 30 lines of code may be used per method. No continue or break is allowed.
1.3.1 Naming Convention The following rules specify when to use uppercase and lowercase letters in identifier or variable names: All variables and method names and all data fields of classes are in lowercase. (Maybe with an occasional uppercase in the middle); for example, firstPlayer. All constants are in uppercase (maybe with an occasional UNDER_SCORE); for example, CLOCK_RADIUS. All classes and interface names start with uppercase and are followed by lowercase letters (maybe with an occasional UpperCase letter); for example BankTeller. Names must be reasonably long and descriptive.
1.3.2 Indentation and White Space Use tab stops every three columns. Use blank lines freely to separate parts of a method that are logically distinct. Use a blank space around every binary operator Example: //Good x1 = (-b sqrt(b * b 4 * c)) / (2 * a); //Bad x1=(-b-sqrt(b*b-4*c))/(2*a); Leave a blank space after (and not before) each comma or semicolon. Do not leave space after a parenthesis or bracket in an expression. Leave spaces around the (. . .) part of an if, while, for or catch statement. Example: if (x == 0) y = 0; f(a, b[i]); Every line must fit on 80 columns. If you must break a statement, add an indentation level for the continuation. Start the indented line with an operator (if possible). Example: a[n] = + ; If the condition in an if or while statement must be broken, be sure to brace body, even if it consists of only one statement: Example: if ( && . || ) { }
1.3.3 Braces Opening and closing braces must line up, either horizontally or vertically: Example: while ( i < n ){ . } OR while ( i < n ) { : : } 1.3.4 Unstable Layout Do not use // comments that extend for more than two lines. Example: // comment dont do this // more comment // more comment Use /* */ comment. Example: /* comment more comment more comment */ OR /* comment more comment more comment */
1.4
Relationship Between Compilers, Interpreter and Programs Programmers writing in a high-level language enter the programs instructions into a text editor. Text editor is similar to a word processor, except the files are saved in a basic text format without the font and formatting codes word processor use. The files saved by text editors are called text files.
A program in the form of a high-level language is called source code. Programmers must have their high-level programs translated into the machine language that microprocessor understands. The translation may be done by interpreter or compilers. The resulting machine language code is known as object code. 1.4.1 Interpreters Is a program that translates the source code of a high-level language into machine language. 1.4.2 Compilers Is another program that translates a high-level language into machine language. A compiler, however, makes the translation once, then save the machine language so that the instructions do not have to be translated each time the program is run. To run a C++ program, we must first create it, then compile it, then link it with other modules (or other compiled programs), and finally run it. The figure bellow shows the steps involve in using compiler: Tool Editor Compiler Linker Step Edit Source Code Compile Object file Link Executable file Run Result/Output Library Product
Explanation: After you have created the source code, you compile it using the C++ compiler. The compiler translates your C++ instructions into a machine readable form. The compiled program is called the object file. Besides compiling the source code into an object file, the compiler also generates information necessary for the linker. The linker links the object file generated by the compiler and any other object file your program may request into a final executable file that can be run as many times as desired without having to be translated again.
2.0
Introduction Many programmers develop programs by using the following steps Analysis Design Implementation Testing or Debugging Maintenance Problems can be defined as unsolved problems that required the problem solving or getting results and normally we need to think and skills to get the correct solutions. Solving process will involve the sequence of acting defined clearly. When we implement the process, we will get the result. Problem Solving can be defined as a process to convert the problem to be solved into a solution by using any strategies, techniques and tools that can be used to solve the problem, and finally that will give the good defined clearly solutions. Any problems can be solved by using computer. The following criteria can be used in order to make choices: The problems have varieties of input. The problems have varieties of output. The complexities of the problems. The times consuming based on the problem given. When we using the same technique repeatedly for the same problem but with different input.
2.1
Analysis Is a process to convert the problem statements into the solution for the problem given. It can be done by using the knowledge and realize our abilities to choose and use any strategies, solutions, techniques and tools to define the main problem. The result from the action taken are: The clearly defined problem statements and understood. Unclearly statements or assuming will be clearly defined. Constrains can be defined. In this phase you have to understand and identify the following matters:
i.
Input for the problem: it is several pieces of data that needed to solve the problem.
ii. Expected output or result from the problem solving. iii. Identify constrains and occurrences that may be exist. iv. Identify the formula needed.
2.2
Design An algorithm is a set of sequential instructions that are followed to solve a problem. An algorithm must fulfill the following requirements: i. Has an input. ii. Produce at least one output. iii. Must be clear. iv. Must be correct and can solve the problems. v. Infinite. vi. Efficient vii. Common
10
Two types of algorithm: (i) Pseudocode Is an artificial and informal language that helps programmers develop algorithms. It is use such as English language or Malay language. The purpose of pseudocode is to make humans who do not understand computer programming can easily understand the flow of the problem solving. Pseudocode are using for: Design an algorithm To communicate with human. To use algorithm as a program code. To correct logic error in program code. Program documentation for maintenance purposes and future reference An example for pseudocode: //To calculates income tax payment. Begin Input salary Calculate incomeTax Print incomeTax End
(ii) Flow Chart It is represents by using geometry shapes with connected line. Example of flow chart:
11
End
2.3
Implementation An algorithms is next translated into program code. A top-down approach to coding the program is followed. We begin by writing the main function, and then write the functions on which the main function depends. Errors can be made during coding that can prevent the program from successfully compiling and linking. A common error is called a syntax error.
2.4
Testing or Debugging Testing and debugging is an important step that is to often ignore. Programs typically fail to operate 100% correctly the first time they are compiled or interpreted. Logics errors and other hidden problems called bugs must be located Software must be tested and debugged to make sure the output is correct and reliable. One way to test a program is to provide input for which the results are known.
12
A type of error that can cause your program to stop running (or crash) is called a run-time error.
2.5
Maintaining and Documenting Programmers must document their work so that that they and other programmers can makes changes or updates later. Documentation may also have to be written for the programs users. Maintenance is an important part of the programming process. Most programs are written to help with a task. As a task changes, the program must also change. Users are likely to request that addition and changes be made to the program. Maintaining a program is an important part of the process because it keeps the programmers work up to date and in use. Bugs may be found that were not uncovered during the testing and debugging phase. It also possible that better ways to accomplish a task in the program may be discovered. The steps of the programming process may be repeated in order to refine or repair an existing program.
2.6
Introduction to Algorithm Design. Algorithm design is a most important in a program development. Its can help to represent the flow of the program clearly. An algorithm is a set of sequential instructions that are followed to solve a problem. It must have input and output. Two types of algorithm that are normally use: i) ii) Flow Chart Pseudocode
13
2.6.1 Flow Chart It is represents by using geometry shapes with connected line. The following geometry shapes are using to represent flow chart.
Shapes
Function
Begin/End
Process
Input/Output
Control Structure
Flow control
14
The following algorithm represent for all cases: (i) Sequential Example: To calculate the sum of two numbers and to update the counter.
Statement_1
Statement_2
sum <- A + B
(ii)
Selection a) if
Selection statement
True
Print PASS
15
b) if else_if
True
Selection Statement
False
Process_2
Process_1
Example: If students mark is greater than or equal 50 print PASS, otherwise FAIL
True
mark >= 50
False
Print PASS
Print FAIL
16
c) Nested if-else_if Example: Print the grade based on the following table: Marks 80 100 70 79 60 69 50 59 0 49 Grade A B C D F
True
Print Grade A
True
Print Grade B
True
Print Grade C
17
d) switch
True
Process_1
break
True
Process_2
break
(iii)
Looping a) for
Initial value
True
Process
Increment
False
18
counter = counter + 1
(iv) do-while
Statement
Expression
True
False
19
i != counter False
True
(v)
while
Expression
True
Statement
False
20
number>0
True
Print number
False
2.6.2 Pseudocode The following algorithm represent for all cases: i) Sequence Begin Statement_1 Statement_2 Statement_3 . . . Statement_n End Example: Calculate income tax. Begin Input annualIncome Input status Calculate incomeTax Print incomeTax End
21
ii) Selection
a) if if expression Statement Example: Print the status of student if the passing marks is 50 Begin Input marks if marks >= 50 Print PASS End b) if-else if (expression) Statement_1 else Statement_2 Example: Determine the status (PASS or FAIL) of student if the passing marks is 50. Begin Input marks if marks >= 50 Print PASS else Print FAIL End
22
c) Nested if - else_if Example: Print the grade based on the following table: Marks 80 100 70 79 60 69 50 59 0 49 Grade A B C D F
Begin Input marks if marks > 80 Print A else_if marks > 70 Print B else_If marks > 60 Print C else_if marks >50 Print D else Print F End d) switch Example: to print the number based on the input given Begin Input number switch number case 1 Print ONE break case 2 Print TWO break case 3 Print THREE break default INVALID NUMBER End
23
iii) Looping
a) while while expression statement statement_1 while expression begin_while looping body statement_1 end_while
Example: To calculate the average marks for five students. Begin Set counter=1 and total=0 while counter<=5 begin_while Input marks total <- total + marks counter <- counter + 1 end_while average <- total / counter Print total, average End
b) dowhile Example: To calculate the total of numbers from 0 until the input given. Begin Input number counter = 0; do total = total + counter counter = counter + 1 while counter <= number Print total End
24
2.7
Example of Solutions by Using Algorithm The following examples are the solution that involves the using of algorithm. Example 1: Determine the maximum value between two numbers. Solution:
i)
Pseudocode Begin Input num1 Input num2 if num1>num2 max<-num1 else max<-num2 End
ii)
Flow Chart
Begin
Input num1
Input num2
True
max=num1
False max=num2
Print max
End
25
Example 2: Calculate the total and average of two numbers. i) Flow Chart ii) Pseudocode Begin Input num1, num2 total <- num1 + num2 average <- total/2 Print total, average End
Begin
Input num1
Input num2
Print total
Print average
End
2.8
Example 1: Write a program that reads in the name and hourly wage of an employee. Then ask how many hours the employee worked in the past week. Compute the pay. Any overtime work (over 40 hours per week) is paid at 150 percent of the regular. Solution:
Analysis To calculate the payment of salary for the employee based on the hours of working. Input and output specification requirements: Name, hourly wage and working hours as an input entered by user.
26
Calculate payment of salary for the employee Solving techniques: Get the formula to calculate the payment of salary for the employee (i) if working hours <= 40 salary = hourly wage * working hours (ii) if working hours >40 salary = hourly wage * 40 + (working hours 40) * hourly wage * 150% Design Design algorithm by using Pseudocode Begin Input name, hourlyWage, workingHours if workingHours <40 salary = hourlyWage * workingHours else salary = hourlyWage * workingHours + (workingHours 40) * hourlyWage*1.5 Print salary End
27
Implementation Program code: void main() { clrscr(); char name[100]; int hourlyWage, workingHours; double salary; cout<<"Enter Name: "; cin.get(name,100); cin.ignore(80,'\n'); cout<<"Enter Hourly Wage: RM "; cin>>hourlyWage; cout<<"Enter Working Hours: "; cin>>workingHours; if(workingHours <= 40) salary = hourlyWage * workingHours; else salary = hourlyWage * 40 + (workingHours - 40) * 1.5 * hourlyWage; cout<<"The amount of salary for " <<name << " is RM " <<salary<<endl; getch(); }
28
Exercise Write the algorithm for each of the following: 1. Compute and output the total of three integer number entered from the keyboard. 2. Compute and output the average of two floating-point numbers entered from the keyboard. 3. 4. Input a persons name and age from the keyboard and output the same Enter 30 integer values [1-200]. Find how many of these values fall in the range 1-50, 51-100, 101-150 and 151-200. 5. Aqua Service wishes to compute the water bill for its clients. It levies 5 cents per unit for the first 1000 units of water consumed, 7 cents per unit for the next 1000 units and 10 cents per unit if the number of unit consumed exceed 2000. Given the names, address, old and new meter readings, compute and print the amount each customer owes Aqua Services using suitable heading. 6. XYZ computes the weekly wages of its employees as follows: the rate for the first 40 hours is 5 dollars, the rate for the next 20 hours is 8 dollars per hour and the rate 10 dollars per hour if the number of hours exceed 60. The contribution of each employee to Socco is 1 percent of the wage earned. Read the names and hours worked for the companys employees and print their pay slips.
29
7.
Write a program that determines your weight on another planet. The program should ask for users weight on Earth, then present a menu of the other planets in our solar system. The user should choose one of the planets from the menu and use a switch statement to calculate the weight on the chosen planet. Use the following conversion factors for the other planets. Planet Mercury Venus Mars Jupiter Multiply by 0.37 0.88 0.38 2.64 Planet Saturn Uranus Neptune Pluto Multiply by 1.15 1.15 1.12 0.04
The program should allow the user to repeatedly ask the user to choose a planet for which to calculate the weight until the user enter a menu selection directing the program to exit.
30
3.0
Introduction The simplest framework for C++ program as follow: #include<iostream.h> void main() { Coding code Program is writing here } Program in C++ always begin with the above framework. Notation: The word that wrote in bold (such as include) can be keywords/reserve word, preprocessor directive or any function that provided in C++. This notation will be used in this course. Preprocessor directive
3.1
Capital Letter and Small Letter The using of capital letter and small letter to represent any identifiers in C++ will refer to different meaning. Example: int min; int MIN; Refer to different meaning of identifier
For the most syntax in C++ were represented by using small letter. Example: cin and cout. But we still can use capital letter to define variables or identifiers.
31
3.2
Comment The comment is purely for the benefit of the human reader, to explain in more detail what the next statement does. In C++ there are two methods for writing comments. Example: // comment is write here or /* comment is write here */ Any text enclosed between // and the end of the line or /* and */ is completely ignored by the compiler. The // comment is easier to type if the comments is only a single line. If you have a comment that is longer than a line, then /*..*/ comment is simpler. Example: /* COMMENT1 COMMENT2 */ Comments are used to explain the program to other programmers or to yourself. Example: int Y = 15; // Y is assigned with 15.
3.3
Variable and Identifier Variable is a storage location in the computers memory. An identifier is the name for a variable, method, or class. Variables are identifiers whose value may change during the course of execution of a program. C++ imposed the following rules for identifiers:
i)
Identifiers can be made up of letters, digits, and underscore (_) character. They cannot start with a digit. Example: VALUE, Value, value, count4
32
ii)
iii)
The identifiers must have less than 32 characters Spaces are not permitted inside identifiers. Cannot use reserve words that are reserved exclusively for their special C++ meanings. Identifiers are also case sensitive, capital letter and small letter is different.
iv)
v)
vi)
Example of the invalid identifiers: student age , continue, cout, Principle+interest 17throw, cin, 10Item,
3.3.1 Types of Identifiers Identifiers can represent many types of data. The table bellow shows the varieties of data that always used in C++ program: Definition Char Int Float Double Character Integer Floating number Floating number with the higher precision Types
When the identifier has type of data, its can represent the data from its types. Example: float number; //number can represent floating //number such as 2.33
33
3.3.2 Reserve Words Have standard, predefined meanings and must be used only for their intended purposed. Programmers should not use these reserve words as identifiers. Here is a list of standard reserve words in C++: asm auto break case catch char class const continue goto delete do double else enum extern float for friend register if inline int long new operator private public throw return short signed sizeof static struct switch this try typedef union unsigned virtual void volatile while default
protected templete
3.3.3 Declaring Variables All variables in a program must be declared prior to their use. The variable is declared after open bracket { of program block. To declare any variable, we need to specify the type and followed by variable. Syntax: type variable_name; Example: Declare y and student_name as character Declare x as integer Declare number as float. void main() { char y, *student_name; int x; float number; }
34
More than one variable of the same type, may be placed in the same statement, separate by commas, otherwise we can separate it as follows: Example: char y; char *nama_pelajar; After declaration of variable, the memory will allocate the location for that variable. The location of that variable does not important but the most important is, the content of that variable can be access by the name of that variable. After declaration of any variables, at memory location does not have any value yet. So the variable can not be assumed to hold 0 value or any values until its value is assigned. Example: char y = A; float number = 2.50; 3.3.3.1 Declaring Variables Types of int Syntax: int variable_name; Example: int number; Variables may be initialized by assigning constants to them either at the time of their declaration or at a letter time. Example: int number = 10;
3.3.3.2
35
Example: float average; Any variable can be assigned with initialize values as follows: float average = 2.3333;
3.3.3.3
Declaring Variable Types of double Syntax: double variable_name; Example: double area; Any variable can be assigned with initialize values as follows: double area = 2.3142345; // (approximately 12 digits of precision)
3.3.3.4
Declaring Variable Types of char Syntax: char variable_name; Example: char status; Any variable can be assigned with initialize values as follows: char status = Y;
36
3.4
Constant Constants are values that do not change during the program execution. They can be type of integer, character or floating point. To declare a constant, use the keyword const as in the example: const int num = 15; const float PI=3.2671111;
3.5
Basic Data Type Variables can hold different types of data. Data type will represent the value of variable. Integer will represent the number (positive and negative) without floating point. Example: 100 0 -145 1998
char will represent single character only. To represent a string, we need to use more complex data type representation. Example: A z * 7
float will represent the real number Example: 12.99 0.00 -5.1345 0.008
double will represent the real number or floating point number with higher precession. The following table represent the various of data type and their range: Definition Char Int Float double unsigned char Range -128 ..127 -32768 32767 -3.4E-38 1.7E+38 -17E-308 ..1.7E+308 0 ..255
37
signed char unsigned int signed int Short int unsigned short int signed short int long int usigned long int signed long int
-128 .127 0 ..65535 -32768 .32767 -32768 .32767 0 ..65535 -32768 ..32767 -2147483648 .2147483647 0 ..429497295 -2147483648 .2147483647
3.6
Arithmetic Operator There are seven arithmetic operators in C++ as shown table below: Operator + * / % -++ Action Addition Subtraction (also unary minus) Multiplication Division Modulus division Decrement Increment
Here are some examples of the operations: Expression 7+9 9-3 5*3 Output 16 6 15
38
3.6.1Division Operator The output of division by using operator / is depend on the type of its operand. Integer Division It happens when both operand are integer values. The value can be constant or identifier. If the value for the output of division is floating point number, its will discard the remainder. The output is integer value. Example: Expression 25 / 5 13 / 2 25 / 3 Non Integer Division It happens when at least one of the operand is a real number. The output is a real number value. Example: Expression 5 / 2.5 5.0 / 10 Output 2.0 0.5 Output 5 6 8
3.6.2 Modulo Operator The value of output for modulo % operator is its remainder from the process of division to integer value. Both of operands must be integer value. Example: Expression 5%2 8%4 Output 1 0
39
3.6.3 Hierarchy of Operators The hierarchy operator precedence from highest to lowest is summarized in the following table: Operator Category Unary Arithmetic multiply, divide, remainder Arithmetic add and subtract Relational operators Equality operators Logical AND Logical OR -, --, ++ *, /, % +, <, <=, > >= ==, != && || Operator
The arithmetic expression will be evaluated based on the operator precedence. The highest operator precedence will be evaluated first. Example: 2+7*5 = 2 + 35 = 37
If the level of operator precedence at the same level, the expression will be evaluated from left to right. Example: 2*3/2 =6/2 =3
As in algebra, C++ expression can be complex. Parentheses can be used to force the order of evaluation. So, the evaluation is not based on the operator precedence.
40
Example: (9 (3 + 2)) * 3 = (9 5) * 3 = 4*3 = 12 In C++, we have to be careful when we try to represent arithmetic expression. We also must be careful to the hierarchy level of operator precedence. If we careless about it, the evaluation result may be incorrect.
41
4.0
Assignment Statement In C++, we can represent the expression by using the following assignment statement:
i. ii. iii.
4.0.1 Simple Assignment Statement Arithmetic expression is an example of simple assignment statement. The computer will evaluate the right expression and will assign the value of output to the left variable. Example: i. ii. average = (5 + 5 + 5) / 3; salary = 16.5 * 30;
The expression can be constant or variable values and also can be evaluated, so that the variable must be assigned with any values.
42
Example: void main() { //Calculate the price of product after discount float price, discount, payment; price = 12.60 discount = 0.05; payment = price * discount; cout<< Amount of payment: RM <<payment; }
4.0.2 Doubly Assignment Statement In C++, beside constant and variable, one expression can be from another expression, which means we can do several processes in one expression. Example: A = B = C = 40;
4.0.3 Compound Assignment Statement When we write the program, sometimes we need to modify certain value for any variable, which is the origin value is added or multiply and then the result will be assigned into the origin variable. We always write the code as follows: Example: count = count + 5; if the origin count is 20, the right expression (count + 5) will produce the result of 25. This value will be assigned into count variable. That means the origin value (20) will lose and its replace with 25.
43
In C++, this statement can be represented by using compound operator. Refer to the following table: Operator += -+ *= /= %= Example count += 5 count -= 5 count *= 5 count /= 5 count %= 5 Meaning count = count + 5 count = count 5 count = count * 5 count = count / 5 count = count % 5
The hierarchy of precedence for compound operator is the lowest which means this expression will be evaluated at last.
4.1 Input/Output Statement We enter data into the computer via the system console (the keyboard) by using the function cin (console input) along with the redirection operator >> while the function cout (console output) along with the redirection operator << is used for sending output to the monitor.
4.1.1 cin Statement This statement is used to read input from keyboard. Syntax: cin >> variable; variable refer to any valid identifier only Example: VALID cin >> height; INVALID cin >> 15
44
When entering data from the console, it is always good to include suitable prompts (message) so that we know what we are doing at the console. Example: cout << Enter height: ; cin >> height;
4.1.2 cout Statement This statement will send the data into output device such as monitor based on the format given. Syntax: cout << The list of output; The list of output can be identifier, constant, expression or combination of all. Example: cout << Enter your age:;
When sending output from the variable to the monitor or to the printer, it is often desirable to send message such as titles or labels along with the output. Example: cout << \nYear of birth:<<year_birth;
Notice that the format string has two additional characters: \n. It is called a newline escape sequence. An escape sequence, if used, must appear within the format string enclosed by . It is used for controlling or formatting the output. Escape sequence begin with the backslash \.
45
The following table shows some escape sequence. Code \a \b \f \n \r \t \\ \ \ \0 Audible bell Backspace Formfeed Newline Carriage return Horizontal tab Backslash character Single quote character Double quote character NULL ASCII 0 Meaning
4.1.3 Example of program: #include<iostream.h> void main() { float value; float result; cout<<\n Enter a number: ; cin>>value; cout<<\n The value was entered: <<value; result = value * value; cout<<\n The result for power of two is: <<result; } Example of input and output: Enter a number: 4 //4 is the value from user input
The value was entered: 4 The result for power of two is: 16
46
4.2 Arithmetic Expression Arithmetic expression contain one or more arithmetic operator: Example: i. 2 + 2 ii. 14 * 2 * 5 iii. 12 6 + 13 * 4/3 In C++, we have to represent the algebra expression by using the valid syntax. The following table shows the valid expression. Algebra Expression 14 5 + 6 16 8 2 15 + 5 + 7 2 42 (xy) xy pow ( 4 , 2 ) sqrt (x y ) abs ( x y ) (15 + 5 + 7) / 2 Valid expression in C++ 14 5 + 6 16 8 / 2
4.2.1 Increment And Decrement Operator C++ provides the ++ unary increment operator and the -- unary decrement operator. The table summarized the above operators :
Operator ++
Called Preincrement
Sample Explanation expression ++a Increment a by 1, then use the new value of a in the expression in which a resides. a++
++
Postincrement
Use the current value of a in the expression in which a resides, then increment a by 1.
47
--
Predecrement
--b
--
Postdecrement
b--
Decrement b by 1, then use the new value of b in the expression in which b resides. Use the current value of b in the expression in which b resides, then decrement b by 1
If an increment or decrement operator is placed before a variable, it is referred to as the preincrement or predecrement operator, respectively. If an increment or decrement operator is placed after a variable, it is referred to as the postincrement or postdecrement operator, respectively. Preincrementing (predecrementing) a variable causes the variable to be incremented (decremented) by 1, then the new value of the variable is used in the expression in which it appears. Postincrement (postdecrementing) a variable caused the current value of the variable to be used in the expression in which it appears, then the variable value is incremented (decremented) by 1. Example: #include<iostream.h> void main() { int c; c = 5; cout<< c << endl; //print 5 cout<< c++ << endl; //print 5 then postincrement cout<< c << endl << endl; //print 6 c = 5; cout<< c << endl; //print 5 cout<< ++c << endl; //preincrement then print 6 cout<< c << endl; //print 6 }
48
4.2.2 Types of Arithmetic Expression In C++, there are many different types of data. When assigning the type into arithmetic expression, the compiler will follow the rules bellows: If there are more than one operand in arithmetic expression are double, so the type of output is double.
ii.
i.
If there are all operands in arithmetic expression are int, so the type of output is int.
iii.
In arithmetic expression assignment, the type for statements and values stored inside variable on the left assignment operator will refer to the same type of its variable. Example: int three; double one, two; one = 3.4; three = 12; if we have the following expression statement: two = one + three; The value for output is 15.4 which is type of double. It happens because one is a variable type of double, so the variable three type of int will be changed into real number and the output will be real number.
4.2.3 The cast function The function cast may be used to force an expression to be of a specific data type. Syntax: (type) expression; type (expression);
49
Example: int b; double a; a = 3.4; b = 12; Expression a = (int)(a + b) a = a + (double)b a = (int) a % b a = b % (int)a a = (int)a + b Example of program: Output 15 15.4 3 0 15
Example 1: To calculate the circumference and the area of a circle #include<iostream.h> #include<conio.h> #define PI 3.14159 #define TWO 2.0 void main() { float area, circum, radius; cout<< "Enter radius: "; cin>> radius; area = PI * radius * radius; circum = TWO * PI * radius; cout<< "\nCircumference : "<<circum; cout<< "\nArea : "<< area; getch(); }
50
Example 2 : A person invests RM1000.00 in a saving account yielding 5% interest. Assuming all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts: a = p(1 + r)n where p is the original amount invested (i.e, the principal) r is the annual interest rate n is the number of years a is the amount on deposit at the end of the nth year. Solution: #include #include #include #include <iostream.h> <conio.h> <iomanip.h> <math.h>
void main() { double amount; //amount of deposit double principal = 1000.0;//starting principal double rate = 0.05; //interest rate cout<< "Year" << setw(21) << "amount on deposit" <<endl; for(int year = 1; year <= 10; year++) { amount = principal * pow( 1.0 + rate, year); cout<< setw( 4 ) << year << setiosflags(ios::fixed |ios::showpoint) << setw ( 21 ) << setprecision( 2 ) << amount << endl; } getch(); }
51
Exercise 1. Write a program that asks the user to input the hours, minutes, and second, then convert it into minutes and seconds only. 2. Write a program to read the weight in pound and convert it into kilogram and gram (hint: 1 pound = 0.453592 kg and 1 pound = 453.59237 gm) 3. Write a program to calculate the area which is labeled (black):
4. The area of triangle can be calculated by knowing the border of a, b and c. Given the following formula: area = Where is; s = (a + b + c) / 2 Calculate the area of triangle by using the above formula. 5. Write a program that prompts the user for two numbers, then prints The sum. The difference. The average. The distance (absolute value of the difference). The maximum. The minimum. s (s a) (s b) (s c)
52
6. Write a program that asks the user for the length of the sides of a square. Then print The area and perimeter of the square The length of the diagonal (use the Pythagorean theorem) 7. Write a program that reads two times in military format (0900, 1730)and prints the number of hours and minutes between the two times. Here is a sample run. Please enter the first time: 0900 Please enter the second time: 1730 8 hours 30 minutes
53
5.0
Introduction The selection structure allows instruction to be executed non-sequentially. It allows the comparison of two expressions, and based on the comparison, to select a certain course of action. C++ provides two selection structures: if-else and switch.
5.1
Relational and Logical Operators Relational operation is used to compare the value of two variables, which are equal, less than, greater then and so on. This operation contains two operands, which is can be value of identifier, constant or both combinations. The six relational operators in C++ are shown below: Operator < <= > >= == != Less than Less than or equal Greater than Greater than or equal Equal Not equal Meaning
The result of evaluation of a relational operation is either true (represented by 1) or false (represented by 0).
54
To evaluate the combination of relational operation on different set of identifiers, we can perform logical operation by using the logical operators. The tree logical operators in C++ are shown bellow: Operator && || ! Meaning AND OR NOT
The following table represents the function for each logical operator. This table known as True Table. 0 values represent false and 1 represent true. Truth table for AND operator: State 1 1 0 0 1 Truth table for OR operator: State 1 1 0 0 1 State 2 0 1 0 1 Value 1 1 0 1 State 2 0 1 0 1 Value 0 0 0 1
55
5.2
If Statement If statement construct enable your program to choose from several alternatives and executes only one statement. In C++, we will use relational and logical operator to represent if statement. Syntax: if (expression) statement; Execution: The statement will be executed if the expression value is true or 1 Normally, the expression is a relational expression that contain of true or false values. Example: if (age < 3) cout<< Baby;
If statement can have many statements known as compound statement. Compound statement must have open bracket { and close bracket }.
56
5.1.1 if-else statement Syntax: if expression statement_1 else statement_2 Execution: statement_1 will be executed if the expression value is 1 statement_2 will be executed if the expression value is 0 Example: a)
if (cgpa < 2.0 ) status = F; else status = P; if ( choice == 1) gender = M; else gender = F; if ( a < b min = a; max = b; } else{ min = b; max = a; } ) { // compound statement // executed if a<b // compound statement // executed if a>=b
b)
c)
57
Example of program : #include <iostream.h> void main() { int marks; cout<< Enter marks: ; cin>> marks; if (marks >= 50) cout<< PASS; else cout<< FAIL; }
5.3
switch Statement The switch construct is an elegant alternative to the more complex ifelse-if construct which is more difficult to read and understand. The switch construct enables your program to choose from several alternatives. switch statement just can be implemented for expression with an integer or character constant. Syntax: switch (expression) { case expression_1 : statement_1; break; case expression_2 : statement_2; break; case expression_3 : statement_3; break; case expression_4 : statement_4; break; . . case const_n : statement_n; break; default : statementA; }
58
Execution : When the switch statement is executed, the expression is first evaluated. If it evaluates to expression_1, the statement sequence for case expression_1 is executed followed by the break which terminates the entire switch statement. If it evaluates to expression_2, then the statement sequence for case expression_2 is executed followed by break which then terminates the switch statement; and so on. If it evaluates to none of the case expressions, the statement sequence for the default case is executed, thus terminating the switch statement. Example 1: int number; cin>> number; switch ( number ){ case 1: cout<< one ; break; case 2: cout<< Two ; break; case 3: cout<< Three ; break; default: cout<< Other number ; }
59
Example 2: char noPlate; cin >> noPlate; switch (toupper(NoPlate) { case R : cout<< PERLIS\n; break; case K : cout<< KEDAH\n; break; case A: cout<< PERAK\n; break; case B : cout<< SELANGOR\n; break; . . default : cout<< wrong input.try again\n; }
Example 3: To calculate total price of fish based on the quantity and type entered by user. #include <iostream.h> #include <conio.h> void main() { clrscr(); int choice; float price, quantity, totPrice; cout cout cout cout cout cout cout << << << << << << << ">>>>>>>Menu Selection<<<<<<<<<"; "\n 1. Ikan Bawal "; "\n 2. Ikan Merah "; "\n 3. Ikan Pari "; "\n 4. Ikan Gelama "; "\n 5. Lain - lain "; "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
cout << "\n\nEnter choice: "; cin >> choice; switch(choice) { case 1 :
60
: : : : :
price = 2.00; break; price = 3.00; break; price = 1.50; break; price = 1.00; break; cout << "\nWrong input";
cout << "Enter quantity : "; cin >> quantity; totPrice = quantity * price; cout << "Total price: " << totPrice; getch(); }
5.4
Nested if statement The if-else constructs can also be nested (placed one within another) to any depth. If nested, they generally take the forms: if-else-if and if-if else.
5.4.1 if-else-if statement Syntax: if (expression_1) statement_1; else if (expression_2) statement_2; . else if(expression_n ) statement _n; else last_statement; In this nested form, expression_1 is first evaluated. If it is not zero, statement_1 is executed and the whole statement terminated.
61
On the other hand, if expression_1 is zero, control passes to the else if part and expression_2 is evaluated. If it is not zero, statement_2 is executed and the whole statement is terminated. If it is zero, other else if parts (if any) are tested in a similar way. Finally, if expression_n is not zero, statement_n is executed; if not, last_statement is executed. Only ONE of the statements will be executed. Example 1: #include <iostream.h> void main() { int marks; cout<< Enter marks:; cin>> marks; if (marks >= 90) cout<< A; else if(marks >= 80) cout<< B; else if(marks >= 70) cout<< C; else if(marks >= 60) cout<< D; else if (marks >= 50) cout<< E; else cout<< F; }
62
Example 2: Program to test whether a banking transaction is a deposit, withdrawal, transfer or an invalid transaction, and to take the necessary action #include<iostream.h> main() { float amount; char transaction_code; cout <<"\nEnter your transaction(D, W, T):"; cin >> transaction_code; if (transaction_code == 'D') { cout << "\nDeposit transaction"; cout << "\nEnter amount: "; cin >> amount; } else if (transaction_code == 'W') { cout << "\nWithdrawal transaction"; cout << "\nEnter amount: "; cin >> amount; } else if (transaction_code == 'T') { cout << "\nTransfer transaction"; cout << "\nEnter amount: "; cin >> amount; } else { cout << "\nInvalid transaction!"; cout << "\nPlease enter the correct transaction code"; } return 0; }
63
Example 3: Write a program to calculate tax for the employee at ABC Company. Given the following table: Gross Salary RM 1500 RM 1999 RM 2000 RM 3999 RM 4000 RM 4999 >RM 5000 Tax 5% from gross salary 10% from gross salary 12% from gross salary 15% from gross salary
#include <iostream.h> #include <conio.h> void main() { double grossSalary; double tax; cout << "Enter gross salary: RM "; cin >> grossSalary; if(grossSalary >= 5000) tax = 0.15 * grossSalary; else if (grossSalary >= 4000) tax = 0.12 * grossSalary; else if (grossSalary >= 2000) tax = 0.10 * grossSalary; else tax = 0.05 * grossSalary; cout << "\nAmount of tax : RM "<<tax; getch(); }
64
5.4.2 if-if else statement Syntax: if (expression_1) if (expression_2) if (expression_3) statement_1; else statement_2; else statement_3; else statement_4; In this nested form, expression_1 is evaluated. If it is zero, statement_4 is executed and the entire nested if statement is terminated; if not, control goes to the second if (within the first if) and expression_2 is evaluated. If it is zero, statement_3 is executed; if not, control goes to the third if (within the second if) and expression_3 is evaluated. If it is zero, statement_2 is executed; if not, statement_1 is executed. Only ONE of the statements is executed. When using the above form care must be taken to properly match the ifs within the correct elses. One simple rule to follow is: always match an else with the nearest if before the else.
65
5.5
Minimum and Maximum Example: //Finding the maximum and minimum of three integers #include <iostream.h> #include <conio.h> int maximum (int, int, int); int minimum (int, int, int); int main() { int a, b, c; cout << "Enter three integers: "; cin >> a >> b >> c; cout << "Maximum is: " << maximum( a, b, c)<< endl; cout << "Minimum is: " << minimum( a, b, c)<< endl; getch(); return 0; } int maximum (int x, int y, int z) { int max = x; if (y > max) max = y; if (z > max) max = z; return max; } int minimum ( int x, int y, int z ) { int min = x; if ( y < min ) min = y; if ( z < min ) min = z; return min; }
66
Exercise 1. The cost of an international call from New Zealand to New Delhi is calculated as follow: connection fee, $1.99; $2.00 for the first three minutes; and $0.45 for each additional minute. Write a program that prompts the user to enter the number of minutes the call lasted and outputs the amount due. 2. Write a program that calculates and prints the bill for a cellular telephone company. The company offers two types of service: regular and premium. Its rates vary depending on the type of service. The rates are computed as follows: Regular service : $10.00 plus first 50 minutes are free. Charges for over 50 minutes are $0.20 per minute. Premium service: $25.00 pus:
a) For calls made from 6.00 a.m to6.00 p.m, the first 75 minutes are free; charges for over 75 minutes are $0.10 per minute. b) For calls made from 6.00 p.m to 6.00 a.m, the first 100 minutes are free; charges for over 100 minutes are $0.05 pr minute. Your program should prompt the user to enter an account number, a service code (type char), and the number of minutes the service was used. A service code of r or R means regular service; a service code of p or P means premium service. Treat any other character as error. Your program should output account number, type of service, number of minutes the telephone service was used, and amount due from the user. For the premium service, the customer may be using the service during the day and at night. Therefore, to calculate the bill, you must ask the user to input the number of minutes the service was used during the day and the number of minutes the service was used at night.
67
6.0
Introduction The repetition or iteration structure permits a sequence of instructions to be executes repeatedly until a certain condition is reached. In C++, there are three forms, while, do-while and for.
6.1
while statement The general form of while statement: Syntax: while (expression) statement; The statement can be either a simple or compound statement. The expression, called a loop condition, acts as a decision-maker and is a logical expression. The expression provides an entry condition. If it initially evaluates to true, the statement executes. The loop condition-the expression- is then reevaluated. If it again evaluates to true, the statement executes again. The statement (body of loop) continues to execute until the expression is no longer true. A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loops body contains one or more statements that ensure that the loop condition-the expression in the while statement will eventually be false.
68
Example 2: cin>> n; while ( n > 0 ){ cout << n; n -= 5; } //if the input value is negative or zero, so the //while compound statement will not be executed.
6.1.1 Counter-Controlled while Loops When we know exactly how many pieces of data (data entries) need to be read, the while loop assumes the form of a counter-controlled while loop. In this case, the while loop might look like the following: counter = 0; while ( counter < N) { . . counter++; . . } Suppose the program has N data items. You can set up a counter (initialize to 0 before the while statement) to track how many items have been read.
69
Before executing the body of the while statement, the counter is compared with N. The value of N can be determined in many ways such as input by user. If the counter < N, the body while statement executes. The body of loop continues to be execute until the value of counter >= N. Thus, inside the body of the while statement, the value of the counter increments after it reads a new item. Example: #include <iostream.h> void main() { int limit, number; int counter = 0; int sum = 0; cout << "Enter data for processing: "; cin >> limit; while (counter < limit) { cout << "\nEnter data " << counter << ": "; cin >> number; sum = sum + number; counter++; } cout << "\nThe sum of " << limit << " number = " << sum <<endl; if ( counter != 0) cout << "\nThe average = " << sum/counter; else cout << "\nNo input"; }
70
6.1.2 Sentinel-Controlled while Loops You might not know how many pieces of data (or entries) need to be read, but you do know that the last entry is a special value, called a sentinel and this type is called a sentinel-controlled while loop. A while loop might look like the following: Input the first data item into variable while (variable != sentinel) { . . input a data item into variable } In this case, you have to read the first item before entering the while statement. If this items does not equal the sentinel, the body of the while statement executes. The while loop continues to execute as long as the program has not read the sentinel.
71
Example: #include <iostream.h> #include <conio.h> void main() { int number; int sum = 0; int count = 0; int SENTINEL = -999; cout << " Enter numbers ending with " <<SENTINEL; cout << "\n Enter number: "; cin >> number; while (number != SENTINEL) { sum = sum + number; count++; cout << "\n Enter number: "; cin >> number; } cout << "\n The sum of " << count << " numbers =" << sum; if ( count != 0) cout << "\n The average = " << (sum / count); else cout << "\nNo input"; }
72
6.1.3 Flag-Controlled while Loops A flag-controlled while loop uses a boolean variable to control the loop. The flag-controlled while loop takes the following form: bool found = false; while (!found) { . . if (expression) found = true; . . } The variable found, which is used to control the execution of the while loop, is called flag variable.
6.2
for Statement The for loop is typically called a counted or indexed for loop. The for loop has the general form: for (initialization; expression; incrementation) statement; The initialization part typically refers to the initial value (if any) given to a loop variable or counter. But it can also include the initialization of any other variable. This initialization part is carried out just once at the beginning of the loop.
73
The expression part determines whether the loop execution should be continued. If the expression is zero (false), the for loop is terminated; if it is not zero (true), the for statement (which can take the form of a block) is executed. The incrementation part typically increments (or decrements) the loop counter variable. This is done after the for statement is executed. This part, like the initialization part, can also include the incrementation of other variables. Example: int sum = 0; for (int i = 0; i < 20; i++) sum = sum + i; cout << Sum of the first 20 numbers = ; cout << sum; The for loop is executed as follows: After the one-time initialization, the expression is first evaluated. If it is zero (false), the for loop is terminated; if it is not zero (true), the statement in the loop is executed, and then the incrementation is performed. The condition expression in the for loop is again evaluated and the process is continued until the expression become zero (false).
74
6.3
dowhile Statement The general form of a dowhile statement is: do{ statement; }while (expression);
The do-while statement can be either a simple statement or a compound statement. If is a compound statement, enclose it between curly braces. The expression is evaluated after the statement is executed. This means the statement in the do-while will be executed at least once. In the while statement, the statement will not be executed if the expression is false. Example: #include <iostream.h> void main() { int selection; do { cout << "\n Menu" << endl; cout << "\n 0. Exit"; cout << "\n 1. Append"; cout << "\n 2. Delete"; cout << "\n 3. Modify"; cout << "\n Enter Selection : "; cin >> selection; }while ( selection > 0 && selection < 4 ); } In this example, the program displays the menu and the requests a selection. If the selection is 1, 2, or 3, the menu is displayed again, otherwise, the loop is terminated.
75
6.4
Nested Loops All of the repetition loop discussed so far can also be nested ( a while loop within another while loop, a do-while loop within another dowhile loop, and a for loop within anther for loop) to any degree. The nesting of loops provides power and versatility required in some applications. Example: #include <iostream.h> #include <conio.h> void main() { for (int i = 1; i < 5; i++) { cout << "\n" <<i; for (int j = i + 1; j < 5; j++) cout << j; } getch(); }
76
6.5
BEGIN SENTINEL = 0 max = 0 min = 999 total = 0 count = 0 INPUT number WHILE ( number != SENTINEL) START_WHILE total = total + number count = count + 1 IF number > max max = number IF number < min min = number INPUT number END_WHILE IF count != 0 average = total / count ELSE PRINT No input PRINT count, total, min, max, average ; END
77
Example of program: #include <iostream.h> #include <conio.h> void main() { int number; int SENTINEL = 0; int max = 0; int min = 999; int total = 0; int count = 0; cout << " Enter numbers ending with " <<SENTINEL; cout << "\n Enter number: "; cin >> number; while ( number != SENTINEL ) { total = total + number; count++; if (number > max) max = number; if (number < min) min = number; cout << "\n Enter number: "; cin >> number; } cout << "\n The total of " << count << " numbers = " << total; cout << "\n Maximum number: " << max; cout << "\n Minimum number: " << min; if ( count != 0) cout << "\n The average = " << (double)total / count; else cout << "\nNo input"; getch(); }
78
Exercise 1. Generate the following pyramid of digit by using nested loops and develop a formula to generate the appropriate output for each line. 1 232 34543 4567654 567898765 2. Write the programs to print the following patterns: a. ********** ********* ******** ******* ****** ***** **** *** ** * b. 1 21 321 4321 54321 4321 321 21 1
3.
Write a program that reads a set of integers, and then finds and print the sum of the even and odd integers.
4.
Write a program that uses a while loop to perform the following steps a. Prompt the user to input two integer: firstNum and secondNum (firstNum must be less that secondNum) b. Output all odd numbers between firstNum and secondNum. Output the sum of all even numbers between firstNum and secondNum. d. e. Output the number and their power of two. Output the sum of the power two of odd numbers between firstNum and secondNum.
c.
79
5.
Write a program that prompts the user input an integer and then outputs the number with the digit reversed. Example, 3456 will be displayed as 6543.
6.
A local university wants to know how well female and male students perform in certain course. The code f is used for female students; m is used for male students. Every student record consists of letter and GPA. The number of entries is unknown. Write a program that computes and output the average GPA for both female and male student. Format your result to two decimal format.
80
Chapter 7 Function
7.0
Introduction C++ is a function-based language. A large programming problem can be broken up into separate modules or subroutines called function. One of these functions must be called main(). The main() function invokes and controls the execution of other functions within its scope. Example:
#include<iostream.h> main () { X(); Y(); }
X() { : }
Y() { : }
Example of program that have two functions named as X( )and Y( ) In C++ we have two types of function known as predefined function and user-defined function.
81
7.1
Defining Function The programmer must first define a function before we can use it in a program. A C++ function definition takes the form: Syntax: function_type function_name (parameter-list) { variable declaration return expression } where function_type is any valid C++ data type. function_name is any valid C++ identifier. parameter-list is a list of parameters separated by commas. variable declaration is a list of variables declared within the function. return is a C++ keyword. expression is the value returned by the function. The function_type (placed before the function_name) indicates the type of value that the function will return when the return statement in the function is executed. The return value (given by the expression in the return statement) may be of any valid type: int, float, double, char. If we do not specify its type, the function is assumed to return an integer value by default. It is also possible that a function may not return any value to the calling program (function). In this case we say the function has the type void. Since the void type does not return a value, the expression part of the return statement is dropped. The function_name is the function and the parameter-list is a list of parameters, separated by commas.
82
The parameter type tells what value the parameter can receives when the function is called or invoked. Here are several examples of function declaration: float average (float x, float y) int cube (int i) char response (char ch) void heading () main() Example: // function to calculate area of circle float calArea (int radius) { float area; //use value of radius to calculate area area = (2.0/7.0) * radius * radius; return area; // return value area of circle }
83
7.2
Making Function Calls Function is called by using the following format: function_name (exact-parameter-list) exact-parameter-list arguments whose values are to be passed as input to the corresponding parameters in the called function. An argument can be explicit value, a variable name, an expression or another function call. Example : main() { another(); return 0; } another() { return value; }
//calling another()
//returning to main()
Flow of control between main() and another() When a function is called, the program temporarily leaves the current function to execute the called function. When the called function terminates, program control reverts to the calling function. A function call consists of the name of the function, followed by a list of arguments whose values are to be passed to the corresponding parameters in the called function. The number and type of the arguments must correspond to the number and type of the parameters in the called function.
84
Example : #include<iostream.h> int num1, num2, sum; void setData(); void printSum(); void main() { setData(); printSum(); } void setData() { cout<< Enter two numbers:; cin>>num1; cin>>num2; } void printTotal() { } NOTE: (1 ..7) Flow of program executions. sum = num1 + num2; //(6) cout<< Sum of two numbers is:<<total; //(7) //(3) //(4) //(2) // (1) // (5)
85
7.3
Function Prototypes A function prototype specifies the number of arguments and their types as well as the return value type of the function. The prototype is used to check if the number of arguments and their types in the calling function correspond to the number of parameters and their types in the called function every time the function is called. The general form of a function prototype declaration: function_type function_name(parameter-list) parameter-list consist of value types for every parameter that can be input to the function. Name of parameter can be ignored. Example: float calcArea (int radius, int width); or float calcArea (int, int); Example: #include <iostream.h> void main() { void printComment(); printComment(); cout<< calTotal(5,2); } void printComment() { cout<< Sum of two numbers is: ;} int calTotal(int a, int b) { int total; total = a + b; return total; } // function prototype int calTotal (int , int );//function prototype
86
7.4
Function Parameters In C++, the code and data defined in one function cannot interact with the code and data defined in another function because the two functions are independent, and therefore, have different scopes. In order to interact with one another, the functions pass arguments. The calling or invoking function passes argument (such as constants, pointer or values of variable) to the called function. The called function receives the values passed to it and stores them in its parameters. Once the values are received into the parameters, the parameters are defined and thenceforth they behave very much like the local variables declared within the function. The number and type of arguments passed by the calling function must agree with the number and type of the parameters in the called function. Example: #include <iostream.h> void display(int); main() //The main() function definition { int x = 12; //defines an integer variable display(x); //call display() and passes it x return 0; //return 0 to environment } void display(int y) //function definition { cout << y; //dislay the value of y } The value 12 is passed from main() to display() Two way to invoke functions in many programming languages are passing by value (call-by-value) and passing by reference (call-by-reference)
87
7.4.1 Passing by Values When an argument is passed call-by-value, a copy of arguments value is made and passed to the called function. Changes to the copy do not affect the original variables value in the caller. This prevents the accidental side effects that so greatly hinder the development of correct and reliable software systems. Example: multiple_two (3,80); Example of program: #include <iostream.h> void main() { int multiple_two (float,float); float a, a_2, value; a = 3; a_2 = 80; value = multiple_two (a, a_2); cout << The value of a_2 is : << a_2; cout << multiple of two is: << value; } int multiple_two (float i, float i_2) { i_2 = i * i; return i_2; } Explanation: When multiple_two function is called, the value of a(3) is copied to i, and the value of a_2(80) is copied to i_2 The function multiple_two will perform the calculation and get the new result of i_2 (9)
88
When the flow of process return to the calling function, the value of i_2 will be returned to the calling function. 7.4.2 Passing by Reference With passing by reference, the caller gives the called function the ability to directly access the callers data, and to modify that data if the called function so chooses. A reference parameter is an alias for its corresponding argument. To indicate that a function parameter is passed by reference, simply follow the parameters type in the function prototype by ampersand (&) Example: int &count; Example: //Comparing call-by-value and call-by-reference //with reference #include <iostream.h> int squareByValue( int ); void squareByReference ( int & ); int main() { int x = 2, z = 4; cout << << << << << x = << x << before squareByValue\n Value returned by squareByValue: squareByValue( x ) << endl; x = << x << after squareByValue\n endl;
cout << z = << z << before squareByReference << endl; squareByReference( z ); cout << z = << z << after squareByReference << endl; return 0; }
89
int squareByValue ( int a ) { return a *= a; // callers argument not modified } void squareByReference (int &cRef ) { cRef *= cRef; // callers argument modified } RESULT x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue z = 4 before squareByValue z = 16 after squareByReference
7.5
Using Predefined functions C++ compilers include predefined function, ready-to-use function to make programming easier. The functions that come with your compiler are called library function. Library functions are just like functions you create and may be used in the same way. The difference is that the source code for library functions does not appear in your program. The prototypes for library functions are provided to your program using the #include compiler directive.
90
Example: #include <iostream.h> #include <math.h> int main() { double base; double exponent; double answer; cout << "Enter the base: "; cin >> base; cout << "Enter the exponent: "; cin >> exponent; answer = pow (base, exponent);//built-in function cout << "The answer is: " << answer << endl; return 0; }
Many C++ compilers provide basic math function. The header file math.h Function Abs Prototype int abs (int x) double Description Returns the absolute value of an integer Pow pow (double Calculate x to the power of y (double Calculate the positive x, double y) Sqrt double x) sqrt
square root of x)
C++ also includes many functions for analyzing and changing characters. The header file ctype.h. Function isupper Prototype int isupper (int c) int islower (int c) int isalpha (int c) Description Determines if a character is uppercase. islower Determines if a character is lowercase isalpha Determines if a character is a letter (a-z, A-Z)
91
Isdigit
toupper
Converts uppercase
character
to
tolower
Converts lowercase.
character
to
We can control the precision of floating-point numbers, i.e., the number of digits to the right of the decimal point, by using setprecision stream manipulator. The header file iomanip.h Example: #include <iostream.h> #include <math.h> #include <iomanip.h> int main() { double root = sqrt (2.0); int places; cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << "\nPrecision set by the set << precision manipulator:\n"; for(places=0; places <= 9; places++) cout << setprecision (places) << root << '\n'; return 0; }
The use left and right flags enable fields to be left-justified with padding characters to the right, or right-justified with padding characters to the left, respectively. setw stream manipulator to specify internal spacing. The header file iomanip.h
92
Example : #include <iostream.h> #include <math.h> #include <iomanip.h> int main() { cout << setw(10) << setiosflags( ios::right) << 123 << endl; return 0; }
The string handling library provides many useful functions for manipulating string data, comparing string and others. The header file string.h. Function Prototype char *strcpy *s1, const char *s2) char *strcpy Function description (char Copies the string s2 into the character array s1. The value of s1 is returned.
*s1, const char *s2, s2 into the character array s1. the value size_t n) of s1 is returned. int strcmp (const Compares the string s1 to the string s2. char *s1, const char The function returns a value of 0, less 0, *s2) or greater than 0 if s1 is equal, less than, or greater than s2, respectively. int strcmp (const Compares up to n characters of the string char *si, const char s1 to the string s2. The function return 0, *s2, size_t n) less than 0 or greater than 0 if s1 is equal to, less than, or greater than s2, respectively.
93
Example 1: #include <iostream.h> #include <string.h> #include <conio.h> int main(void) { char string[10]; char *str1 = "abcdefghi"; strcpy(string, str1); cout << string; getch(); return 0; } Example 2: #include <iostream.h> #include <string.h> #include <conio.h> int main(void) { char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc"; int ptr; ptr = strcmp(buf2, buf1); if (ptr > 0) cout << "buffer 2 is greater than buffer 1\n"; else cout << "buffer 2 is less than buffer 1\n"; ptr = strcmp(buf2, buf3); if (ptr > 0) cout << "buffer 2 is greater than buffer 3\n"; else cout << "buffer 2 is less than buffer 3\n"; getch(); return 0; }
94
7.6
Creating User-Defined Functions Example of program : #include <iostream.h> #include <math.h> #include <conio.h> //Function prototype int sum( int , int ); int multiply (int , int ); int power ( int , int ); void maximum ( int , int ); void minimum ( int , int ); int main() { int num1, num2; cout << "Enter two numbers: "; cin >> num1 >> num2; //calling function int valueSum = sum( num1 , num2 ); cout << " \nThe value of sum : " << valueSum; cout << "\nThe value of multiply : " << multiply (num1 , num2 ); int valuePower = power( num1 , num2 ); cout << "\nThe value of power : " << valuePower; maximum ( num1 , num2 ); minimum ( num1 , num2 ); getch(); return 0; } //Function definition int sum ( int x , int y ) { return x + y ; }
95
int multiply ( int x , int y ) { int value = x * y; return value; } int power ( int x, int y ) { return pow( x , y ); } void maximum ( int x, int y ) { int max; if ( x > y ) max = x; else max = y; cout << "\nThe maximum value : " << max; } void minimum ( int x, int y ) { int min; if ( x < y ) min = x; else min = y; cout << "\nThe minimum value : " << min; }
96
Exercise 1. Given floating-point values for a, b and c, find the values of x where x = -b (b2 4ac) 2a 2. Write a program that reads a students name together with his or her test scores. The program should then compute the average test score for each student amnd assign the appropriate grade. The grade scale is as follows: 90 100, A; 80 89, B; 70 79, C; 60 69, D; 0 59, F Your program must use the following methods: a. A void method, calculateAverage, to determine the average of five test scores for each student. (This method does not output the average test score. That task must be done in the method main) HINT: Use passing by reference concept. b. A value-returning method, calculateGrade, to determine and return each students grade. (This method does not output the grade. That task must be done in the method main). HINT: Use passing by value concept. The output should be of the following form: Fill the last two columns.
Student Ahmad Salmah Jamal Test1 Test2 Test3 Test4 Test5 85 80 78 .. .. 83 90 81 .. .. 77 95 11 .. .. 91 93 90 .. .. 76 48 73 .. .. Average Grade
97
Chapter 8 Array
8.0
Array An array is a collection of a fix number of elements, wherein all the elements are of the same data type. All the elements of an array occupy of contiguous memory locations and each element can be identified using an index or subscript. The following diagram shows a one-dimensional array
X[0]
X[1]
X[2]
X[3]
Each element in the array can access by referring on index of an array, such as for the first element can be referred as X[0], the second element can be referred as X[1], and so on until the last element at i as X[i-1].
8.1
Array Declaration The general form of declaring a one-dimensional array is: type variable_name[size]
type- which is the type of each element in the array. variable_name is the name of an array which is any valid identifier. size defines how many elements the array will hold
98
Example: int number [5]; // a contains of 5 element which is // type of integer The declaration above can store up to 5 integers with the first integer occupying location a[0] and the last integer occupying a[4]. This array does not contain any value yet. Note that index runs from 0 to 4. In C++, an index always starts from 0 and end with size 1.
8.2
Array Initialization In C++, an array may be initialized at the time of its declaration Example: int number [5] = { 2, 4, 6, 8, 10}; The value of an array for each element as follows: number [0] = 2 number [1] = 4 number [2] = 6 number [3] = 8 number [4] = 10 If the initialize value less than size of an array, the extra values will be initialized with 0. Example: int number [5 ] = {1,2,3}; The value of an array for each element as follows: number [0] = 1 number [1] = 2 number [2] = 3 number [3] = 0 number [4] = 0
99
If any declaration of an array without specified size and initialized value, so the size of an array will be set automatically as many as number of value assigned.
Example: float arr [ ] = {1, 2, 3, 4}; //The size of array //is four.
8.3
Array Accessibility
8.4
100