ELECTRICAL ENGINEERING TECHNOLOGY IN COMPUTER
COURSE: TIEC 111-PROGRAMMING I & LAB
CHAPTER 1 – General Problem-Solving Concepts
Problem Solving in Everyday Life
People make decisions every day to solve problems that affect their lives. If a bad decision is made, time and resources are wasted, so it’s important that people know how to make decisions well. There are six steps to follow to assure the best decision:
1. Identify the problem. What is the problem that you must solve?
2. Understand the problem. You must understand what is involved in the problem before you can continue toward the solution. What do you have to solve the problem? What do you need to solve the problem?
3. Identify alternative ways to solve the problem. This list should be as complete as possible. You might want to talk to other people to find other solutions than those you have identified.
4. Select the best way to solve the problem from the list of alternative solutions. In this step, you need to identify and evaluate the pros and cons of each possible solution before selecting the best one. In order to do this, you need to select criteria for the evaluation. These criteria will serve as the guidelines for evaluating each solution.
5. List instructions that enable you to solve the problem using the selected solution. These numbered, step-by-step instructions must fall within the knowledge base set up in step 2. No instruction can be used unless the individual or the machine can understand it. This can be very limiting, especially when working with computers.
6. Evaluate the solution. To evaluate or test a solution means to check its result to see if it is correct, and to see if it satisfies the needs of the person(s) with the problem. If the result is either incorrect or unsatisfactory, then the problem solver must start the process again.
Types of Problems
Problems do not always have straightforward solutions. Some problems, such as baking a cake, can be solved with a series of actions. These solutions are called algorithmic solutions. The algorithmic solutions are reached by completing the actions in steps. These steps are called the algorithm. The solutions of other problems, such as whether to expand the company, are not so straightforward. These solutions require reasoning built on knowledge and experience, and a process of trial and error. Solutions that cannot be reached through a direct set of steps are called heuristic solutions.
Problem Solving with Computers
A computer is a machine that process data faster than the human being and capable to compute mathematical, relational, and logical operations. The computer is organized in six units:
1) Input Unit: the input unit takes data from us to the computer in an organized manner for processing. There are devices associated to this unit, such as keyboard, scanner, and mouse, between others.
2) Output Unit: This is the unit with the task of producing results from the data for getting useful information. Monitor and printer are examples of devices associated to this unit.
3) Memory Units: There are two kinds of computer memory: primary and secondary.
a. Primary Memory: Primary memory is accessible directly by the processing unit. RAM is an example of primary memory. As soon as the computer is switched off the contents of the primary memory is lost. You can store and retrieve data much faster with primary memory compared to secondary memory.
b. Secondary Memory or Secondary Storage Unit: Secondary memory such as floppy disks, magnetic disk, etc., is located outside the computer. The Hard Disk is another example of secondary memory. This memory has a greater storage capability in comparison with the primary memory, but tends to be slower than primary memory. This memory storage data permanently.
4) Control Unit (CU): The control unit determines the sequence in which computer programs and instructions are executed. Things like processing of programs stored in the main memory, interpretation of the instructions and issuing of signals for other units of the computer to execute them. It also acts as a switch board operator when several users access the computer simultaneously. Thereby it coordinates the activities of computer’s peripheral equipment as they perform the input and output.
5) Arithmetic and Logic Unit (ALU): After you enter data through the input device it is stored in the primary storage unit. The actual processing of the data and instruction are performed by Arithmetic Logical Unit. The major operations performed by the ALU are addition, subtraction, multiplication, division, logic and comparison. Data is transferred to ALU from storage unit when required. After processing the output is returned back to storage unit for further processing or getting stored.
The ALU and the CU of a computer system are jointly known as the central processing unit. You may call CPU as the brain of any computer system. It is just like brain that takes all major decisions, makes all sorts of calculations and directs different parts of the computer functions by activating and controlling the operations.
The term solution means the instructions listed during step 5 of problem solving _ the instructions that must be followed to produce the best results. Results mean the outcome or the completed computer-assisted answer. Program means the set of instructions that make up the solution after they have been coded into a particular computer language. There exist three classes of computer languages:
1) Machine Language. This is the language that computers understand. It is based on decimal or binary numeric system. Each machine instruction is represented with a sequence of numbers (a combination of numbers). Unfortunately, the machine language is hardware dependent, and the programmer must know and understand the architecture of the machine in order to write a program.
2) Assembly Languages. They implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture. This representation is usually defined by the hardware manufacturer, and is based on abbreviations (called mnemonics) that help the programmer remember individual instructions.
A utility program called an assembler is used to translate assembly language statements into the target computer's machine code.
3) High-Level Languages. A high level language isolates the execution semantics of computer architecture from the specification of the program, making the process of developing a program simpler and more understandable with respect to a low-level language (like machine and assembly languages). Examples of High-level languages are: COBOL, FORTRAN, Visual Basic, C, C#, and C++, between many others.
In a High-level language, such as C++, you can write expression and equations using mathematical, relational and logical operators (represented by specific symbols). For example, the equation
pay = payrate*hours + overtimepay;
computes the weekly pay of an employee.
High-level languages use programs called compilers to translate the high-level codes into machine code. Once compiled the program, an executable file is generated by the compiler. In order to generate an executable, a High-level language passes through several steps. For example, let consider the typical C++ environment. C++ programs typically go through six phases to be executed. These are: edit, preprocess, compile, link, load, and execute. The first phase consists of editing a file. This is accomplished with an editor program (example: vi, emacs, Borland C++, Microsoft Visual Studio, and others). In this phase, the programmer types a C++ program with the editor and makes corrections if necessary. The program source file is then stored on a secondary storage device such as a disk.
In the next phase, the programmer gives the command to compile the program. The compiler translates the C++ program into a machine language code or object code. In a C++ system, a preprocessor program executes automatically before the compiler’s translation phase begins. The C++ preprocessor obeys commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. The preprocessor is invoked by the compiler before the program is converted to machine language.
The next phase is called linking. C++ programs typically contain references to functions and data defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. The object code produced by the C++ compiler typically contains “holes” due to these missing parts. A linker links the object code with the code for the missing functions to produce an executable image (with no missing pieces). If the program compiles and links correctly, an executable image is produced.
The next phase is called loading. Before a program can be executed, the program must first be placed in memory. This is done by the loader, which takes the executable image from disk and transfers it to memory. Finally, the computer, under the control of its CPU, executes the program one instruction at a time.
Primary Memory
Computers are built to deal with algorithmic solutions, which are often difficult or very time-consuming for humans. People are better than computers at developing heuristic solutions. Solving a complicated calculus problem or alphabetizing 10,000 names is an easy task for the computer, but the problem of how to throw a ball or how to speak English is not. The difficulty lies in the programming. How can problems such as how to throw a ball or speak English be solved in a set of steps that the computer can understand?
The field of computers that deals with heuristic types of problems is called artificial intelligence. Artificial intelligence enables a computer to do things like build its own knowledge bank and speak in a human language. As a result, the computer’s problem-solving abilities are similar to those of a human being. Artificial intelligence is an expanding computer field. Until computers can be built to think like humans, people will process most heuristic solutions and computers will process many algorithmic solutions.
CHAPTER 2 – Beginning Problem-Solving Concepts for the Computer
Problems that can be solved on computers generally consist of only three:
- Computational: problems involving some kind of mathematical processing.
- Logical: problems involving relational or logical processing.
- Repetitive: problems involving repeating a set of mathematical and/or logical instructions.
There exist two fundamental concepts that you need to understand when computers are using to solve a problem: constant and variable. A programmer takes the data, the unorganized facts, and the information, the organized facts, relevant to a problem and defines them as constants or variables.
Other concepts that are essential to developing computer solutions to problems are operators and functions. Operators are the many signs and symbols that show relationships between the constant and variables in the expressions and equations that make up the solution. Operators are combined with constant and variables to create expressions and equations. Functions are sets of instructions that are so commonly used that they are built into a computer language or application, saving the programmer the trouble of writing them.
Constants and Variables
The computer uses constants and variables to solve problems. A constant is a value, that is, a specific alphabetical and/or numeric value that never changes during the processing of all the instructions in a solution. Constants can be any type of data- numeric, alphabetical, or special symbols. In some programming languages and applications, constants can be named. In this case, the constant is given a location in memory and a name. During the execution of the program, this constant is given a value and then is referred to by its name.
In contrast, the value of a variable may change during processing. A programmer must give a name to each variable value used in a solution. The programmer uses a variable name as a reference to help it find that value in its memory. The computer sets up a specific memory location to hold the value of each variable name found in a program. Variables can be any data type, just as constants can.
Examples:
Define a constant named g as: g = 9.81 m/s2.
Define a constant named c as: c = 2.99 * 108 m/s
Define a variable named Country that can be any country of the world.
Country = “Puerto Rico”
Country = “Spain”
The name is the label the computer uses to find the correct memory location; the value is the contents of the location; it uses the value found at the memory location to do the processing.
Rules for Naming and Using Variables
- Name a variable according to what it represents, that is, HOURS for hours worked, PAYRATE for rate of pay, and so on.
- Do not use spaces in a variable name. If space is needed, use the underline character.
- Do not use a dash (or any other symbol that is used as a mathematical operator) in a variable name.
- After you have introduced a variable name that represents a specific data item, this exact variable name must be used in all places where the data item is used.
- Be consistent when using upper- and lowercase characters. In some languages HOURS is a different variable name than Hours.
Data Types
To process solutions, the computer must have data. Data are unorganized facts. They go into the computer as input and are processed by the program. What is returned to the user is an output, or information. This information is printed in form of reports.
The data the computer uses are of many different types. Computers must be told the data type of each variable of constant. The most common data types are numeric, character, and logical. The following table illustrates the data types and their data sets (their kind of values).
Data Type | Data Set | Examples |
Numeric: Integer | All whole numbers | 2680 -38 |
Numeric: Real | All real numbers (whole + decimal) | 3896.31 3457828.0 0.002345 -3456.987 |
Character (surrounded by quotation marks) | All letter, numbers, and special symbols | “A” “a” “M” “z” “k” “1” “5” “7” “8” “0” “+” “=” “(“ “%” “@” |
String (surrounded by quotation marks | Combinations of more Than one character | “Engi2310” “00918” “787-111-2222” |
Logical | True False | True False |
1) Numeric Data: include all types of numbers. Numeric is the only data type that can be used in numeric calculations. This data type includes two subtypes: integers and real numbers. Integers are whole numbers; they can be positive or negative. Real numbers, or floating point numbers, are whole numbers plus decimal parts.
2) Character Data (Alphanumeric Data): consists of all single digit numbers, letters, and special characters available to the computer. An uppercase letter is considered a different character from a lowercase letter. The ASCII (American Standard Code for Information Interchange) character set contains 256 characters. Each character has a whole numbers associated to it. For example, the character “+” is the 43; the character A is the 65. When more than one character is put together, the computer considers this item a string (a string of characters).
ASCII Table
Character and string data can be compared and arranged in alphabetical order in the following way. The computer gives each character a number. This numeric representation is necessary because the computer works only with numbers. The numbers are compared to see which is larger and are then arranged in ascending numeric order. Character data or string data can be joined together in an operation called concatenation. When two pieces of character data are joined, the concatenation results in the second being placed at the end of the first.
3) Logical Data: consists of two values: the words True and False. These are used in making yes-or-no decisions. For example, logical data type might be used to check the state of a bulb; True would mean the bulb is on, and False would mean it is off. Although the logical data might be either True or False, they are not string data.
There exist additional data types, such as user-defined data types. The term user-defined data type means that a programmer may define its own data types.
The following table illustrates examples of the kinds of data that are commonly used in practical problems.
Data | Data Type | Explanation |
The price of an item: 3.79, 13.55 | Numeric: real | The price of an item would be used in calculations. The price is money and needs decimals. |
An student number: “ee000777” | Character: string | A student number consists of alphanumeric or simply numeric data. It is not used for calculations. |
A quantity: 235 | Numeric: integer | A quantity is used for calculations. It is an integer because it normally is a whole number. |
Grades of students: “A”, “B”, “C”, “D”, “F” | Character | A grade is represented by a letter and therefore would be a character data type. |
A credit check: True, False | Logical | The credit check of a customer would be a choice of two answers such as yes (it is okay), or no (it is no okay). Therefore, it should be logical data. |
In C++ language the most common data types are the following:
Data Type | Description |
int | Numeric type: integer numbers |
float | Numeric type: real numbers |
double | Numeric type: real numbers (double precision in float) |
char | Character type: character values such as single letters, numbers and symbols. |
bool | Logical type: True or False. |
When using C++, it is important to declare all the variables and constant before use them. A declaration is the process of reserve a memory space to store values of any type. The declaration consists of a data type, followed by the name of the variable, and ended with a semicolon:
datatype variablename;
The following table illustrates several declarations:
Declaration | Description |
int x; | A variable named x of type int. |
float pay; | A variable named pay of type float. |
double rate; | A variable named rate of type double. |
char grade; | A variable named grade of type char. |
bool credit; | A variable named credit of type bool. |
When you assign an initial value to a variable, as part of the declaration of the variable, the process is called initialization. For example, the instruction
float payrate = 5.75;
In this case a variable named payrate was declared as float and a real number of value 5.75 was assigned to it; this is the initialization. Note that the assigned value has the same type of the declared variable.
Functions
Functions are small sets of instructions that perform specific tasks and return values. They are usually built into a computer language or application. Functions are used as parts of instructions in a solution. Because they are basic tasks that are used repeatedly in the problem-solving process, by using them a programmer or user can shorten the problem-solving time and improve the readability of the solution. Each language or application has a set of functions within it. This set varies with the language and the application. Most languages allow programmers to write their own functions. Libraries of functions can be added to many languages. The form of a function is the name of the function followed by an open parenthesis, followed by the data needed to perform the tasks and concluded by a closed parenthesis. In most languages, the function concludes with a semicolon after the closed parenthesis.
functionname(data);
The value of the result of the function is returned in the name of the function.
Functions use data. The data is listed as part of the function and are called parameters. Functions normally do not alter the parameters. In fact, this depends on the way the function is invoked: call-by-value or call-by-reference. Nevertheless, these concepts will be discussed later.
Functions have been divided into classes:
1) Mathematical functions. Often used in science and business, mathematical functions calculate such things as square root, absolute value, or a random number. There are many others mathematical functions, which may vary depending on the language.
2) String functions. These are used to manipulate string variables. For example, they concatenate two strings, find the number of characters in the string, and so forth.
3) Conversion functions. These functions are used to convert data from one data type to another. For example, since character strings cannot be used in calculations, one of these functions would convert a string value to a numeric value.
4) Statistical functions. These functions are used to calculated things such as maximum values, minimum values, and so forth.
5) Utility functions. They access information outside the program and the language in the computer system. Examples of these include date and time functions.
It is needed to understand that function names are not allowed to be used as variable or constant. They are considered reserved words. Using these reserved words (or key words) will cause a bug in a program.
Some mathematical functions of C++ are illustrated in the following table.
Name | Description | Example |
sqrt | Computes the square root of a numeric value | sqrt(4) returns 2 sqrt(16) returns 4 |
pow | Raise to power | pow(2,3) returns 8 pow(4,2) returns 16 |
fabs | Absolute value | fabs(-2) returns 2 fabs(3) returns 3
|
ceil | Round up value | ceil(4.12) returns 5 ceil(3.6) returns 4 |
floor | Round down value | floor(4.12) returns 4 floor(3.6) returns 3 |
fmod | Compute remainder of division | fmod(4,2) returns 0 fmod(6,5) returns 1 |
exp | Compute exponential function | exp(5) returns 148.41 |
cos | Compute cosine |
|
sin | Compute sine |
|
tan | Compute tangent |
|
acos | Compute arc cosine |
|
asin | Compute arc sine |
|
atan | Compute arc tangent |
|
atan2 | Compute arc tangent with two parameters |
|
cosh | Compute hyperbolic cosine |
|
sinh | Compute hyperbolic sine |
|
tanh | Compute hyperbolic tan |
|
log | Compute natural logarithm |
|
log10 | Compute base-10 logarithm |
|
Exercise 1: Complete the table of mathematical functions presented above by selecting an example for each blank box.
In C++ each class of function is part of a different library (also called a header files). For example, mathematical functions are part of the cmath library and the string functions are part of the cstring library. There are other libraries in C++, such as the standard library iostream, and the ctime library, between others.
The following table presents some functions of the cstring library.
Name | Description |
Strcpy | Copy string |
Strlen | Get string length |
Strcat | Concatenate strings |
Strcmp | Compare two strings |
Operators
The computer has to be told how to process data. This task is accomplished through the use of operators. Operators are the data connectors between the expressions and equations. The operators also tell the computer what type of processing needs to be done. The types of operators used in calculations and problem solving include mathematical, relational, and logical.
The operand and the resultant are two concepts related to the operator. Operands are the data that the operator connects and processes. The resultant is the answer that results when the operation is completed. For example, in the expression 5 + 7, the + is the operator, 5 and 7 are the operands, and 12 is the resultant.
· Mathematical Operators. Include addition, subtraction, multiplication, division, and modulo division. The computer has a symbol for each of them.
· Relational Operators. Include the following: equal to, less than, greater than, less than or equal to, greater than or equal to, and not equal to. A programmer uses relational operators to program decisions. The operand of a relational operator can be either numeric or character (including strings); however, both operands must be of the same data type. The resultant of a relational operation is logical data type True or False. However, in languages such as C++ the resultant can be either integer or logical, depending on the data type of the variable that receive the resultant value. For example, let consider two cases: integer data type and logical data type.
Case 1:
int result;
result = 3 > 4;
In this case, the relational expression 3 > 4 returns a 0, indicating that the resultant is False. The returned value is assigned to the variable result; in other words result has a numeric integer value equal to 0. In general terms, 0 is returned indicating that the comparison is False, and a 1 is returned if the comparison is True.
Case 2:
bool result;
result = 3 > 4;
In this case, the expression 3 > 4 returns a False, indicating that 3 is not greater than 4. Because the variable result was declared of bool type, its value can be either True or False.
· Logical Operators. Logical operators are used to connect relational expressions (decision-making expressions) and to perform operations on logical data. There are three basic logical operators NOT, AND, and OR. In C++ the operator NOT is represented by the symbol !, the AND is &&, and the OR is . The definitions of these logical operators are illustrated in the following table.
NOT
A | !A | Description |
F | T | NOT False is True |
T | F | NOT True is False |
AND
A | B | A && B | Description |
F | F | F | False AND False is False |
F | T | F | False AND True is False |
T | F | F | True AND False is False |
T | T | T | True AND True is True |
OR
A | B | A B | Description |
F | F | F | False OR False is False |
F | T | T | False OR True is True |
T | F | T | True OR False is True |
T | T | T | True OR True is True |
The following table shows the different operators with their respective symbols in C++.
Operator | Type | Symbol | Examples |
Addition | Mathematical | + | 2+5 is 7 -3+1 is -2 |
Subtraction | Mathematical | - | 5-3 is 2 4.5-1.0 is 3.5 |
Multiplication | Mathematical | * | 2*10 is 20 |
Division | Mathematical | / | 4/2 is 2 1.0/2.0 is 0.5 |
Modulo Division | Mathematical | % | 4 % 2 is 0 14 % 3 is 2 |
Equal to | Relational | == | 4 == 4 is True -3==3 is False |
Less than | Relational | < | 5 < 10 is True -2 < -4 is False |
Greater than | Relational | > | 0 > -1 is True 4 > 6 is False |
Less than or equal to | Relational | <= | 2 <= 2 is True 0 <= -3 is False |
Greater than or equal to | Relational | >= | -2 >=-3 is True 5 >= 10 is False |
Not equal to | Relational | != | 1 != 2 is True 3 != 3 is False |
NOT | Logical | ! | !(1 > 3) is True !(1 != 2) is False |
AND | Logical | && | 2 > 0 && 3<8 is True -1 > 0 && 2 == 2 is False |
OR | Logical | 5 > 0 2 < 1 is True -2 > 2 8 > 0 is False |
There exists a hierarchy of operations:
1) Parenthesis
2) Functions
3) Mathematical Operators in the following order:
a. Modulo division, multiplication and division
b. Addition and subtraction
4) Relational Operators
a. All have the same priority
5) Logical Operators in the following order:
a. NOT
b. AND
c. OR
When several operations have similar hierarchies, such as in relational operations, the hierarchy is determined by the precedence of the operations.
No hay comentarios:
Publicar un comentario
Nota: solo los miembros de este blog pueden publicar comentarios.