EASY LEARNING C ++ AZRIN AZLI SUHAIMI SITI ZAHARAH SIDEK ASYRAN ABDULLAH A complete guide for beginners
EASY LEARNING C ++ AZRIN AZLI SUHAIMI SITI ZAHARAH SIDEK ASYRAN ABDULLAH A complete guide for beginners
i Cetakan Pertama 2022 Hak cipta terpelihara. Tiada bahagian daripada terbitan ini boleh diterbitkan semula, disimpan untuk pengeluaran atau ditukarkan ke dalam sebarang bentuk atau dengan sebarang alat, sama ada dengan cara elektronik, gambar, fotokopi mekanik, rakaman atau cara lain sebelum mendapat keizinan bertulis daripada penulis terlebih dahulu. Penolakan Tuntutan Penulis telah berusaha untuk memastikan ketepatan serta mutu bahan terbitan yang dihasilkan. Walau bagaimanapun, tiada jaminan diberikan sama ada yang tersurat mahu pun tersirat. Penerbit dan penulis menolak sebarang tuntutan terhadap apa jua tanggungjawab atau liabiliti untuk apa-apa gantirugi secara langsung atau tidak langsung yang disebabkan oleh isi kandungan atau maklumat di dalam buku ini. Diterbitkan Oleh: Politeknik Muadzam Shah, Lebuhraya Tun Abdul Razak, 26700, Muadzam Shah Pahang. Tulisan: Azrin Azli bin Suhaimi | Siti Zaharah binti Sidek Suntingan & Grafik: Asyran Zarizi bin Abdullah
ii FOREWORD Alhamdulillah, as much gratitude to Allah SWT because with His permission and grace, this Easy Learning C ++ Book has been successfully published. This book is suitable for beginners who want to deepen the C ++ programming language at a basic level. It comes with a concise description along with practical examples that aid understanding in mastering the subject of C ++. It is hoped that this book can have a positive impact on all readers. 25 June 2022
iii INTRODUCTION TO FUNDAMENTALS OF PROGRAMMING C++ Program Basic Stucture 2 Comment 3 Pre-processor Directive 4 Header File 4 Main Function 5 C++ Statement 5 Curly Braces 6 Return Statement 6 Identifier and Data Types 7 Variables 7 Variables Declaration 8 Variables Initialization 9 Types of variable 10 Constants 12 Naming Convertion Rules 13 Keyword/Reserved Word 13 Data Types 14 Get Started with IDE 14 Dev C++ 15 Compliling and Debugging Process 15 Compiling Process 16 Debugging Process 16 Errors in Programming 16 BASIC PROGRAM ELEMENTS Input and Output Statement 18 Standard input stream (Cin) 18 Standard output stream (Cout) 19 C++ Operators 20
iv Arithmetic Operator 21 Assignment Operator 23 Compound Assignment 24 Relational Operator 25 Logical Operator 27 Increment & Decrement Operator 30 Conditional Operator 32 Operator Precedence 34 CONTROL STRUCTURE Introduction of Control Structure 37 Sequential 37 Selection 38 Repetition 42 Nested for statement 45 ARRAY Introduction of Array 47 Components of an Array, One-dimensional Array 48 Components of an Array, Two-dimensional Array 51 FUNCTION Introduction of Function 56 Built-in function/ System defined function 56 User Define Function 57 Types of User Define Function 59 Functions with no parameters and no return value 59 Functions with no parameters and with return value 60 Function Prototypes 63 Arguments and Parameters 64 Exercise 66
1 1 OF PROGRAMMING INTRODUCTION TO FUNDAMENTALS ✓ C++ PROGRAM BASIC STRUCTURE ❖ Comment ❖ Pre-Processor Directive (#) ❖ Header File ❖ Main Function ❖ C++ Statement ❖ Curly Braces ❖ Return Statement ✓ IDENTIFIER AND DATA TYPES ❖ Variables ❖ Constants ❖ Naming Convention Rules ❖ Keyword/Reserved Word ❖ Data types ✓ GET STARTED WITH IDE ❖ Compiling and Debugging Process ❖ Compiling Process ❖ Debugging Process ❖ Errors in Programming
2 1.1 C++ PROGRAM BASIC STRUCTURE Probably the best way to start learning a programming language is by writing a program. Before we write the programming code, we need to know the basic structure of programming code. There a seven basic structures in a programming code which is: a) Comment b) Pre-processor directive c) Header file d) Main function e) C++ statement f) Curly braces and g) Return statement Figure 1.1: C++ Program Basic Structure COMMENT MAIN FUNCTION C++ STATEMENT RETURN STATEMENT CURLY BRACES
3 1.1.2 COMMENT Statement in the source code which are ignored by the compiler. C++ support two style/form of comments as below: a) Single line comment (//) b) Block / Multi-line comment (/*…….*/) Below are the illustration the valid and invalid comments within a program. Comment Statements //this program displays a message Valid /this program display a message Invalid //this comment is invalid because its extend over two lines Invalid //this comment is used a comment that extend //across two lines Valid /*this comment is a block comment that spans three lines*/ Valid Table 1.1: Illustration the valid and invalid comments
4 1.1.3 PRE-PROCESSOR DIRECTIVE (#) Include a library or some special instructions to the compiler about some certain terms used in the program. Different pre-processor directives (commands) perform different tasks. How to write the syntax? a) Begin with # symbol. b) No semicolon (;) is expected at the end of a preprocessor directive. Below is the example of using pre-processor directive: Pre-processor directive Meaning #include<iostream> Tells preprocessor to include the input/output stream header file <iostream> #define NAME “BOB” Define a constant Table 1.2: Pre-processor directive 1.1.4 HEADER FILE For big projects having all the code in one file is impractical. But if we split the project into smaller files, we share functions between them by using headers file. The purpose of a header file is to hold declarations for other files to use. Consider the following program code: Figure 1.2: The use of header file Program never declare cout, so how does the compiler know what cout is? The answer is that cout has been declared in a header file called “iostream”. Header files typically only contain declarations. They do not define how something is implemented
5 1.1.5 MAIN FUNCTION A part of every C++ program and identify the start of the program. Exactly one function in a program must be main. The following is the structure of main function: Figure 1.3: Structure of main function 1.1.6 C++ STATEMENT A specification of an action to be taken by the computer as the program executes. Statement is the instruction to the program to perform an action and all statements must be end with a semicolon (;). Parts of statement: Figure 1.4: Part of C++ statement An empty argument lists Function name Type of return value Function body Declarations - The part of the program that tells the compiler the names of memory cells in a program. Executables - Program lines that are converted to machine language instructions and executed by the computer.
6 1.1.7 CURLY BRACES Function body is delimited by braces ({}) symbol. This symbol identifies a segment / body of a program a) The start and end of a function block. b) The start and end of the selection or repetition block. Since the opening braces indicates the start of a segment with the closing braces indicating the end of a segment, there must be just as many opening braces as closing braces. 1.1.8 RETURN STATEMENT The return statement causes the main function to finish. Return may be followed by a return code (in our example is followed by the return code with a value of zero). Figure 1.5: Example of return statement in a program A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. Return statement
7 1.2 IDENTIFIER AND DATA TYPES Identifiers refer to a unique combination of letters and digits, that are used to identify a variable, method, class or any other object in a programming language uniquely. Identifiers are used to represent various objects such as variables, constants, functions name and etc. Identifier can be short name (p and q) or more descriptive names (sum, total and numbers). It is recommended to use descriptive names in order to create understandable and maintainable code. Figure 1.6: Example of identifiers 1.1.2 Variables Variables are containers for storing data values. This identifier can change the whose value during the execution of a program. Example: This is an example of programming expression. Total, price and quantity are variables. Variables can represent numeric values, characters, character strings, Boolean value or floating-point numbers. int number = 60; //good variable name int n = 100; //OK, but not so easy to understand what is n actually Total = price * quantity;
8 1.1.3 Variables Declaration Before use variables, it is must be declared. It’s because to tells the compiler the type of data to store. Declaring a variable means specifying both its name and its data type. In a program, every variable has: a) Name (Identifier) b) Data Type c) Value Example: Figure 1.7: Variable declaration If the variables are more than one and have same data type, we can declare in one line separated with comma. float price = 50.00; Data type Name Value A declaration tells the compiler to allocate enough memory to hold a value of this data type, and to associate the What does a identifier with this location. variable declaration do?
9 1.1.4 Variables Initialization The variables once declared, are assigned some value. This assignment of value to these variables is called initialization of variables. Two types of initialization: • Static Initialization: Here, the variable is assigned a value in advance. This variable then acts as a constant. • Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of this variable can be altered every time the program is being run. Figure 1.8: Variable initialization double tax; tax = 0.15; Variables are initialized in assignment statements double tax = 0.15; Declaration and initialization can be combined
10 1.1.5 Types of variable In programming, the scope of a variable is defined as the extent of the program code within which the variable can we accessed or declared or worked with. There are two types of variable which is: Figure 1.9: Types of variable Figure 1.10: The use of local and global variables in a program Global variables Local variables Use scope resolution operator (::) to access global variables when local and global variables have same name.
11 Comparison between local and global variables Basis for Comparison Local Variable Global Variable Declaration Variables are declared inside a function Variables are declared outside any function Scope Within a function, inside which they are declared Throughout the program Value Uninitialized local variable result in storage of the garbage value Uninitialized global variable stores zero by default Access Accessed only by the statements, inside a function in which they are declared Accessed by any statement in the entire program. Storage Local variables are stored on the stack unless specified Stored on a fixed location decided by a compiler Changes in a variable value Any modification implied in a local variable does not affect the other functions of the program The changes applied in the global variable of a function reflect the changes in the whole program. Table 1.3: Comparison between local and global variables
12 1.1.6 Constants Identifier that appear in the program code as fixed values. Any attempt to modify a constant will result in error. Constant expression must be initialized when they are declared and cannot be modified. Three types of constant: a. Literal Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program. b. Define We can define our own names for constants that we use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. c. Declared We can declare constants by using const prefix with specific type in the same way as we would do with variable declaration except that their values cannot be modified after their definition. char grade = ‘A’; or int number = 100; #define grade A or #define number 100 const char grade = ‘A’; or const int number = 100;
13 1.1.7 Naming Convention Rules There a certain rule in naming identifiers based on the Table xx Rules Example Can contain a mix of character and numbers. However it cannot start with a number H2o First character must be a letter or underscore Number1, _area Can be of mixed cases including underscore character XsquAre, my_num Cannot contain any arithmetic operators R*S+T … or any other punctuation marks #@x%!! Table 1.4: Naming convention rules 1.1.8 Keyword/Reserved Word Keywords are words that have a special meaning to the computer and cannot be used in your program for other purpose. Figure 1.11: Keyword or reserved word in C and C++ programming languages Keywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
14 1.1.9 Data types Data type is classification of a particular type of information. Data types are essential to any computer programming language. Different data types have different sizes in memory depending on the machine and compilers. Figure 1.12: Basic data types in programming 1.2 GET STARTED WITH IDE An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. All of the tools for writing, compiling and testing code in one place. An IDE normally consists of: Figure 1.13: IDE Components There are many IDE available that we can choose to develop our C++ program code. For example, DEV C++.
15 1.2.1 DEV C++ Bloodshed Dev C++ is an older IDE for Windows system only. However, many users praise its clean interface and uncomplicated way of writing a code and compiling. The following figure XX shown the user interface XXXX Figure 1.14: Dev C++ interface 1.3 COMPILING AND DEBUGGING PROCESS Compiling and debugging process for C++ code from Dev C++ is very easy, just of clicking and icon and seeing the result. 1.3.1 Compiling Process A compiler is a computer program (or set of programs) that transforms source code written in a computer language (the source language) into another computer language (the target language, often having a binary form known as object code). The most common reason for wanting to transform source code is to create an executable program. Figure 1.15: Compiling process Compile Execute Compile & Execute New file
16 1.3.2 Debugging Process Debugging is the process of locating and fixing or by passing bugs (errors) in computer program code or the engineering of a hardware device. Debugging is a generalized term which essentially means to step through a process in order to systematically eliminate errors. 1.3.3 Errors in Programming Error is an action or fault or problem which is incorrect or makes the program in abnormal working. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Below are the three types of error in programming: Error Descriptions Common examples Syntax errors/ Compile error Grammar errors in the use of the programming language ✓ Misspelled variable and function names. ✓ Missing semicolons (;) ✓ Improperly matches parenthesesm square brackets[], and curly braces {} ✓ Incorrect format in selection and loop statements Run time errors Occur when a program with no syntax errors asks the computer to do something that the computer is unable to reliably do. ✓ Trying to divide by a variable that contains a value of zero ✓ Trying to open a file that doesn`t exist ✓ There is no way for the compiler to know about these kinds of errors when the program is compiled. Logic errors Logic errors occur when there is a design flaw in your program. ✓ Multiplying when you should be dividing ✓ Adding when you should be subtracting ✓ Opening and using data from the wrong file ✓ Displayin the wrong message ✓ Table 1.5: Errors in Programming
17 2 BASIC PROGRAM ELEMENTS ✓ INPUT AND OUTPUT STATEMENT ❖ Standard input stream (cin) ❖ Standard output stream (cout) ✓ C++ Operators ❖ Arithmetic Operator ❖ Assignment Operator ❖ Relational Operator ❖ Logical Operator ❖ Increment & Decrement Operator ❖ Conditional Operator ❖ Operator Precedence
18 2.1 Input and Output Statement In C++, input and output is performed in the form of a sequence of bytes or more commonly known as streams. a) Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input. b) Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device (display screen) then this process is called output. The two keywords cout and cin in C++ are used very often for printing outputs and taking inputs respectively. Figure 2.1: Illustration of input and output stream 2.1.1 Standard input stream (cin) C++ cin statement is the instance of the class istream and it is used to read input from the standard input device which is usually a keyboard. The extraction operator (>>) is used along with the object cin for reading inputs.
19 Figure 2.2: The use of input stream in a program 2.1.2 Standard output stream (cout) C++ cout statement is the instance of the ostream class and it is used to produce output on the standard output device which is usually the display screen. The insertion operator (<<) is used along with the object cout to be displayed on the screen. INPUT OUTPUT
20 Figure 2.2: The use of output stream in a program 2.2 C++ Operators An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in programming language to operate on data and variables. C++ has a rich set of operators which can be classified as below. OUTPUT
21 Figure 2.3: Types of operator 2.2.1 Arithmetic Operator All the basic arithmetic operations can be carried out in C++. All the operators have almost the same meaning as in other languages. The five arithmetic operations supported by the C++ language are: Table 2.1: Arithmetic operator C++ Arithmetics Operator C++ Operation C++ Expression + Addition f + 7 - Subtraction p – c * Multiplication b * m / Division x / y % Modulus r % s
22 Figure 2.4: The use of arithmetic operator in a program This program will produce result based on the arithmetic operator used.
23 2.2.2 Assignment Operator Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Figure 2.5: The use of assignment operator in a program
24 2.2.3 Compound Assignment When we want to modify the value of a variable by performing an operation on the value currently stored in that variable, we can use compound assignment operators. Table 2.2: Example of compound assignment expression Expression Equivalent to value+=increase; Value = value+increase; a -=5; a = a – 5; a /= b; a = a / b; price *=units + 1; price = price * (units + 1); x %= c – (3 * 2); x = x % c – (3 * 2)
25 Figure 2.6: The use of compound assignment operator in a program 2.2.4 Relational Operator Relational and equality operators are used to evaluate a comparison between two expressions. Commonly, relational expressions are used in decision making statements of C++ language such as if, while and for statements to decide the course of action of a running program. The result of a relational operation is a Boolean value that can only be 1 - if true or 0 - if false, according to its Boolean result. Table 2.3: Relational operator Operator Example Meaning > x>y x is greater than y < x<y x is less than y >= x>=y x is greater than or equal to y <= x<=y x is less than or equal to y = = x = = y x is equal to y ! = x! = y x is not equal to y
26 Figure 2.7: The use of relational operator in a program This program will produce result based on relational operator used.
27 2.2.5 Logical Operator Logical operator uses to test multiple conditions. There are 3 types of logical operators and they work the same way as the Boolean: a) AND (&&) The following panel shows the result of operator && (AND) evaluating the expression a && b: Table 2.4: Logical operator AND Figure 2.8: The use of logical AND operator in a program a b a & & b True True True True False False False True False False False False
28 b) OR (||) The following panel shows the result of operator || (OR) evaluating the expression a || b: Table 2.5: Logical operator OR Figure 2.9: The use of logical OR operator in a program a b a || b True True True True False True False True True False False False
29 c) Not (!) The Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Figure 2.10: The use of logical NOT operator in a program
30 2.2.6 Increment & Decrement Operator The increment and decrement operator are one such type of Unary Operators in C++ which are used to add or subtract the value of 1 from the operand respectively. They are extensively used in for, do while and while loops. A characteristic of this operator is that it can be used both as a prefix and as a postfix. Figure 2.11: Increment and decrement operator In simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning. ++variable --variable Prefix Postfix variable++ variable--
31 How to solve? Figure 2.12: Prefix and postfix solution for increment operator PREFIX POSTFIX
32 Figure 2.13: The use of increment and decrement operator in a program 2.2.7 Conditional Operator The conditional operator can exchange simple if-else code for a single operator. This operator is the only C++ ternary operator (working on three values). How to write? conditional <Expression> ? <expression1>:<expression2>; If the conditional Expression is TRUE, expression1 executes, otherwise if the conditional Expression is FALSE, expression 2 executes. Syntax: The syntax also can be written as below: Figure 2.14: The use of increment and decrement operator in a program (a>b)?(c=25:(c=45); c = (a>b)? 25: 45;
33 Figure 2.15: The use of conditional operator in a program
34 2.3 Operator Precedence Operator precedence means determines which operator is performed first in an expression with more than one operators with different precedence. Figure 2.16: Illustration of operator precedence For example, x = 10 + 20 * 30; x is assigned 70, not 90 because operator * has higher precedence than +, so it first gets multiplied with 20*30 and then adds into 10. Based on the Table 2 below, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. If two operators with the same precedence level are adjacent to each other in an expression, the operator’s associativity tells the compiler whether to evaluate the operators from left to right or from right to left.
35 Table 2.6: Operator Precedence in C++ Programming Figure 2.17: Applying operator precedence in a program Category Operator Associativity Postfix () [] -> . ++ - - Left to Right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to Right Additive + - Left to Right Shift << >> Left to Right Relational < <= > >= Left to Right Equality = = != Left to Right Bitwise AND & Left to Right Bitwise XOR ^ Left to Right Bitwise OR | Left to Right Logical AND && Left to Right Logical OR || Left to Right Conditional ?: Right to left Assignment = += .= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to Right
36 ✓ INTRODUCTION OF CONTROL STRUCTURE ✓ SEQUENTIAL ✓ SELECTION ❖ Single if ❖ if-else ❖ Nested if ❖ switch ✓ REPETITION ❖ for ❖ while ❖ do-while ❖ Nested for Statement 3 CONTROL STRUCTURE
37 3.1 INTRODUCTION OF CONTROL STRUCTURE Control Structures are just a way to specify flow of control in programs. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. They are commands that enable a program to make decisions whether following one path or another. A program is usually not limited to a linear sequence of instructions since during its process it may divided in two, repeat code or bypass sections. Control Structures are the blocks that analyze variables and choose directions in which to go based on given parameters. Figure 3.1: Types of control structure 3.1.1 Sequential The sequential control structure follows the sequential flow of control. The execution of the program statement takes place line by line. In the sequence control structure, an activity leads to the next activity, which is arranged linearly. Figure 3.2: Sequence flow chart As we can see, there is no condition involved in this flow chart. Only sequential statement with any related expression involved SEQUENTIAL SELECTION REPETITION CONTROL STRUCTURE Input Statement 1 Statement 1 Statement 1 End
38 Figure 3.3: The use of sequence control structure in a program 3.1.2 Selection The selection control structure allows one set of statements to be executed if a condition is true and another set of actions to be executed if a condition is false. Figure 3.4: Selection flow chart In this flow chart conditional was apply to make comparison between two value and it provide true and false statement as a result. Input True False End Choice Statement 1 Statement 2 In this segment code user will key-in their name. Computer will read the input and preview the output
39 Figure 3.5: The use of selection control structure in a program Figure 3.6: Example of C++ program code to validate the username and password In this segment code Adam was set as initial value for variable named “name”. Then the “if” statement will make comparison between the variable and the value This C++ code program is to make validation against username and password. Then nested is statement was used to solve the problem.
40 Figure 3.7: The use of switch statement in a program Break Leave a process even if the condition for its end is not fulfilled or to force it to end before it’s natural termination Expression Data type must be INTEGER or CHAR only Switch case is almost similar to the if statement. It is more in the form of a menu of options. It uses the expression as an optional condition
41 Table 3.1: Comparison between single if, if-else and nested if statement If...end if / single if If ...else Nested if Used to execute a set of statements when the given condition is satisfied. Conditional statements within the block are executed when the condition in the if statement is satisfied. Executes the set of statements in if block, when the given condition is satisfied. Executes the statements in the else block, when the condition is not satisfied. The if statements written within the body of another if statement to test multiple conditions is called nested if. if(<condition>) { <statements>; } if (<condition>) { < statements1>; } else { <statements2>; } if (<Condition 1>) { if(<Condition 2>) { < Statement 1 >; } else { < Statement 2 >; } } else { <Statement 3>; }
42 3.1.3 Repetition Repetition control structures statements are called loops and also referred to as iterative structures, are groupings of code which are designed to repeat a set of related statements. The number of repetitions is based on criteria defined in the loop structure, usually a true/false expression. Figure 3.8: Repetition flow chart Input False True End Choice Statement 1 Initialization Condition Increment / decrement This program will execute multiply by two number five times using for statement Repetition also known as looping or iteration. It uses conditions to make a choice of either continuing the loop or exiting the loop
43 Figure 3.9: Example of C++ program code using for statement Figure 3.10: Example of C++ program code using while statement While Loop Statement The while loop can be used if we don’t know how many times a loop must run. For Loop Statement From one number to another number and increases by a specified value each time This program will execute multiply by three number five times using for statement
44 Figure 3.11: Example of C++ program code using do-while statement Do…while loop statement DO…WHILE loops are useful for things that want to loop at least once. This program will execute multiply by five number five times using for statement