Professional Documents
Culture Documents
ii
Munirah Ab.Rahman (Course Coordinator) Zarina Tukiran Siti Idzura Yusof Suhaila Sari
Department of Computer Engineering Faculty Electrical & Electronic Engineering Universiti Tun Hussein Onn Malaysia
Salinan Digital Pertama (Modul Pengajaran & Pembelajaran), 2012 (c) Munirah Ab.Rahman, Zarina Tukiran, Siti Idzura Yusof dan Suhaila Sari
SEMESTER I 2012/2013 Hak cipta terpelihara. Tidak dibenarkan mengeluar ulang mana-mana artikel, ilustrasi dan isi kandungan buku ini dalam apa-apa bentuk dan cara apa jua sama ada secara elektronik, fotokopi, mekanik atau cara lain sebelum mendapat izin bertulis daripada penulis.
Edisi ini merupakan edisi Modul Pembelajaran dan Pembelajaran yang diterbitkan tanpa melalui proses penilaian dan penyuntingan. Mutu edisi ini akan dibaiki dari masa ke semasa berdasarkan maklumbalas yang diterima daripada aktiviti pengajaran. Sebarang pelanggaran atau unsur yang bertentangan dengan aspek etika penulisan dan hak cipta adalah di bawah tangung jawab penulis. Edaran modul ini hanya dibenarkan di dalam kawasan premis Universiti Tun Hussein Onn Malaysia (UTHM) atau mana-mana cawangannya sahaja. Pengedaran di luar UTHM memerlukan kebenaran bertulis dari penulis.
iv
UNIVERSITI TUN HUSSEIN ONN MALAYSIA FAKULTI KEJURUTERAAN ELEKTRIK DAN ELEKTRONIK PERANCANGAN KULIAH LECTURE PLAN MAKLUMAT KURSUS (COURSE INFORMATION)
SEMESTER/SESI (SEMESTER/SESSION) KOD KURSUS (COURSE CODE) NAMA KURSUS (NAME OF COURSE) BEBAN AKADEMIK PELAJAR (STUDENT ACADEMIC LOAD) : : : : I/2012/2013 BEC10102 COMPUTER PROGRAMMING
Aktiviti Pembelajaran (Learning Activity) Kuliah (Lecture) Tutorial (Tutorial) Amali (Practical) Persediaan (Preparation): 1. Projek (Project) 2. Ulangkaji (Revisions) 3. Lain-lain (Others) Pembelajaran Kendiri (Independent Study) Persediaan dan Penilaian Formal (Preparation and Formal Assessments) JUMLAH JAM BELAJAR (JJB) TOTAL STUDENT LEARNING TIME (SLT) Kursus Pra-Syarat (Pre-requisite Course) Nama Pensyarah (Lecturers Name)
Minggu (Week) 12 0 14
9 12
2 1
18 12 0
2 4
1 2
2 8
80
: Tiada (Nil) : : : : Pn. Munirah Ab. Rahman (Course Coordinator) Pn. Zarina Tukiran Pn. Idzura Yusof Dr. Suhaila Sari
MATLAMAT (GOALS) : Introduce the concept of Software Development Environment with an emphasis on programming skills; design, develop, test, and evaluate software systems which can be apply to the solution of problem solving using C++ Programming Language.
SINOPSIS (SYNOPSIS) : This course is intended to provide a study of programming concept through the use of a high level programming language such as C++. Students will learn to design, code, debug, test and document wellstructured programs based on technical and engineering problems. Topic covered; Software Development Method, programming language basics, data types , input and output operations, the use of arrays, string, pointers and structures, file processing handling and advance applications.
HASIL PEMBELAJARAN (LEARNING OUTCOMES) : At the end of this course the student will be able to: (1) (2) (3) Demonstrate the fundamental knowledge of C++ programming language for solving computer programming problems correctly. (C3) Organize good team work to solve problem based on given task of computer programming techniques and applications. (P4, TS) Differentiate the computer programming techniques for latest electronic and computer engineering application. (A3, LL)
ISI KANDUNGAN (CONTENT) : MINGGU (WEEK) 1 KANDUNGAN (CONTENT) 1. SOFTWARE DEVELOPMENT PRINCIPLE 1.1 Electronic Computers 1.2 Introduction to Programming 1.3 Software Development Method 1.4 Algorithm Design 2. INTRODUCTION TO C++ LANGUAGE 2.1 Introduction to C++ Programming Language 2.2 Fundamentals of C++ 2.3 Operation and Operator PENTAKSIRAN (ASSESSMENT)
2,3
vi
KANDUNGAN (CONTENT) 3. CONTROL STRUCTURES 3.1 Introduction to Control Structures 3.2 Selection Structures 3.3 Repetition Structures 3.4 break, and continue statements
PENTAKSIRAN (ASSESSMENT)
TEST 1 8-10 4. FUNCTIONS 4.1 Introduction to Functions 4.2 Benefits of Modular Design 4.3 Function Categories 4.4 Function Elements 4.5 Variable Scopes 5. ARRAYS & STRING 5.1 Introduction 5.2 Declarations 5.3 Initialization 5.4 Passing to Functions 5.5 Two-Dimensional Arrays TEST 2 13 6. STRUCTURES 6.1 Introduction to Structures 6.2 Structure Declaration & Initialization 6.3 Passing Structures to Functions
11,12
14
7. POINTERS 7.1 Introduction to Pointers 7.2 Pointer Declarations 7.3 Passing Pointers to a Function
STUDY WEEK
TUGASAN / PROJEK (ASSIGNMENT / PROJECT) One group project will be given, which the students must solve a case study by developing an application based on the software development method (SDM), C++ language and Microsoft Visual C++.
vii
PENILAIAN (ASSESSMENT) : 1. 2. 3. 4. 5. 6. 7. Kuiz (Quizes) Tugasan (Assignment) Ujian 1 (Exam#1) Ujian 2 (Exam#2) Projek (Project) Lain-lain (Others Lab Reports) Peperiksaan Akhir (Final Examination) Jumlah (Total) : : : : : : : : 5% 0% 10 % 10 % 15 % 20 % 40 % 100 %
RUJUKAN (REFERENCES) : 1. 2. 3. 4. D.S. Malik. (2009). C++ Programming: From Problem Analysis to Program Design. 4th Ed. Course Technology, Cengage Learning. Boston, USA. S. Walter Problem Solving with C++, 7th. Edition. Addison-Wesley, 2009. Y.D. Liang Introduction to Programming with C++, Comprehensive Version. International Edition. Pearson Education, 2007. D.M. Etter, J.A. Ingber. Engineering Problem Solving with C++, 2th. Edition. Prentice-Hall, 2007.
KEHADIRAN / PERATURAN SEMASA KULIAH (LECTURE ATTENDANCE / REGULATION) (1) Pelajar mesti hadir tidak kurang dari 80% masa pertemuan yang ditentukan bagi sesuatu KURSUS termasuk KURSUS Hadir Wajib (HW) dan KURSUS Hadir Sahaja (HS).
Students must attend lectures not less than 80% of the contact hours for every COURSE including Compulsory Attendance COURSEs (Hadir Wajib HW) and Attendance Only COURSEs (Hadir Sahaja HS)
(2) Pelajar yang tidak memenuhi perkara (1) di atas tidak dibenarkan menghadiri kuliah dan menduduki sebarang bentuk penilaian selanjutnya. Markah sifar (0) akan diberikan kepada pelajar yang gagal memenuhi perkara (1). Manakala untuk KURSUS Hadir Wajib (HW), pelajar yang gagal memenuhi perkara (1) akan diberi Hadir Gagal (HG).
Students who do not fulfill item (1) will not be allowed to attend further lectures and sit for any further examination. Zero mark (0) will be given to students who fail to comply with item (1). While for Compulsory Attendance COURSEs (Hadir Wajib HW), those who fail to comply with item (1) will be given Failure Attendance (Hadir Gagal HG).
(3) Pelajar perlu mengikut dan patuh kepada peraturan berpakaian yang berkuatkuasa dan menjaga disiplin diri masing-masing untuk mengelakkan dari tindakan tatatertib diambil terhadap pelajar.
Students must obey all rules and regulations of the university and must discipline themselves in order to avoid any disciplinary actions against them.
(4) Pelajar perlu mematuhi peraturan keselamatan semasa pengajaran dan pembelajaran.
Student must obey safety regulations during learning and teaching process.
viii
MATRIK HASIL PEMBELAJARAN KURSUS DAN HASIL PEMBELAJARAN PROGRAM (COURSE LEARNING OUTCOMES AND PROGRAMME LEARNING OUTCOMES MATRIX) Course Learning Outcome and Programme Learning Outcome Matrix
Faculty: Programme: Course: Code: Faculty of Electrical & Electronics Engineering Bachelor in Electronic Engineering (Computer Engineering) with Honours Computer Programming BEC 10102
This template to be used together with: 1. Programme Educational (PEO) Objective
Compliance to PLO
No 1 Course Learning Outcomes Demonstrate the fundamental knowledge of C++ programming language for solving computer programming problems correctly. Organize good team work to solve problem based on given task of computer programming techniques and applications. Differentiate the computer programming techniques for latest electronic and computer engineering application. LO-1 x C3 X P4 X A3 LO-2 LO-3 LO-4 LO-5 LO-6 LO-7 LO-8 LO-9 LO-10 LO-11
Psychomotor
P1 P2 P3 P4 P5 P6 P7 Perception Set Guided Response Mechanism Complex Overt Response Adaptation Origination
Affective
Receiving Responding Valuing Organising Internalising
ix
BEC10102 Computer Programming Teaching & Learning Activities Plan Sem01 Session 12/13
Week 1. Lecture Session Duration: 1 hour BEC10102 Briefing on Lecture Session Lecture01: Software Development Principles Lecture Slide01_SDM Lab Session Duration: 3 hours Remark
2.
Lecture02: Introduction to C++ Language Lecture Slide02_Intro Lecture02: Cont Introduction to C++ Language Lecture Slide02_Intro
3.
Experiment M01: Self Exercise - SDM and Introduction to C++ Experiment M01: Problem Crafting - SDM and Introduction to C++
**Submission of Module01 (M01) lab report is a day after your lab session.
4.
5.
6.
Test01: (Duration - ONE hour) Topic SDM, Intro to C++ & Control Structures Lecture03: Control Structures Lecture Slide03_Repetition
**Submission of Module02 (M02) lab report is a day after your lab session.
7.
*Group Project (GP): Refer to the Handout for GP activities. *26/10/12 Eid Al-Adha
**Note: Contain of the report is as instructed in the module. Please read carefully the instruction section in laboratory instruction manual. Failure to do so will affect your grade for the lab report.
BEC10102 Computer Programming Teaching & Learning Activities Plan Sem01 Session 12/13
Week 8. Lecture Session Duration: 2 hours Functions Lecture Slide04_Functions Lab Session Duration: 3 hours Experiment M03: Self Exercise Functions, Arrays & Structure Remark
9.
10.
11.
Test02: (Duration: ONE hour) Topic Control Structures, Functions, Arrays & Strings Arrays & String Lecture Slide05_Arrays & Strings
**Submission of Module03 (M03) lab report is a day after your lab session.
12.
13.
14.
All group projects should submit their group project report on Friday of the week.
xi
BEC10102 Computer Programming Teaching & Learning Activities Plan Sem01 Session 12/13
CONTACT Name Mdm. Munirah Ab.Rahman Mdm. Zarina Tukiran Mdm. Siti Idzura Yusof Dr. Suhaila Sari Office Block C16 Room No: C15-00-5 Block C15 Room No: C15-00-25 Block Room No: Block C15 Room No: C15-00-25 Tel. 07-4537352 07-4537566 07-4537566 Email
munira@uthm.edu.my zarin@uthm.edu.my idzura@uthm.edu.my suhailas@uthm.edu.my
xii
TABLE OF CONTENTS
CHAPTER
CONTENT
PAGE
1
1 2 4 6 7 11 13
EXERCISE 1
17
17 21 24 25 26 27 32 36 39 43 45 46 52 56 58 63
EXERCISE 2
xiii
3 CONTROL STRUCTURES
3.1 3.2 Introduction Sequence Structure 3.2.1 3.2.2 3.2.3 3.2.4 3.2.5 3.3 Single Selection Structure with if statement Double Selection Structure with if-else statement Multiple Selection Structure with if-else statement Double Selection Structure using conditional operator Multiple Selection Structure using switch keyword
66
66 67 68 70 72 73 74 77 78 79 82 84 85 87 90
Repetition Structure 3.3.1 3.3.2 3.3.3 3.3.4 Repetition Structure using while statement Types of Repetition Structure Repetition Structure using for statement Repetition Structure using do-while statement
3.4 3.5
EXERCISE 3
4 FUNCTIONS
4.1 4.2 4.3 Introduction Benefits of Modular Design Functions Categories 4.3.1 4.3.2 4.4 Standard Library Functions User-defined Functions
97
97 98 98 99 100 101 101 106 109 118 118 118 121
Function Elements 4.4.1 4.4.2 4.4.3 Function Definition Function Call Function Prototype
4.5
EXERCISE 4
xiv
127
127 130 132 133 137 139 140 141 142 143 144 147 148 149 150 151 152 153 159 160 162 165
EXERCISE 5
6 STRUCTURES
6.1 6.2 Introduction Defining a Structure 6.2.1 6.2.2 6.3 Defining using struct keyword Defining using typedef keyword
172
172 173 174 175 178 180
xv
6.4 6.5
Initializing Structure Passing Structures to Functions 6.5.1 6.5.2 Pass individual members to function Pass entire structure to function
EXERCISE 6
7 POINTERS
7.1 Pointers 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.1.6 7.1.7 7.1.8 7.1.9 7.1.10 7.1.11 7.1.12 EXERCISE 7 Pointers Declaration The address of Operator The Dereferencing Operator Pointer Assignment The new operator Dynamic Variables Basic Memory Management The delete operator Dangling Pointers Automatic Variables Global Variables Pointer Reference Parameters
191
191 193 194 195 196 197 197 198 198 199 200 200 202 208
xvi
xvii
INTRODUCTION
This chapter introduces fundamentals of computer, the relationship between computers, computer software and computer programming. In addition, important steps to be taken to develop a software project are also addressed.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. 2. 3. Understand how computer works so that the requirements specification of computer application development is identified correctly. Describe the steps taken to develop a C++ program using software development method. Construct algorithm using pseudocode or flowchart to solve given problem.
LEARNING CONTENTS
1.1 Introduction
Nowadays, most of the computer programs have been embedded in various electrical and electronic devices such as washing machine, microwave, hand phone, rice cooker and others. This computer programs have been develop to ease humans burdens in doing their daily activities such as billing payment, booking transportation ticket, forecasting weather, communicating with others, and so on. Thus, the computer inventions and computer application makes human daily activities works faster and better. As engineering student, you should develop the ability to solve problems, and it is very likely that you will need to use computers for problem solving. Thus, the content of this unit is design in such a way you can develop your problem solution skills using a computer. To develop this problemsolving ability, you must have these three (3) tools: knowledge of computer basis, an understanding of problem-solving strategies and techniques and a programming language.
1.2
Electronic computer
A computer is an electronic device designed to perform operations specified with a set of instructions called a program. Operation that can be handle by computers are input and store data, process the stored data according to the instructions and produced output to its user. As you read further, you will find computers terms used in the explanation. Thus, table 1.1 lists all of the terms and their description used in this unit in order to help you familiarise with it. Table 1.1 Computer terms and description
Terms Hardware Description The physical aspect of the computer that can be seen. E.g.: monitor, keyboard, speaker, motherboard and etc. Software The invisible instructions that control the hardware and make it works. Such instructions are checking the hardware status, communicate between input and output devices and etc. E.g.: MS Word, BIOS, C and etc. Computer Memory Input Devices Devices that send data into the computer for further actions. E.g.: Keyboard, mouse, scanner and etc. Output devices Devices or peripherals that sends the processed data out from the computer. E.g.: Monitor, speaker, printer and etc. Devices that stores information for further process.
A computer includes both hardware and software. Fig. 1.1 illustrates the computer hardware that consists Central Processing Unit (CPU). A CPU consists of Arithmetic and Logic unit (ALU) and Control Unit (CU). ALU performs all arithmetic and logic function while CU directs and monitors overall operation of computer.
CU
Input device
ALU
Output device
Fig. 1.1 Computer Components There are two (2) types of memory which are internal memory and external memory. Internal memory stores information in a logically consistent format. The two (2) fundamental types of
internal memory are Read Only Memory (ROM) and Random Access Memory (RAM). External memory or sometimes refer as secondary storage is use as permanent storage for program and data. Example of external memory is hard drives, floppy disc, flash drive and etc. Input and output unit provide access to and from the computer. It is the interface to which peripheral devices such as keyboards, computer screen, and printers. Software refers to the programs that describe the steps we want the computer to perform. There are four (4) types of software that can control the hardware and make it work as stated in Table 1.2. Table 1.2 Types of Software
Types Operating System (OS) Description The collection of computer programs that control the interaction of the user and the computer hardware and that manage allocation of computer resources. Example of OS such as UNIX, Window XP, MS-DOS, and Macintosh. Device drivers Specialised software programs that allow input and output devices to communicate with the rest of the computer system. Every single device brand are supported by its driver. Usually many basic device drivers come with system software. Newer operating system recognises new hardware and automatically installs the driver. If the OS does not recognise new hardware, it will display message and ask user to install the driver from CD or floppy that comes iwth with the hardware. Utility programs This type of software known as service programs, perform tasks related to the control and allocation of computer resources. They enhance existing functions or provide services not supplied by other system software programs. Application programs This type of software is developed to assist a computer in accomplishing specific tasks. Such example is word processors; MS Word and WordPerfect, spreadsheet program; MS Excel and Lotus 123 and mathematical computation tools; MATLAB and Mathematica.
As described, software is a program that has instructions how computer perform task. You as a programmer write instruction or programs using computer programming language such C, Visual Basic, JAVA and etc. Without programs, a computer is just like an empty machine. Computers do not understand human language, so you need to use computer language to communicate with it. To understand how computers can be used, how applications work, how systems are configured, it is necessary for you to understand what programs are and how they are constructed.
1.3
Lets understand some basic concepts of programming before do the actual programming. A computer program is an organized list of instructions that, when executed, causes the computer to behave in a predetermined manner. Without programs, computers are useless. Therefore, programming means designing or creating a set of instructions to ask the computer to carry out certain jobs which is normally very much faster than human beings can do. Table 1.3 explicitly describe the relation between program, programming language, computer programming and programmers. Table 1.3 Terms and Descriptions
Terms Program Description A set of instructions that tells a computer how to perform a particular task. It describes the data and the sequence of steps. Programming Language Computer Programming Programmer A person who writes a program using a programming language. His/her job is to convert a solution to a problem into set of instructions understood by a computer. The programmer should also test the program to see whether it is working properly and corrective actions should be taken. An artificial and formal language that has a limited vocabulary consists of a set of keywords of making and providing a set of grammar rules to develop a program. The art or process of developing computer programs.
Usually, a lot of people think that computer is a very intelligent thing, which in actual fact it cannot do nothing without human assistance. The microchips of a CPU can only understand two distinct electrical states, namely, the ON and OFF states, or 0 and 1 codes in the binary system. Thus, the CPU can only understand combinations of 0 and 1 code, which is called machine language. Machine Language is known as the primitive language and it is extremely difficult to learn. However, this task has been simplified by smarter programmers who wrote interpreters and compilers such as BASIC, COBOL, JAVA, C, C++ and etc, that able to translate human language-like programs into machine language so that the computer can carry out the instructions entered by the users.
1.4
1.5
10
1.6
Case Study 3: Write a program to find the voltage across a 200 ohm resistor carrying 3A using Ohms law.
1. 2.
3.
Design
Calculate the voltage across a 200 ohm resistor carrying 3A using Ohms law. Then display the result. Data Input Current, I = 3 Resistance value, R = 200 Data Output Voltage, V Formula V=IxR Constrain Nil Using Pseudocode Begin Assign I = 3 Assign R = 200 Calculate V=IxR Display V End
11
4.
Implementation **Type your program in editor window. You will use Microsoft Visual C++ software. /* Date Created: 1 Sept 2011 Date Modified: 12 Sept 2011 Description: Calculate & display voltage across a 200 ohm resistor carrying 3A using Ohms law. */ #include<iostream> using namespace std; void main() { int V, I, R; //declares variables I=3; //set current value R=300; //set resistance value V=I * R //Calculate voltage, V=IxR
//Display the result cout<< Voltage across a 200 ohm resistor carrying 3 A is << V << V; //newline cout<<endl; } 5. Verification & Testing **Then, execute the program by clicking Run button or from Build menu. What you need to do to verify the output? Check the value obtained from the program agains your own calculation; e.g. using a calculator. Verify your answers with your peers; do they get the same results as you for the same data.
12
EXERCISE 1 Answer question 1 to question 3 using the first three (3) steps of Software Development Method. 1. Construct a C++ program that displays Nasi Lemak Kopi O. 2. Construct a C++ program that repeatedly displays Nasi Lemak Kopi O for 10 times. 3. Construct a C++ program asks a user whether they want to display a message or not. Displays the message This is my C++ program! if and only if the user chooses to proceed. Otherwise, end the program. 4. Construct a C++ program that can read and display two integer numbers. 5. Construct a C++ program that can multiply five integer numbers. 6. Based on question 5, determine whether the multiplication result is positive or negative value. If the result is negative value, display a message The result is a negative value. Otherwise, display a message The result is a positive value. Design algorithms for question 7 to question 11 using flowchart. 7. Construct a C++ program that able to find total price of two items. Then display the total price. 8. Construct a C++ program that allows a user to enter the price of five (5) items. Then get the average price. 9. Design a C++ program that able to calculate total mark after a user inserting their carry mark and final mark. 10. Reconstruct question 2. This time displays the message as many as user requests. 11. Design a C++ program that calculates and displays the average performance for each class. Use the following formula to find the average. = ( + + + + )
where x is a total mark and n is a number of student in each class. 12. Convert the following pseudocode to flowchart. Begin 1. read no1 and no2 2. while no1 == no2 2.1 repeat step 2 3. if no1>no2 3.1 greater = no1 else 3.2 greater = no2 4. display greater End
13
13. Transform the following source code to pseudo code. //Program 1.1: Calculating the net salary #include <iostream> void main() { float gross, tax, net; cout<<Gross salary:; cin>>gross; tax=0.14 * gross; net = gross tax; cout<<Taxes withheld: << tax; cout<<endl; cout<<Net salary: << net; cout<<endl; } //Program 1.2: Calculating the area using formula (base x height) / 2 #include <iostream> main() { float base, height, area; cout<<Base:; cin>>base; cout<<Height:; cin>>height; area=(base*height)/2; cout<<Area: <<area; cout<<endl; return 0; } //Program 1.3: Determine smallest value between two integer numbers #include <iostream> main() { int count, n, num1, num2, smaller; cout<<\nPlease enter the first number:; cin>>num1; cout<<\nPlease enter the second number:; cin>>num2; if(num1<=num2) smaller=num1; else smaller=num2; cout<<\nThe smaller number is <<smaller<<endl; return 0; }
14
//Program 1.4: Determine smallest value between two integer numbers #include <iostream> main() { int count, n, num1, num2, smaller; cout<<How many pairs of numbers:; cin>>n; for(count=1; count<=n; ++count){ cout<<\nPlease enter the first number:; cin>>num1; cout<<\nPlease enter the second number:; cin>>num2; if(num1<=num2) smaller=num1; else smaller=num2; cout<<\nThe smaller number is <<smaller<<endl;} return 0; } 14. Design an algorithm for the following program output.
REFERENCES
Andy M. Tyrell, Stephen L. Smith and Jonathan A. Dell. The Essence of C for Electronic Engineers. Europe: Prentice Hall, 2011.
15
16
CHAPTER 2
INTRODUCTION
This chapter is concerned with the basic elements used to construct simple C++ statements. These elements include identifiers, keywords, data types, constants, variables, declarations, expressions and statements. How these basic elements can be combined to form more comprehensive program components is also addressed.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. 2. 3. Familiarise C++ program components in order to construct a complete C++ program. Identify suitable data types, operators, expressions, pre-processor directives and C++ statements to develop a C++ program. Develop a simple C++ program using Microsoft Visual C++ software.
LEARNING CONTENTS
2.1 Introduction
What is computer programming? A computer program or a program is a sequence of statements whose objective is to accomplish a task. What is programming? Programming is a process planning and creating a program.
17
18
19
20
2.2
Comments
21
22
23
2.3
Special Symbols
24
2.4
Reserved Keywords
25
2.5
Identifiers
26
2.6
Data Types
27
28
29
30
31
2.7
32
33
34
35
2.8
36
37
38
2.9
Expressions
39
40
41
42
2.10
Type Conversion
43
44
2.11
String Type
45
2.12
Data Input
46
There are two (2) ways to declare constant data; using const keyword and using #define. The following shows how to do the declaration for both methods.
47
48
49
50
51
2.13
Output
52
53
54
55
2.14
56
57
2.15
Preprocessor Directives
58
59
60
61
2 3
EXERCISE 2 1. Get the result for the following arithmetic operation of (a) to (e). Show your step-by-step solution. Assume all variables are declared correctly. (a) x = 20/5+(10-10) * 2; (b) int a=1, b=2, k=3, m=4; a+=b+k; b*=k=m+5; (c) z=8+2*(-2); (d) a=10/3+7%2; (e) b=7 - + ++2 % (3 + -3); 2. Determine the result of statement (a) to (d). (a) (4<40) && (3<30) (b) (5<50) || (3>30) (c) int a=1, b=2, c=3; a>b && c<a a<!b || !!a a+b < !c+c a-x || b*c && b/a (d) int a=1, b=2, k=3; a==b a!=b (a+b+c) == (-2*-k) 3. Find the following program output. #include <iostream> using namespace std; void main(){ int a, b=1, c=1; a=++b + ++c; cout<<Value a: << a << Value b: <<b<< Value c: <<c <<endl; a=b++ + c++; cout<<Value a: << a << Value b: <<b<< Value c: <<c <<endl; a=++b + c++; cout<<Value a: << a << Value b: <<b<< Value c: <<c <<endl; a=b-- + --c; cout<<Value a: << a << Value b: <<b<< Value c: <<c <<endl; }
4. Write a single C++ statement for the following statement: (a) Declare and assign a character data to a variable named category.
63
(b) display a value with two (2) floating points of a variable named AverageMark where
AverageMark = total_mark/number-of_student
5. Predict the output of the following C++ code. #include<iostream> using namespace std; void main(){ int a=10; cout<< A is << ++a; cout<<endl; a--; cout<<Now A is << --a + a++; cout<<endl; }
6. Solve the following problem statements. (a) Given a=-10 and b=20. Find the value of c where c=a+++b-a-(b) Given a=4 and b=9. Find the value of k for k=++a-2+b (c) Given v1=4 and v2=8. What is the value of v1 and v2 after executing the following statement? v1=v1++; v2=--v2; 7. Find and fix errors, if any. #include <iostream> using namespace std; Main() int 1_num, 2_num, total; Read 2 numbers cout<<Enter two numbers:; cin>>1_num; cin>>2_num; Calculate and display the result 1_num + 2_num = total; cout<< \nThe total of two numbers: << total << endl; } /*declare all variables
REFERENCES D.S. Malik. C++ Programming: From Problem Analysis to Program Design. 4th Ed.. Course Technology, Cengage Learning. Boston, USA. 2009
64
65
CHAPTER 3
3 CONTROL STRUCTURES
INTRODUCTION
The previous chapter discussed the programs that were executed in the same order in which they appeared within the program. However this type of programs are unrealistic because they do not include tests to determine whether conditions is met or not, repeated execution is required or not and execution of individual groups of statements on selective basis is involved or not. Thus, this chapter introduce the concept of control structure; selection and repetition control structure in order to construct a realistic C++ program that may require a logical test to be carried out at some particular point within the program.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. Understand the concept of control structures in order to control the program. 2. Use suitable selection statement to control the execution of the program. 3. Use suitable loop statement to control the repetition of the program. 4. Understand the use of break and continue keyword in order to control the execution of the program.
LEARNING CONTENTS
3.1 Introduction
In structured programming, there are three (3) structures; sequence structure, selection structure and repetition structure. The description of each structure is as follows. Sequence structure: execute one command right after another in order. Selection structure: one execution branch or another (but not both). Repetition structure: sometimes called iterative structure which repeating one section of command(s) multiple times.
66
3.2
Sequence Structure
67
3.2.1
68
69
3.2.2
70
71
3.2.3
72
3.2.4
73
3.2.5
74
75
76
3.3
Repetition Structure
77
3.3.1
There are three (3) repetition statements; while statement, for statement and do-while statement.
78
3.3.2
There are three (3) types of repetition structure; counter-controlled, sentinel-controlled, and flagcontrolled. These three (3) types of repetition structure can be applied with while statement, for statement and do-while statement. The following example shows how to apply each type using
while statement.
79
80
81
3.3.3
82
83
3.3.4
84
3.4
break statement
85
sum=0; isNegative=false; cin >> num; while (cin && !isNegative) { if (num<0) { cout<<Negative number found in the data. << endl; isNegative=true; } else { sum+=num; cin>>num; } }
Figure 3.1 using flag-controlled
86
By using break statement in the above program, it can eliminate the use of certain (flag) variables. Figure 3.2 gives similar output as shown in Figure 3.1.
continue statement
87
88
89
EXERCISE 3 1. Translate the following C++ code into an algorithm (a) cout<< Enter an integer:; cin >> number; if (number%5==0) cout << Hi5 << endl; if (number%2==0) cout << Hi2 << endl; (b) if (rad>=0){ Area=rad*rad*PI; cout << Area << endl; } cout << Good day\n switch(x+3){ case 6: y=1; default: y+=1; } switch(x+3){ case 6: y=1; break; default: y+=1; } if (i>j){ if (i>k) cout << Good morning\n;} else cout << Good afternoon\n; cout<< Enter circuit orientation:S (series) or P (parallel):; cin >> orient; if ((orient== S)||( orient== s)){ LR=L1+L2+2*M; cout << Relative inductance is << LR << endl;} else if ((orient== P)||( orient== p)){ LR=(L1 + L2 + sqrt(M)) / (L1 + L2 2 * M) ; cout << Relative inductance is << LR << endl;} else cout<< Invalid selection!!!<<endl;
(c)
(d)
(e)
(f)
2. Find and fix errors in the following C++ code (if any). Assume all variables used in the code are declared properly. (a) if i=2 cout<< The value of i is 2\n; else cout<< The value of i is not equal to 2\n; (b) if (age>=65); cout<< Age is greater than or equal to 65\; else cout<< Age is less than 65\n;
90
(c)
3. Rewrite the following if statement to a switch statement. (a) if (a==1) x+=5; else if (a==2) x+=10; else if (a==3) x+=15; else if (a==4) x+=20; (b) if ((orient== S)||( orient== s)){ LR=L1+L2+2*M; cout << Relative inductance is << LR << endl;} else if ((orient== P)||( orient== p)){ LR=(L1 + L2 + sqrt(M)) / (L1 + L2 2 * M) ; cout << Relative inductance is << LR << endl;} else cout<< Invalid selection!!!<<endl;
4. Analyse the following code. Determine the output of the program. Assume all variables used in the code are declared properly. (a) //Assuming number is 30 if (number % 2 ==0) cout<< number << is even. << endl; cout<< number << is odd. << endl; //Assuming number is 30 if (number % 2 ==0) cout<< number << is even. << endl; else cout<< number << is odd. << endl; //Suppose x=3 and y=2. if (x>2){ if (y>2){ z = x+y; cout<< z is << z << endl;} } else cout<< x is << x << endl; //Assuming x=5 and y=8, what will be the output produced. if (y==8) if (x==5) cout<< @@@@ << endl; else cout<< #### << endl; cout<< $$$$ << endl; cout<< &&&& << endl;
(b)
(c)
(d)
91
(e)
//Assuming L1=2, L2=3, M=2 and orient is P. cout<< Enter circuit orientation:S (series) or P (parallel):; cin >> orient; if (orient= S){ LR=L1+L2+2*M; cout << Relative inductance is << LR << endl;} else if (orient== P) { LR=(L1 + L2 + sqrt(M)) / (L1 + L2 2 * M) ; cout << Relative inductance is << LR << endl;} else cout<< Invalid selection!!!<<endl;
5. Find and fix errors in the following C++ code (if any). (a) //The following code should output the odd integers from 999 to 1 for(x=999; x>=1; x+=2) cout<< x << \t; (b) //The following code should output the even integers from 2 to 100 counter=2; Do{ if (counter%2 == 0) cout<<counter<<endl; counter+=2; } While (Counter < 100) (c) //The following code should sum the integers form 100 to 150 total = 1; x=100; while(x<=150){ total+=x; x++;} 6. Count number of iteration in the following loops. (a) int count=0; while(count<=n){ count++;} (b) count=5; do{
92
7. Determine the output of the following program. (a) int balance=1000; while(true){ if(balance<9) break; balance=balance-9;} cout<< Balance is <<balance<<endl; (b) int balance=1000; while(true){ if(balance<9) continue; balance=balance-9;} cout<< Balance is <<balance<<endl; 8. Convert the following loop to dowhile loop. int sum=0; int number; cin>>number; while (number!=0){ sum+=number; cin>>number;} cout<<sum;
9. Convert the following loop to a while loop and dowhile loop. sum=0; for (c=0; c<=1000; c++) sum=sum+c;
93
10. The for loop on the left is converted into the while loop on the right. What is wrong? Correct it. for (int i=0; i<4;i++){ if (i%3==0) continue; sum+=i; } } int i=0; while(i<4){ if (i%3==0) continue; sum+=i; i++;
Programming 11. Construct a C++ program that reads an integer and checks whether it is odd. In addition, your program should looks something like the following output: The output for 1 run: Enter an integer: 20 Is 20 an odd number? false
nd st
12. Solve the following linear equations. You can use Cramers rule to solve the following 2x2 system of linear equation.
+ + = =
= =
Construct a C++ program that prompts the user to enter a, b, c, d, e and f and display the result. If ad-bc=0, display a message The equation has no solution.
94
Chapter 3 : Control Structures 13. Solve the following quadratic equations. The two roots of a quadratic equation ax2+bx+c=0 can be obtained using the following formula.
1=
+ 2 2
r2 =
Construct a C++ program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. The discriminant of the quadratic equation is b2 - 4ac. If the discriminant is positive, display two roots. If the discriminant is 0, display one root. Otherwise, display The equation has no real roots. 14. Create a C++ program that able to print out a temperature conversion table form degrees in Celsius to degree in Fahrenheit when the temperature varies in the range of -10 to 40 degrees in Celcius with an incremental step size of 1 degree. The relationship is as follows:
f = (9/5)c + 32
where c is the temperature in Celsius and f is the temperature in Fahrenheit. 15. Modify the following program so that the program is allows the user enters an operator and then performs basic mathematical operation (+, -, x, /) for two random numbers in the range from 1 to 10. For example, user enters + operator, therefore two random numbers are added. Enters operator, two random numbers are subtracted. #include<iostream> #include<ctime> using namespace std; void main(){ int r1,r2; //Generate different random numbers at each run srand ( time(NULL) ); //Generate two random integer numbers ranging from 1 to 10 for (int i=1; i<=10; i++){ r1=rand()%10; r2=rand()%10; cout<<r1<< "\t" << r2 << endl;} }
REFERENCES
D.S. Malik. C++ Programming: From Problem Analysis to Program Design. 4 Technology, Cengage Learning. Boston, USA. 2009.
th
Ed.. Course
95
96
Chapter 4 : Functions
CHAPTER 4
4 FUNCTIONS
INTRODUCTION
This chapter is concerned with the structure of programs consisting of more than one function. The distinction between local variables that are recognised only within a single function and global variables that are recognised in two or more functions are also addressed.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. Understand the concept of modular programming. 2. Create functions, invoke functions and pass arguments to a function. 3. Identify suitable scope of variable used in the program.
LEARNING CONTENTS
4.1 Introduction
The complexity of the programming problems increases becomes more and more difficult to consider the solution as a whole. The best way to develop and maintain a large program is to organize a program into several smaller routines called functions. One of these functions must be called main(). The main() function is always the first to execute. It does not need to be first in a program, but it usually is. In designing such program that contains several functions in it, you can apply either top-down design or bottom-up design. However, in this lecture, we will focus on top-down design. The topdown design specifies the process of identifying first the major tasks then further subtasks within them. The later process is also known as functional decomposition or stepwise refinement.
97
Chapter 4 : Functions
4.2
4.3
Functions Categories
There are two (2) categories of functions; standard library functions and user-defined functions.
98
Chapter 4 : Functions
4.3.1
99
Chapter 4 : Functions
4.3.2
User-defined Functions
100
Chapter 4 : Functions
4.4
Function Elements
In C++, there are three (3) function elements; function definition, function prototype and function call. 4.4.1 Function Definition Function definition has two (2) principle components; function header and function body. The following format is a general format for function definition.
101
Chapter 4 : Functions
102
Chapter 4 : Functions
103
Chapter 4 : Functions
104
Chapter 4 : Functions
105
Chapter 4 : Functions
4.4.2
Function Call
106
Chapter 4 : Functions
107
Chapter 4 : Functions
108
Chapter 4 : Functions
4.4.3
Function Prototype
109
Chapter 4 : Functions
110
Chapter 4 : Functions
111
Chapter 4 : Functions
112
Chapter 4 : Functions
113
Chapter 4 : Functions
114
Chapter 4 : Functions
115
Chapter 4 : Functions
116
Chapter 4 : Functions
117
Chapter 4 : Functions
4.5
Variables Scope
Variable scope is the part of the program where the variable can be referenced. There are two (2) types of variable scope; local variable and global variable. 4.5.1 Local Variable
4.5.2
Global Variable
118
Chapter 4 : Functions
119
Chapter 4 : Functions
120
Chapter 4 : Functions
EXERCISE 4 1. Analyse the following code. Determine the output of the program. (a) #include <iostream> using namespace std; char mystery (int first_par, int second_par); void main(){ cout<<mystery(10,9) << ow\n; cout<<endl; } char mystery (int first_par, int second_par){ if (first_par >= second_par) return W; else return H; } /*The following code creates a header file named MyCalculator.h. This file defines a function named calculate that returns areaCylinder. */ double calculate (double h, double r){ double areaCylinder = 0.00; const double PI=3.142; areaCylinder =PI * h * r * r; return (areaCylinder); } /*The following code creates a file named UseMyCalculator.cpp. This file contains a main function for testing the calculate function. */ #include <iostream> #include MyCalculator.h using namespace std; int main(){ double cyl; cyl = calculate (2.0, 4.0); cout<< "The cylinder area is " << cyl ; cout<< m2 << endl; return 0; } #include<iostream> void friendly(); void shy(int audience_count); int main(){ using namespace std; friendly(); shy(6); cout<< One more time:\n; shy(2); friendly(); cout<< End of program.\n; return 0; } void friendly(){ using namespace std; cout<< Hello\n; }
(b)
(c)
121
Chapter 4 : Functions
void shy(int audience_count){ using namespace std; if (audience_count<5) return; cout<< Goodbye\n; } (d) /*The following code creates a header file named MyMax.h. This file defines two functions named Mmax and display_Max that returns max value and displays it. */ #include<iostream> using namespace std ; int Mmax (int num1, int num2){ cout << "Max number between "<<num1; cout <<" and "<<num2<<" is "; if (num1>num2) return num1; else return num2; } void display_max(int m){ cout<< m<<endl; } /*The following code creates a file named FindMax.cpp. This file contains a main function for testing the calculate function. */ #include <iostream> #include MyMax.h int main(){ display_max(Mmax(4,10)); return 0; } #include<iostream> void figure_me_out(int& x, int y, int& z); int main(){ using namespace std; int a, b, c; a=10; b=20;c=30; figure_me_out (a, b, c); cout<<a<< << b << << c <<endl; return 0; } void figure_me_out(int& x, int y, int& z){ using namespace std; cout<<x<< << y << << z <<endl; x=1 ; y=2 ; z=3 ; cout<<x<< << y << << z <<endl; } #include<iostream> #include<cmath> using namespace std; double calculate2(int y, int z){ double m;
(e)
(f)
122
Chapter 4 : Functions
m = sqrt(pow(y /=2, z -= 10)); cout<< Calculate2: <<pow(m,z) <<endl; return m; } double calculate1(int w, int x){ double n; n = calculate2(w += 12, x *=2); cout<< Calculate1: << sqrt(n + x)<<endl; return n; } void main(){ double answer; int a = 36, b = 6; answer = calculate1(a,b); cout<< Main: << answer <<endl; } 2. Identify and correct the errors in the following program. (a) int function1(int n){ cout<<n; } function2(int n, m){ m += N; function1(3.4); } (b) void p (int I){ int I=5; cout<< I is << I << endl; } 3. Write a C++ statement of function declarations and function definition for the following problem statement. (a) A function named sumAll that takes three arguments, all of type int, and that returns the sum of its three arguments. (b) A function named AverageNum that takes one argument of type int and one argument of type double, and that returns a value of type double that is the average of the two arguments. (c) A function named findChar that takes one argument of type double. The function returns the character value P if its argument is positive and returns N if its argument is zero or negative. (d) A function named read_filter has no parameters and returns a value of type double. The function read_filter prompts the user for a value of type double and reads the value into a local variable. The function returns the value read provided this value is greater than or equal to zero and returns zero if the value read is negative.
123
Chapter 4 : Functions
4. Write C++ statement of function definition for the following problem statement. (a) A function named in_order that takes three arguments of type int. The function returns
true if the three arguments are in ascending order; otherwise, it returns false. For
example, in_order(1,2,3) and in_order(1,2,2) both return true, while in_order(1,3,2) returns false. (b) A function named even that takes one argument of type int and returns a bool value. The function returns true if its one argument is an even number; otherwise it returns false. (c) A function is_digit takes one argument of type char and returns a bool value. The function returns true if the argument is a decimal digit; otherwise it returns false. (d) A function is_root takes two argument of type int and returns a bool value. The function returns true if the first argument is the square root of the second; otherwise, it returns
false.
5. Answer the following: Suppose you have two function definitions with the following function declarations. Which function definition would be used in the following function call and why would it be the one used? (a) double score(double time, double distance); int score(double points) ; (b) double ans(double data1, double data2) ; double ans(double time, int count) ; /*Assume x is of type double*/ Final_score=score(x) ; /*Assume X and y are of type
double*/
X=ans(y, 6.0); (c) double ans(double data1, double data2) ; double ans(double time, int count) ; X=ans(5,6);
(d)
double ans(double data1, double data2) ; double ans(double time, int count) ;
X=ans(5, 6.0);
6. Answer (a) to (d) based on the following function definition. Line 1 Line 2 Line 3 Line 4 Line 5 int calculate ( int y) { int n, times = 2, product; for( n = y; n <= 6; n++) product = n * times; return product; }
(a) State functions name, return value, parameter and returns value type. (b) Write a suitable C++ statement of function prototype for the above function definition.
124
Chapter 4 : Functions
(c) What the value returns by calculate to the calling function when it is call with a value of 2? (d) Modify some lines of above code to ensure that the function receives but does not return any value to the calling function and displays the value of product.
Programming 7. Write a header file that contains the following two functions. /*Convert from feet to meter*/ double foot2Meter(double foot) /*Converts from meters to feet*/ double meter2foot(double meter) The formula for the conversion is:
meter = 0.305 x foot
Implement the header file and write a complete C++ program that invokes these functions to display the
Feet 1.0 2.0 9.0 10.0
following tables:
Meters 0.305 0.61 2.745 3.05 | | | | | | Meters 20.0 25.0 60.0 65.0 Feet 65.574 81.967 196.721 213.115
8. Write two functions to do the following: The first function calculates the energy needed to heat water from an initial temperature to a final temperature. The formula to compute the energy is:
where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is measured in joules. The second function displays the calculated energy. Write a program that prompts the user to enter the water amount in kilograms and its initial and final temperatures. Then calculates and displays its energy.
REFERENCES
Y. Daniel Liang. Introduction to Programming with C++: Comprehensive Version. Pearson Education. Upper Saddle River, USA, 2007.
125
Chapter 4 : Functions
126
CHAPTER 5
INTRODUCTION
This chapter discussed the manner in which arrays are defined and processed, the passing arrays to functions and the use of multidimensional arrays. Both numerical and character-type arrays are considered in the discussion.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. Understand the concept of arrays in order to use it within a C++ program. 2. Differentiate the method used for numerical and character-type arrays in solving problem. 3. Apply the array operations that can be performed on numerical and character data within a C++ program.
LEARNING CONTENTS
5.1 Introduction
127
128
129
5.2
Array Declaration
131
5.3
Array Subscript
132
5.4
133
134
135
136
5.5
5.6
Two-dimensional Arrays
139
5.7
140
5.8
141
5.9
142
5.10
143
5.11
144
145
146
5.12
Strings Declaration
147
5.13
Strings Initialization
148
5.14
149
5.15
150
5.16
151
5.17
152
5.18
153
154
155
156
157
158
5.19
159
5.20
160
161
5.21
162
163
164
EXERCISE 5 1. Mark the following statement as T (True) or F (False). (a) A double type is an example of a simple data type. (b) A one-dimensional array is an example of a structured data type. (c) The index value specifies the position of the component in the array. (d) Arrays can be passed as parameters to a function either by value or by reference. (e) A function can return a value of type array. (f) The size of an array is determined at compile time. (g) Given the declarations:
int list[10];
the statement:
list[5]=list[3]+list[2];
updates the content of the fifth component of the array list. (h) If an array index goes out of bounds, the program always terminates in an error. 2. Write C++ statements to do the following. (a) Declare an array alpha of 15 components of type int. (b) Output the value of the tenth component of the array alpha. (c) Set the value of the fifth component of the array alpha to 35. (d) Set the value of the ninth component of the array alpha to the sum of the sixth and thirteenth components of the array alpha. (e) Set the value of the fourth component of the array alpha to three times the value of the eight components minus 57. (f) Output alpha so that five components per line are printed. 3. Consider the following function headings
void funcOne (int alpha[], int size); int funcSum (int x, int y); void funcTwo (const int alpha[], int beta[]);
165
Write C++ statements to do the following. (a) Call the function funcOne with the actual parameters, list and 50, respectively. (b) Print the value returned by the function funcSum with the actual parameters, 50 and the fourth component of list, respectively. (c) Print the value returned by the function funcSum with the actual parameters, the thirtieth and tenth components of list, respectively. (d) Call a function funcTwo with the actual components, list and alist respectively. 4. Suppose num is an array of five components of type int. What is stored in num after the following C++ code executes?
for(i=0; i<5; i++){ num[i]=2*i+5; if (i%2==0) num[i]=num[i]-3; }
5. Suppose list is an array of six components of type int. What is stored in list after the following code executes?
list[0]=0; for(i=1; i<6; i++){ list[i]=i*i+5; if (i>2) list[i]=2*list[i]-list[i-1]; }
#include<iostream> using namespace std; int main(){ int count, alpha[5]; alpha[0]=5; for(count=1; count<5; count++){ alpha[count]=5*count+10; alpha[count-1]=alpha[count]-4; } cout<< List elements:; for(count=0; count<5; count++) cout<<alpha[count]<< <<endl; return 0; }
166
#include<iostream> using namespace std; int main() { int j, one[5], two[10]; for(j=0; j<5; j++) one[j]=5*j+3; cout<< One contains:; for(j=0; j<5; j++) cout<<one[j] << <<endl; for(j=0; j<5; j++){ two[j]=2*one[j]-1; two[j+5]=one[4-j]+two[j]; } cout<< Two contains:; for(j=0; j<10; j++) cout<<two[j]<< <<endl; return 0; }
declares LocationName to be an array of 9 characters because the string Nice Day has only 8 characters. (b) The declaration:
mark the following statements as valid or invalid. If a statement is invalid, explain why.
167
(a) strcpy (string15, Hello there); (b) strlen (string15); (c) string15= Batu Pahat; (d) cin>>string15; (e) cout<<string15; (f) if (string15>= Good day) cout<<string15; (g) string15[6]=t; 10. Given the declaration:
mark the following statements as valid or invalid. If a statement is invalid, explain why. (a) str1=str2; (b) if (str1==str2) cout<< Both strings are of the same length. << endl; (c) if (strlen(str1)>=strlen(str2)) str1=str2; (d) if (strcmp(str1, str2)<0) cout<< str1 is less than str2.<< endl; 11. Given the following declaration.
char name[8]= Shelly;
mark the following statements as Yes if they output Shelly. Otherwise, mark the statements as No and explain why it does not output Shelly. (a) cout<<name; (b) for (int j=0; j<6; j++) cout<<name[j]; (c) int j=0; while(name[j]!= \0) cout<<name[j++]; (d) int j=0; while (j<8) cout<<name[j++]; 12. Given the declaration.
char str1[21], str2[21];
168
Write C++ statements to do the following. (a) Receives Sunny Day via keyboard and stores in str1. (b) Stores the length of str1 into the int variable length. (c) Copies the value of name into str2. Assume name is an array of string. (d) Outputs str1 if str1 is less than or equal to str2, and otherwise outputs str2. 13. Assume the following declarations.
char name[21]; char yourName[21]; char friendName[21];
mark the following statements as valid or invalid. If a statement is invalid, explain why. (a) cin>>name; (b) cout<<friendname; (c) yourName[0]= \0; (d) yourName=friendName; (e) if (yourName==name) friendName=name; (f) int x=strcmp(yourName,friendName); (g) strcpy(friendName, name); (h) for (int j=0; j<21; j++) cout<<name[j]; 14. Answer (a) and (b). (a) By using a diagram, explain the differences between the following two arrays. char s1[] = {a, b, c}; char s2[] = abc; (b) The following C++ program contains several errors. #include<iostream> using namespace std; void main(){ char addr[]= "UTHM"; char state[]="Johor"; char s3[5]; int i=0; cout<<strcpy(s3[i],strcat(addr[i],state[i]))<<endl;
169
return;}
(i) Rewrite the above program so that the program is free from errors. (ii) Predict the program output after (i) is executed.
Programming 15. Construct a C++ program that prompts the user to enter n numbers, and displays the standard deviation of numbers. Use eq.(1) and eq.(2) to find the standard deviation of numbers.
x
mean=
i =1
x1 + x 2 + ... + x n n
eq.(1)
(x
deviation =
i =1
mean) 2 n 1
e.q.(2)
Source: Final Exam Sem1 Session1011
REFERENCES
Y. Daniel Liang. Introduction to Programming with C++: Comprehensive Version. Pearson Education. Upper Saddle River, USA, 2007. .
170
171
Chapter 6: Structures
CHAPTER 6
6 STRUCTURES
INTRODUCTION
This chapter is concerned with the use of structures within a C++ program. How structure are defined, and how their individual members are accessed and processed within a program is also discussed. In addition, the relationships between structures and pointers, arrays and functions are also examined.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. Understand the concept of structures in order to use it within a C++ program. 2. Apply correct C++ statement to defined and accessed members of the structure. 3. Construct a C++ program with the use of structures within the program.
LEARNING CONTENTS
6.1 Introduction
172
Chapter 6: Structures
6.2
Defining a Structure
173
Chapter 6: Structures
6.2.1
174
Chapter 6: Structures
6.2.2
175
Chapter 6: Structures
176
Chapter 6: Structures
177
Chapter 6: Structures
6.3
Members of Structure
178
Chapter 6: Structures
179
Chapter 6: Structures
6.3.1
180
Chapter 6: Structures
6.4
Initializing Structure
181
Chapter 6: Structures
182
Chapter 6: Structures
183
Chapter 6: Structures
6.5
6.5.1
184
Chapter 6: Structures
6.5.2
185
Chapter 6: Structures
186
Chapter 6: Structures
EXERCISE 6 1. Answer (a) to (d). (a) (b) (c) (d) Define an object in C++. Give an example. Define a class in C++. Give an example. Define a member function in C++. Give an example. Explain briefly the relationship between object, member function and class in C++.
2. Write C++ statements of structure declaration using (a) struct keyword and (b) typedef keyword.
3. Write C++ statements of structure declaration using struct keyword. This structure should be able to store a record of five students information that consists of: (a) Test Marks for Exam1 and Exam 2. (b) Total Marks where the total marks is a summation marks of Exam1 and Exam2. 4. Answer (a) and (b) based on following structure.
struct marks{ float Test1, Test2, FinalExam; int Total_Marks; char grade; }; Exams_Mark student1, student2;
(a) Label. (i) structure tag; if any. (ii) members of the structure, if any. (iii) structure variable, if any. (b) Define the following. (i) structure tag, (ii) members of the structure, and (iii) structure variable.
187
Chapter 6: Structures
5. Find and fix error(s) in the following structure definition and declaration.
6. Propose C++ code fragment to define the structure named device, containing the character array deviceName[10], the integer year_of_purchase, and a structure variable dv of type array with size 5. 7. Given the following structure definition.
(a) Declare old_Theater of type Theater. (b) Write a statement that will set the title of the theater to Puteri Gunung Ledang, the location to Istana Budaya and the capacity of the theater to 1500. 8. Write a function definition corresponding to the following function declaration. void display_theather_record(Theater& ot); //display theaters record on the screen. 9. Give two advantages of implementing structures in the program. Explain briefly each of it.
188
Chapter 6: Structures
Programming 10. Write a grading program for your class that has the following grading policies using C++ programming language. There are two quizzes, each graded on the basis of 10 points. There are one midterm exam and one final exam, each graded on the basis of 100 points. The final exam counts for 50% of the grade, the midterm counts for 25%, and the two quizzes together count for a total of 25%. (You need to normalize the quiz scores by converting to percent before averaged.) Any grade of 90 or not more than 100 is an A, any grade of 80 or more (but less than 90) is a B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any grade below 60 is an F. User enters students score and the program will reads the score and outputs the students record on the computer screen. The record consists of two quiz and two exam scores as well as the students average numeric score for the entire course and the final grade. Define and use a structure for the student record.
REFERENCES
Walter Savitch, Problem Solving with C++, 7th ed., Addison-Wesley, 2009. Chapter 6: I/O
Streams as an Introduction to Objects and Classes, subtitle Introduction to Classes and Objects, page 342 343.
Walter Savitch, Problem Solving with C++, 7th ed., Addison-Wesley, 2009. Chapter 10: Defining
Classes, page 560 to 569.
189
Chapter 6: Structures
190
Chapter 7: Pointers
CHAPTER 7
POINTERS
INTRODUCTION
This chapter explains basic pointer concepts.
LEARNING OUTCOMES
At the end of this chapter, students will be able to: 1. Understand the basic of pointer in order to use it within a C++ program. 2. Demonstrate pass any variable by reference using pointers. 3. Explain differences between array and dynamic arrays.
LEARNING CONTENTS
7.1 Pointers
Pointers is one of the most powerful features of the C++ programming language. A pointer is the address of an item, such as a data value, in memory. In the real world, you frequently use locations, instead of names, to refer to a person or thing. For example, the postal service uses the address on the envelop to deliver your mail. When you make a phone call, the phone company uses the number that you dialed, not the name of the recipient to locate the phone that belongs to the recipient. Pointers variables contain memory addresses, which are represented internally as non-negative values. Normally, a variable directly contains a specific value. A pointer, on the other hand, contains the address of a variable that contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value as illustrate in Fig. 7.1. Referencing a value through a pointer is often called indirection. Note that diagrams typically represent a pointer as an arrow from the pointer variable (which contains a memory address) to the variable it referenes (located at that address in memory).
191
Chapter 7: Pointers
noOfStudent noOfStudent directly references a variable that contains the value 30.
30
dPointer
noOfStudent dPointer indirectly references a variable that contains the value 30.
30
Chapter 7: Pointers
7.1.1
Pointers Declaration
193
Chapter 7: Pointers
7.1.2
194
Chapter 7: Pointers
7.1.3
195
Chapter 7: Pointers
7.1.4
Pointer Assignment
196
Chapter 7: Pointers
7.1.5
7.1.6
Dynamic Variables
197
Chapter 7: Pointers
7.1.7
7.1.8
198
Chapter 7: Pointers
7.1.9
Dangling Pointers
199
Chapter 7: Pointers
200
Chapter 7: Pointers
201
Chapter 7: Pointers
202
Chapter 7: Pointers
203
Chapter 7: Pointers
204
Chapter 7: Pointers
Chapter 7: Pointers
206
Chapter 7: Pointers
207
Chapter 7: Pointers
EXERCISE 7 1. Explain briefly the meaning of pointers in C++. 2. Interpret the following declaration. (a) int *n1, n2; (b) int* n1, n2; (c) int *n1, *n2; 3. By using example, state a least two (2) uses of the * operator. 4. Pointers implementation: Based on the following code, answer (i). Then answer ONE question: (ii) or (iii). Line 1. Line 2. Line 3. Line 4. Line 5. Line 6. int v1=0; int *p1; p1=&v1; *p1=42; cout<<"*p1 is " << *p1 << endl; cout<<"v1 is "<< v1 <<endl; Fig. E7.1 Fragment code of question 4 (i) Predict the output of the above fragment code. (ii) Draw a graphical memory representation to show the activities at each line of code in Fig. E7.1. or (iii) Describe activities at each line of code in Fig. E7.1. 5. Pointers implementation: Based on the following code, answer (i) and (ii). Then answer ONE question: (iii) or (iv). Line 1. Line 2. Line 3. Line 4. Line 5. Line 6. Line 7. int *c1, *c2; c1=new int; *c1=42; c2=c1; cout<<"*c1= "<<*c1<<endl; cout<<"*c2= "<<*c2<<endl; *c2=53; Fig. E7.2 Fragment code of question 5
208
Chapter 7: Pointers
Line 8. Line 9. Line 10. Line 11. Line 12. Line 13.
cout<<"*c1= "<<*c1<<endl; cout<<"*c2= "<<*c2<<endl; c1=new int; *c1=88; cout<<"*c1= "<<*c1<<endl; cout<<"*c2= "<<*c2<<endl; Fig. E7.2 Fragment code of question 5 (cont)
(i) State the purpose of using new operator in the program. (ii) Predict the output of the above fragment code. (iii) Draw a graphical memory representation to show the activities at each line of code in Fig. E7.2. or (iv) Describe activities at line 1 to 4, line 7 and line 10 to 11 in Fig. E7.2.
6. Pointers implementation: Based on the following code, answer (i) to (iii). Then answer ONE question: (iv) or (v). Line 1. Line 2. Line 3. Line 4. Line 5. Line 6. Line 7. Line 8. Line 9. Line 10. int *a, *d; a=new int; *a=42; d=a; *d=53; a=new int; *a=88; delete d; cout<<"*a= "<<*a<<endl; cout<<"*d= "<<*d<<endl; Fig. E7.3 Fragment code of question 6 (i) State the purpose of using delete operator in the program. (ii) Predict the output of the above fragment code. (iii) Give reason(s) of such output in (ii). (iv) Draw a graphical memory representation to show the activities at line 1 to 8 in Fig. E7.3. or (v) Describe activities at line 1 to 8 in Fig. E7.3. 7. Pointers implementation: Based on the following code, answer (i) to (iii). Then answer ONE question: (iv) or (v).
209
Chapter 7: Pointers
Line 1. Line 2. Line 3. Line 4. Line 5. Line 6. Line 7. Line 8. Line 9. Line 10. Line 11.
cout<<"Enter number of students:"; int size; cin>>size; int *list=new int [size]; cout<<"Enter students\'s mark:"; for (int i=0; i<size; i++) cin>>list[i]; cout<<"\n\nThe entered marks:\n"; for (i=0; i<size; i++) cout<<"Student "<<i+1<<" \t"<<list[i]<<endl; cout<<"\n\nThe entered marks:\n"; Fig. E7.4 Fragment code of question 7
(i) Interpret the code in line 4. (ii) Predict the output of the above fragment code if the size is 6 and the marks are 66 33 88 24 45 98 76 56. (iii) Give reason(s) of such output in (ii). (iv) Draw a graphical memory representation to show the activities at line 4 and line 6 to 7 in Fig. E7.4 or (v) Describe activities at line 4 and line 6 to 7 in Fig. E7.4. 8. Give an advantage(s) of implementing pointers in the program. Explain briefly each of it. 9. Illustrates the following program on pointers activities . Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12 Line 13 Line 14 void main(){ int m=2, n=4; ofstream myfile; myfile.open(mydata.txt); } void duplicate (int*a, int*b){ (*a)=2*(*a); (*b)=2*(*b); #include<iostream> #include<fstream> using namespace std;
210
Chapter 7: Pointers
myfile<<Value before duplicate is <<m<< and <<n<<endl; duplicate(&m,&n); myfile<<Value after duplicate is <<m<< and <<n<<endl; close (myfile);
Source: Final Exam, Sem 01, Session 1011
REFERENCES
Walter Savitch, Problem Solving with C++, 7th ed., Addison-Wesley, 2009
211
Chapter 7: Pointers
212