Topic 2: C++ Programming fundamentals

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "Topic 2: C++ Programming fundamentals"

Transcription

1 Topic 2: C++ Programming fundamentals Learning Outcomes Upon successful completion of this topic you will be able to: describe basic elements of C++ programming language compile a program identify and correct errors execute a program test and debug a program describe and use C++ program conventions. Introduction to the Topic This topic introduces the basic components of a C++ program, such as identifiers, special symbols and functions. It explains different data types, and how to declare variables and use operators to manipulate them. You will also learn how to structure a program and use C++ library functions. Background Skills and Knowledge Knowledge gained in Topic C++ identifiers, expressions and constants The basic components of a C++ program include: identifiers special symbols functions. Identifiers (or variables) in C++ are allocated to various storage sizes in a computer memory. The location size depends on the type of the variable to which the identifier refers. EEET 2280 Computing Engineering 35

2 Naming rules: An identifier may consist of letters, digits, and the underscore character (_) An identifier must begin with a letter or underscore Uppercase and lower case letters are considered different (C++ is case sensitive) C++ has some predefined identifiers, such as cout and cin A reserved word (keyword) cannot be used as identifier. For a complete list of reserved words in C++ see Appendix 1 (Appendix 1 is located in the References section of this guide) Activity 2.1 A Discussion/ Problem solving In a group of 2 to 3 students, discuss which of the following names cannot be used as identifiers; explain the reasons, and suggest a valid name. volume Time 1_side mynumber km/hour void degrees_c static $AUS number 1 num_1 grade Grade Grade(%) EEET 2280 Computing Engineering 36

3 2.2 Data types The data type of a variable determines a range of values that can be stored in it, and operations that can be performed. The C++ built-in (simple) data types allow you to define and manipulate variables corresponding to integers, characters, floating-point values, and Boolean values. Three categories of simple data are: integral (char, short, int, long, bool, unsigned char, unsigned int etc. ) floating-point (float, double, long double) user-defined (or enumeration type) allows programmers to define their own simple data type. Fig. 2 demonstrates amount of memory allocated for int, bool, and char variables, and their range of values. Data type Values Storage (in bytes) int to bool True or false 1 char -128 to Figure 2. Data types: range of values and memory allocation Appendix 2 shows built-in numerical data types and their minimum guaranteed ranges as it is specified by the ANSI/ISO C++ Standard. (Appendix 2 is located in the References section of this guide) Variables in C++ must be declared before they are used in the program. You may initialise (assign a value) to the variable after declaration, or at the same time: EEET 2280 Computing Engineering 37

4 int length; length = 7; int width = 12; float voltage, resistance; The assignment operator (equal sign = ) assigns the value of the right-side operand or expression to the variable at the left side. It copies the value to the memory location where the variable is stored. Constants refer to memory locations whose values cannot be changed during the program s execution. For example: const double PI = ; const char COURSE[] = "EEET 2280"; const int MAX_RESULT = 100; Activity 2.2 A Discussion/ Problem solving 1. Which data types would you use for the following variables: A person s age Voltage Number of people on Earth Average Melbourne temperature in a month Student ID Gender 2. Discuss the best suitable names for their identifiers. 3. Declare variables from the above list. EEET 2280 Computing Engineering 38

5 2.3 Operators After you have declared and initialised variables you can manipulate those using operators. All arithmetic operations can be performed in a C++ program using the standard notations, such as + for addition, - for subtraction, * for multiplication, and / for division. If operands are of the same type the result will also be of this type. That is, if int i = 5, and int k = 2, the result i/k is the integer 2. However, the expression i/2.0 will return a double value 2.5, because in this case value in variable i used in this expression will be automatically promoted (or converted) to the default, double value. This does not affect the original value in the variable i which retains an integer type. You can also explicitly convert a data type of a variable or expression using the cast operator (type): expression i/(double)k will return 2.5. NOTE that the cast operator has a higher precedence than arithmetic operators. This means that in the example above k will be converted to a double type before the division occurs. In addition to standard arithmetic operators, C++ defines increment (++) and decrement (- -) operators. The increment operator adds 1 to the variable. The statement x++ is equivalent to x = x+1. This means that 1 is added to the existing value of x, and the new value is assigned to the variable x. Similarly, the decrement operator subtracts 1 from the existing value: y-- is equivalent to y = y-1. These operators are shortcuts which used when a variable is to be incremented or decremented by 1. If other value needs to be added or subtracted the increment and decrement operators are combined with the assignment operator =. For instance, x += 5 will increment the existing value of x by 5; y -= 2.5 will subtract 2.5 from y and re-assign the resulting value to y. In C language this type of operation can be performed by using the arithmetic assignment operator which combines the arithmetic EEET 2280 Computing Engineering 39

6 operation with the assignment operation: x += y. There are five arithmetic assignment operators defined in the table below: Operator Description Example Equivalent Statement += Additional assignment operator -= Subtraction assignment operator *= Multiplication assignment operator /= Division assignment operator %= Remainder assignment operator x+=y; x-=y; x*=y; x/=y; x%=y x=x+y; x=x-y; x=x*y; x=x/y; x=x%y; The increment and decrement operators can be part of an arithmetic or logic expression. In this case they work differently when placed in front of a variable (pre-increment/decrement) or after a variable (post-increment/decrement). For example, in the statement y = x++, the value of x will be assigned to y first, and incremented by 1 next. This is equivalent to two separate statements: y = x; x++; Alternatively, the statement y = ++x will result in the incrementing of x by 1 first, and assigning the new value to y next, which is the same as EEET 2280 Computing Engineering 40

7 x++; y = x; The order of arithmetic operations in C++ follows precedence rules. It is important to understand the precedence rules to obtain a correct output from the expression. Modulus ( or remainder) operator ( % ) can be applied only to integer operands. It returns a remainder of integer division. NOTE, if you divide two integer values using the arithmetic division operator (/) any remainder will be truncated. Thus, the result of 9/2 is 4, and 9%2 is 1. Activity 2.3 A Discussion/ Problem solving 4. Declare a constant for inch as Declare a float variable and initialise it using inch as a constant 6. What is the value of 41/4? What is the value of 41%4? Examine the following fragment of code: int x, y; int current = 72; x = current++; y = ++x; What are the values of the variables x, y, and current after this fragment has been executed? C++ program can interact with the user using the standard input and output operations. In most computers standard input refers to the keyboard, and the standard output refers to the screen. To read information from the keyboard and output it onto the screen, C++ uses the insertion << and extraction >> operators, together with the predefined objects cin (for the standard input) and cout (standard output). EEET 2280 Computing Engineering 41

8 cout << "enter the resistance in ohms\n"; cin >> resistance; cout << "enter the voltage in volts"<<"\n"; cin >> voltage; cout << "current = "<<voltage/resistance<<" amp\n"; In the code fragment above we have used a new-line character \n to start the next line on the screen. In a similar way a special function endl can be used: cout << "enter the resistance in ohms"<<endl; This function is one of the input/output manipulators which will be discussed in detail in the Topic Statements and blocks The end of a statement in C++ is defined by the semicolon. A statement can occupy a small part of a line or be spread over two or more lines. Two or more logically connected statements can be combined in a code block. All statements in a block are enclosed within opening and closing curly braces { }. There is no semicolon at the end of a block; a closing brace } terminates the block. For example, the body of a function is a block. As we will see in Topic 3, a block can also define a target of the for loop or if statement. 2.5 Functions A function is a subprogram which contains one or more statements. A function can perform some actions on data and may return a value. Each C++ program contains at least one main() function. EEET 2280 Computing Engineering 42

9 A function name is used to make a function call. When a function is called from the main() function the program execution transfers to the body of this function, and statements within the function are executed. When the function completes (returns), the program flow resumes from the next line in the main() function after the function call. The use of the IDE s debugger allows you to track the program execution and observe values of the variables when the program control moves to a function. C++ functions can be built-in or user-defined. C++ comprises an extensive set of predefined functions which are organised into separate libraries. This includes functions used in input/output operations, mathematical computations, and string manipulations. Some mathematical functions are sqrt(x)and pow(x,y). Every library has a name and is referred to by a header file. I/O functions are defined in iostream.h header; mathematical functions - in cmath.h header. Preprocessor directives are instructions supplied to the preprocessor. All preprocessor instructions start with # and do not have a semicolon at the end. Thus, a line of code #include <cmath> instructs the preprocessor to explicitly add the cmath.h file to the program code A user-defined function has the following format: Return-type name (parameter-list) { //body of function } In the example below we define a function that displays a student name and ID on onto the screen. This function does not take any parameters and does not return a value. A function prototype is placed before main() function. void signature (); //function prototype EEET 2280 Computing Engineering 43

10 The function definition can be placed prior main(), or after main() function. /* this function displays my name and my student ID on the screen */ void signature () //function definition { cout << "Derek Hudson\n"; //function s body cout << "st.id \n"; } Random number generator Many applications that simulate engineering problems or other real-life situations require introduction of sequences of random numbers. For example, several trials of the same experiment may differ due to unpredictable external conditions, such as change of the temperature in the room or atmospheric pressure; to simulate a realistic radio signal one needs to add a background noise. We will use the C++ standard library function int rand() to generate sequences of random numbers. The use of the rand() function requires including the <cstdlib> header. This function returns an integer in the range between 0 and RAND_MAX where RAND_MAX = 32,767 in most operating systems. Consecutive calls for rand() from the same program will produce a sequence of positive random integers. However, if you run the program again you will get exactly the same sequence of numbers. This happens because each time rand() EEET 2280 Computing Engineering 44

11 generates a pseudo-random sequence using the mathematical algorithm with the same random number seed (the default value is 1). To change the seed we need to use void srand(unsigned int) function (also defined in cstdlib) before calling rand(). The following code fragment generates and displays two sets of three random numbers: srand(100); cout<<rand()<<" "<<rand()<<" "<<rand()<<endl; srand(1250); cout<<rand()<<" "<<rand()<<" "<<rand()<<endl; Each time you run this code you will receive different sequences of random numbers. Computer simulations of engineering solutions in most cases require random sequences in a specific range. To generate a random numbers within a specified range you can use the following: EEET 2280 Computing Engineering 45

12 1. random integer x between 0 and r_max: x = rand()%r_max; 2. random integer x between r_min and r_max: x = rand()%(r_max r_min+1)+r_min; 3. random double y between 0 and 1: y = (double)rand()/rand_max; 4. random double y between r_min and r_max: y = (double)rand()/rand_max*(r_max r_min)+r_min; Activity 2.6 A Discussion/ Problem solving In groups of 3-4 students discuss the four cases of random number generation listed above. Write a line of code that generates a random number in each of the following cases: a positive integer number less than 100 an integer in the rage [5, 20] an integer in the range [-20, +20] including -/+ 20 a floating-point number in the range [1.5, 2.0] a floating-point number in the range [-1.0, +1.0] Write a function int my_rand(unsigned seed, int max_number) that takes a seed and max_number as parameters, sets up a random generator with this seed, and returns a random integer number between 0 and the max_number. Write a complete program that asks a user to enter a seed and max_number from the keyboard, calls the my_rand() function and displays on the screen a random number that has been generated. EEET 2280 Computing Engineering 46

13 2.6 C++ language conventions Commonly accepted programming style that makes a C++ program readable includes the following: meaningful variable/function names where possible. capitalised letters of each word after the first in an identifier (dayofweek), or the use of underscore (day_of_week). one level indentation after each opening brace and return one level back after each closing brace. Some statements require additional indentation. These will be indicated to you later in this course. Activity 2 B Laboratory exercises 1. Following instructions in the reference text Herbert (2004), C++ A Beginner s Guide complete Project 2-1, page 53. Write, compile and run the program. 2. Write, compile and run a program that asks a user to enter a temperature in Fahrenheit, converts it to the temperature in Celsius, and display both values on the screen. Hint: To convert Fahrenheit to Celsius (Centigrade), subtract 32 and divide by 1.8. To convert Celsius (Centigrade) to Fahrenheit, multiply by 1.8 and add 32. Write two functions: one function, float FarToCels (float tempf) takes a temperature in Fahrenheit and returns the temperature in Celsius; and another function float CelsToFar(float tempc) takes a temperature in Celsius, and returns the temperature in Fahrenheit. Write a complete program which calls one function, and then another. Debug the program step-by-step and observe the sequence of execution of the program s statements. EEET 2280 Computing Engineering 47

14 Reading 2 Read Herbert (2004), C++ A Beginner s Guide, pp 38, 43 62, Deitel (2001), C++ How to Program, pp Summary and Outcome Checklist In Topic 2 you have learnt the basic components of a C++ program, and how to declare and use them; you have discovered C++ libraries, and learnt how to write user-defined functions. Tick the box for each statement with which you agree: I can describe basic elements of C++ programming language I can compile a program I can identify and correct errors I can execute a program I can test and debug a program I can describe and use C++ program conventions Assessment This topic will be assessed as part of the following Major Assessment tasks: Practical Test 1 and 2; and the Major project (see Assessment for more detail). This aims to ensure understanding of key concepts prior to undertaking the end of the semester examination. EEET 2280 Computing Engineering 48