The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

A Complete Guide for Beginners - Easy Learning C++

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Penerbitan PMS, 2023-02-21 00:04:49

A Complete Guide for Beginners - Easy Learning C++

A Complete Guide for Beginners - Easy Learning C++

45 3.2 Nested For Statement A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop". These are typically used for working with two dimensions such as multidimensional array, printing stars in rows and columns. Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. Figure 3.12: Example of C++ program code using nested for statement Nested for statement Loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop" This program will execute nested for statement. For one loop of the “first for statement”, the “second for statement” will loop for five times according to the condition.


46 ✓ INTODUCTION OF ARRAY ✓ COMPONENTS OF AN ARRAY, ONE-DIMENSIONAL ARRAY ✓ COMPONENTS OF AN ARRAY, TWO-DIMENSIONAL ARRAY ARRAY 4


47 4.1 Introduction to Array An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Figure 4.1: Types of array An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Figure 4.2: Characteristics of array Characteristics of Arrays Same Data Type Subsequent Memory Locations Unique Array Name Array Size Size Must Be A Constant Expression TYPE OF ARRAY MULTI DIMENSIONAL ONE DIMENSIONAL


48 4.2 Components of An Array: One Dimensional Array EXAMPLE: int age[4] = {19, 25, 35 40}; Figure 4.3: One dimensional array components age[0] age[1] age[2] age[3] 19 25 35 40 DATA TYPE ARRAY SIZE ARRAY NAME ARRAY ELEMENTS INDEXES (Start with 0 until n-1) ELEMENTS (Must same data type elements) Memory simulation Array elements are stored in subsequent memory locations. Two-dimensional array elements are stored row by row in subsequent memory locations. Each element in the array has been assigned its own address in memory.


49 Figure 4.4: The use of one dimensional array in a program In this segment code, array named huruf will accept five elements value. Array name data type same as element data type. At the end of this segment code it will print out the value located at index 2.


50 Figure 4.5: Insert elements for one dimensional array from user This program will accept number from user. Program will then request user to key-in any number for five times. Output will be display in horizontal.


51 4.3 Components of An Array: Two-Dimensional Array EXAMPLE: int age[3][2] = {{19,25},{35,40},{12,33}}; int age[3][2] = {{19,25},{35,40},{12,33}}; Figure 4.6: Two-dimensional array component age[0] 19 25 age[1] 35 40 age[2] 12 33 DATA TYPE ARRAY SIZE [3] = ROWS [2] = COLUMNS ARRAY NAME ARRAY ELEMENTS THREE ROWS TWO COLUMNS 1 2 3 1 2 THREE ROWS TWO COLUMNS


52 Figure 4.7: The use of two-dimensional array in a program “Nested for statement” help to insert and display element from two dimensional array. The first “for statement” represent row and the second “for statement” will represent column.


53 Figure 4.8: Program to calculate average of array elements The program will calculate the sum and average of the element in the array named numbers. The element was given by the programmer as initial value in the array.


54 Figure 4.9: Program to display pyramid using two-dimensional array The segment code combine between “nested for statement” and “while statement” at the end of the program it display a pyramid pattern.


55 5 FUNCTION ✓ INTRODUCITON OF FUNCTION ✓ BUILT-IN FUNCTION / SYSTEM DEFINED FUNCTION ✓ USER DEFINED FUNCTION ✓ FUNCTION PROTOTYPE ❖ Function with no parameters and no return value ❖ Function with no parameters and with return value ❖ Arguments and Parameters


56 5.1 INTRODUCTION OF FUNCTION A function is a group of statements that together perform a specific task. Every program has at least one function that the name is main. The main function is called by the operating system when the code is executed. A function only runs when it is called. You can pass data, known as parameters, into a function. There are two types of function which is: Figure 5.1: Types of function 5.2 Built-in Function / System Defined Function Built-in functions are also called library functions. The C++ standard library provides numerous built-in functions that program can call.These are the functions that are provided by C++ and we need not write them ourselves. We can directly use these functions in our code. FUNCTIONS BUILT-IN FUNCTIONS / SYSTEM DEFINED FUNCTIONS USER DEFINED FUNCTIONS


57 Figure 5.2: C++ program using built-in function 5.3 User Defined Function A user-defined function groups code to perform a specific task. The group of code is given a name by the programmer. When the function is called from any part of the program, it all executes the codes defined in the body of the function. SYNTAX: returnType functionName(parameter list) { //statement(s) area; return statements } • returnType - is any valid C++ data type • functionName - is any valid C++ identifier • parameter-list - is a list of parameters separated by commas • statement(s) - is a list of set of instruction or formula end by semi colon • return statements - is the value returned by the function Built-in function uses standard library function that provide by the programm


58 Table 5.1: Difference between built-in and user define function Built-in Function Used-defined Function Description A part of the system standard library functions that manipulate numbers, strings and output Programmer create their own Function to perform specific task. Example strlen(“Pahang”) – refer to the header file <string> *calculates the length of a string sqrt(x) – refer to the header file <math> *calculate the square root of x float average (float x) double subtraction (int num) char response() int calculate(int sum, int total) User define function created the programmer itself. The function do not exist in the standard library.


59 5.4 Types of User Define Function There are four types of user define function, that are: a) Functions with no parameters and no return value b) Functions with no parameters and with return value c) Functions with parameters and with no return value d) Functions with parameters and with a return value 5.4.1 Functions with no parameters and no return value In this type of function each function is independent. These functions can either be used to display information or they are completely dependent on the user. The example program code below showing the functions with no parameters and no return value. Figure 5.4: C++ program using functions with no parameters and no return value


60 5.4.2 Functions with no parameters and with return value In this type of function, the number of arguments is pass through the calling function to the called function but the called function returns value. The called function is independent. The example program code below showing the functions with no parameters and with return value. Figure 5.5: C++ program using functions with no parameters and with return value


61 5.4.3 Functions with parameters and with no return value This type of function, arguments are passed through the calling function to called function but does not returns value. Such type of function practically dependent on each other. The example program code below showing the functions with parameters and with no return value. Figure 5.6: C++ program using functions with parameters and with no return value


62 5.4.4 Functions with parameters and with a return value This is the best type, as this makes the function completely independent of inputs and outputs, and only the logic is defined inside the function body. Both functions are dependent on each other. The example program code below showing the functions with parameters and with return value. Figure 5.7: C++ program using functions with parameters and with return value


63 5.5 Function Prototypes The function prototypes provide a declaration for a function that specifies the data type returned by the function, its name, and the data types of the arguments expected by the function. If the called function is placed physically above the calling function, no further declaration is required. Figure 5.8: The use of function prototype in a program Function prototypes declared when the called function is placed physically below the calling function CALLING FUNCTION CALLED FUNCTION


64 5.5.1 ARGUMENTS and PARAMETERS Parameter and arguments are the same element; they are given different names to simplify the identification of the error liable to be produced when values are passed to or received by the function. Table 5.2: Difference of Arguments and Parameters ARGUMENTS PARAMETERS An argument is a value passed to a function when function is called. A parameter is defined in the function definition. It is a place holder for the argument during function execution. THIS IS ARGUMENTS THIS IS PARAMETERS THIS IS FUNCTION PROTOTYPE THIS IS MAIN FUNCTIONS


65 Figure 5.9: Example of C++ program using arguments and parameters in a program 1 2


66 1. C++ PROGRAM BASIC STRUCTURE a. Write a program to calculate the sum and difference of two numbers and display the result on screen. i. Declare two integer type variables and also variables to store sum and differences of two numbers. ii. Initialize the two integer variables with some values iii. Calculate and display the sum of these numbers iv. Calculate and display the difference of these numbers. Then, label the program code with C++ program basic structure. b. Identify the identifier below VALID or INVALID. If INVALID give the reason. STATEMENT VALID/INVALID REASON 1number my name price = 10.50 char = ‘M’ Total_Mark continue NUM_temp2 365_days const String Two2Number Program_info EXERCISE


67 c. Write a variable or constants declaration with appropriate data types based on the statement below: a. Variable Course that hold value Diploma in Information Technology. b. Define constant TAX with value 3.50 c. Variable Price that hold value 5.00 d. Variable Gender that hold single character either M / F e. Declare constant Item Price with value 25.30 f. Variable Result with value TRUE 2. BASIC PROGRAM ELEMENTS a. Write a program to calculate the Area of circle. Get input Radius from user and calculate the circle area. Then display the output on the screen. i. Declare Radius and Area variables with appropriate data types ii. Initialize the Area variables with zero iii. Prompt user to input the Radius iv. Calculate and display the Area of circle b. Identify value stored into the integer variable num after each of the following expressions has been evaluated. i. num = 17 % 3; ii. num = 8 / 3 + 2; iii. num = 6.0 / 12.0 + 5.25; iv. num = 3 + 5 * 2; v. num = (2+10) – 3 * 2 % 3


68 c. Given integer variables a=2, b=5 and c=7, produce the result for expression below: NO STATEMENT RESULT 1 a * b – a + c 2 a * (b + c) – a 3 b + (a % a) 4 a * a * b + c – a * 3 5 (b - c) + 3 * a + (a*b) 6 a == b 7 b != c 8 a <= b 9 (c + a) <= 9 10 (a * a) == b - 1 11 a = b++ 12 b = --a 13 c*a != b*a 14 !(a<b) && (a>c) 15 (c >= c) || (a*b > c) 16 (c < a) && (b != 2)


69 3. CONTROL STRUCTURE a. Selection o Password verification Student need to key in their username and password to enter Campus Registration System. You’re required to write a program to accept and verify student username and password in order to allow them enter the system. b. Repetition o Average A teacher has to find the average marks of five of his students for a mathematics subject. you are required to find the total marks and the average marks of his students. 4. ARRAY a. One dimensional o Average There are thirteen marks in an array named Markah_pelajar. you are required to find the sum and average of all the marks. b. Two dimensional o Write a program to view output as shown below


70 5. FUNCTION a. Built-in function Write a program that uses the sqrt () built-in function. Set variable XYZ to a value of 450. Display the output as in the example below. b. Function Prototype Write a function named biodata to allow user key-in data and it function prototype. Call the function biodata from the main function to view the output.


71 Marc. G. (2020). Professional C++ (5th Edition). New York, United States: Wiley. (ISBN: 978-1-119-69540-0) Gilberg. R., Forouzan. B. A. (2019). Loose Leaf for C++ Programming: An ObjectOriented Approach, McGraw-Hill Education. United States. (ISBN: 9780073523385) Lospinoso. J. (2019). C++ Crash Course: A Fast-Paced Introduction. United States. (ISBN: 978-1-59327-888-5) Marc. G. (2018). Professional C++ (4th Edition). New York, United States: Wiley. (ISBN: 978-1-119-42130-6) Joel. M. (2018). Murach's C++ Programming 2018, Fresno, CA, United States: Mike Murach & Associates. (ISBN: 1943872279) Marina. U. B. & Amanda. S. (2018). ScratchJr Coding Cards: Creative Coding Activities. No Starch Press. (ISBN: 1593278993) REFERENCE


72 NOTE


73 Answer Scheme 1. C++ PROGRAM BASIC STRUCTURE a. Write a program to calculate the sum and difference of two numbers and display the result on screen. Pre-processor directive Header file Main function Statement Comment Return statement Curly braces ANSWER


74 Output: b. Identify the identifier below VALID or INVALID. If INVALID give the reason. c. Write a variable or constants declaration with appropriate data types based on the given statement: STATEMENT VALID/INVALID REASON 1number INVALID Starting with number my name INVALID White space price = 10.50 VALID char = ‘M’ INVALID Reserved word Total_Mark VALID continue INVALID Reserved word NUM_temp2 VALID 365_days INVALID Starting with number const INVALID Reserved word String VALID Two2Number VALID Program_info VALID NO. STATEMENT i. string Course = “Diploma in Information Technology”; ii. #define TAX 3.50 iii. float Price = 5.00; OR double Price = 5.00; iv. char Gender = ‘M’; OR char Gender = ‘F’; v. const float Item_Price = 25.30; OR const double Item_Price = 25.30; vi. bool Result = TRUE;


75 2. BASIC PROGRAM ELEMENTS a. Write a program to calculate the Area of circle. Get input Radius from user and calculate the circle area. Then display the output on the screen. Output:


76 b. Identify value stored into the integer variable num after each of the following expressions has been evaluated. c. Given integer variables a=2, b=5 and c=7, produce the result for expression below: NO STATEMENT RESULT 1 a * b – a + c 15 2 a * (b + c) – a 22 3 b + (a % a) 5 4 a * a * b + c – a * 3 21 5 (b - c) + 3 * a + (a*b) 14 6 a == b False 7 b != c True 8 a <= b True 9 (c + a) <= 9 True 10 (a * a) == b - 1 True 11 a = b++ a = b = b + 1 a = b b = b + 1 a = 5 b = 6 12 b = --a b = b – 1= a b = b - 1 b = a b = 5-1 4 = a b = 4 13 c*a != b*a True 14 !(a<b) && (a>c) False 15 (c >= c) || (a*b > c) True 16 (c < a) && (b != 2) False NO. STATEMENT RESULT i. num = 17 % 3; num = 2 ii. num = 8 / 3 + 2; num = 4 iii. num = 6.0 / 12.0 + 5.25; num = 5 iv. num = 3 + 5 * 2; num = 13 v. num = (2+10) – 3 * 2 % 3 num = 12


77 3. CONTROL STRUCTURE a. Selection o Password verification Student need to key in their username and password to enter Campus Registration System. You’re required to write a program to accept and verify student username and password in order to allow them enter the system.


78 b. Repetition o Average A teacher has to find the average marks of five of his students for a mathematics subject. you are required to find the total marks and the average marks of his students.


79 4. ARRAY a. One Dimensional o Average There are five marks in an array named Markah_pelajar. you are required to find the sum and average of all the marks.


80 b. Two Dimensional Write a program to view output as shown below


81 5. FUNCTION a. Built-in function Write a program that uses the sqrt () built-in function. Set variable XYZ to a value of 450. Display the output as in the example below.


82 b. Function Prototype Write a function named biodata to allow user key-in data and it function prototype. Call the function biodata from the main function to view the output.


About the author Asyran Abdullah holds a Bachelor of Computer Science (Networking), before continuing his studies to the Master's level in the same major at Universiti Malaysia Pahang (UMP). Has more than 10 years of experience as a lecturer in the Department of Information & Communication Technology (JTMK) at Muadzam Shah Polytechnic (PMS). Siti Zaharah binti Sidek holds a Bachelor of Computer Science (Software Development) with Honors from KUTKM and also holds a Bachelor's Degree in Technical and Vocational Education from UTHM. Has 14 years of teaching experience in the field at Information and Communication Technology Department (JTMK) for 3 polytechnics and Muadzam Shah Polytechnic (PMS) is the third polytechnic until now. Azrin Azli Suhaimi holds a Master of Science in Information Technology (Msc.IT) from University of Technology MARA(UiTM) and a Bachelor's Degree in Multimedia with Honors from the University Utara Malaysia (UUM). He has experience working in the industry for four years before joining the Malaysian Polytechnic as an instructor for fifteen years until now. He has been teaching various types of programming languages for the past fifteen years including java, actionscript, HTML, PHP, SQL and C ++. He was always optimistic to teach and impart knowledge to his students. EASY LEARNING C ++ This book has been written and compiled specifically for beginners who want to learn the C ++ programming language from a basic level. Equipped with a clear and concise description, has an arrangement with the help of attractive graphics as well as displays a list of examples of relevant instructions along with practicals that are able to help to master this programming language. A complete guide for beginners


Click to View FlipBook Version