Docsity

Basic Tools for Building Algorithms: Chapter 2 - Notes | COP 3502, Study notes of Computer Science

Toggle sidebar
bg1
Basic Tools for Building Algorithms
Atomic Data
-Numbers: integers, real (floating point)
-Characters: alphabetic and symbols
-Booleans: true/false
-Pointers: reference memory addresses (locations)
Operators
-Assignment: number1 = number2
-Arithmetic: +, -, *, /, ^
-Input/Output: scanf, printf (in C)
-Relational: <, >, ==, etc.
-Boolean: and, or, not
Creating Simple Variables
A variable can be thought of as a named box, or cell, in which one or more
data values are stored and may be read or written by the algorithm.
An atomic variable is a variable that can hold only 1 individual piece of
data, such as a number or a character.
The act of creating a variable is called declaring the variable. For every
variable that is declared it must be explicitly typed. In other words, each
variable has an associated data type.
An identifier is simply the algorithmic terminology for a name that we
“make-up” to “identify” the variable. Every variable must be given a unique
identifier so that there will be no ambiguity as to which piece of data we
are referencing.
Examples
int age; /* declares a variable named age whose type is integer */
int test_score;
float average; /*declares a variable named average of type float */
Algorithms - 1
Basics of Algorithms – Chapter 3
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Basic Tools for Building Algorithms: Chapter 2 - Notes | COP 3502 and more Study notes Computer Science in PDF only on Docsity!

Basic Tools for Building Algorithms  Atomic Data

  • Numbers: integers, real (floating point)
  • Characters: alphabetic and symbols
  • Booleans: true/false
  • Pointers: reference memory addresses (locations)  Operators
  • Assignment: number1 = number
  • Arithmetic: +, -, *, /, ^
  • Input/Output: scanf, printf (in C)
  • Relational: <, >, ==, etc.
  • Boolean: and, or, not Creating Simple Variables A variable can be thought of as a named box, or cell, in which one or more data values are stored and may be read or written by the algorithm. An atomic variable is a variable that can hold only 1 individual piece of data, such as a number or a character. The act of creating a variable is called declaring the variable. For every variable that is declared it must be explicitly typed. In other words, each variable has an associated data type. An identifier is simply the algorithmic terminology for a name that we “make-up” to “identify” the variable. Every variable must be given a unique identifier so that there will be no ambiguity as to which piece of data we are referencing. Examples int age; /* declares a variable named age whose type is integer / int test_score; float average; /declares a variable named average of type float */

Basics of Algorithms – Chapter 3

Rules for Variable Identifiers in C  A sequence of letters, digits, and the special character _ (underscore).  A letter or the underscore character must be the first character of an identifier.  The C language is case-sensitive. This means that first and First are two different identifiers. Atomic Data Types in C  Numbers

  • int : 4 bytes
  • short : 2 bytes
  • long : 4 bytes
  • unsigned : 4 bytes
  • float : 4 bytes
  • double : 8 bytes
  • long double : 8 bytes The range of values that can be stored in each type depends upon the particular computer hardware on which the program will be executed.  Characters
  • char : 1 byte Examples char your_grade; char first, middle, last; int age, year; A variable can be assigned an initial value at the time it is declared. int height = 75; char grade = ‘A’;

Associativity (left to right) 10 + 3 + 7 = 20 10 – 3 + 7 = 14 15 / 5 * 2 = 6 Assignment Operator / Assignment Statement general form: variable = expression;  The expression can be a constant or a variable. int x, y; x = 5; y = x; x = 6;  The expression can be an arithmetic expression. x = y + 1; y = x * 2; x = x + 10;  Assignment compatibility: There must be compatible types on both sides of the assignment operator or an error will occur. int x; double y; char c; c = ‘9’; /* ok / c = ‘10’; / error / c = 9; / ok in C, not all languages though / x = y; / y is truncated to fit into x / y = x; / ok / x = 5 + 3.2; / truncates the result to 8 / y = 5 + 3.2; / ok / x = 10/4; / x is 2, this is integer division, no remainder / y = 10/4; / y is 2.0 / y = 10/4.0; / y is 2.

 For pointers, assignment means one of the following depending on how it is used: (1) Creating a new variable. If we already had: int *this; int that; and then we do the following: this = malloc(sizeof(int)); this will allocate a new memory space for the pointer and makes the pointer variable refer to it as shown below: (2) Assign the address of a declared variable. int alpha; this = α / this refers to the same address as alpha */ (3) Assigning a value to a variable to which a pointer points. *this = 4; This type of assignment will assign the value 4 to the integer variable to which the pointer variable refers. situation before assignment: situation after the assignment: (4) Making one pointer variable refer to another pointer variable. that = this; Input and Output Operators in C this? this? this 4 this 4 that

Conversion Character Works With How corresponding argument is read or written c printf or scanf as a character d printf or scanf as a decimal integer e printf as a floating point in scientific notation f printf or scanf as a floating point g printf in the e or f format whichever is shorter s printf or scanf as a string lf scanf as a floating point (double) Lf scanf as a floating point (long double) A Simple C Program Literals /* This program adds the two numbers that it reads and prints the sum / / LAB SECTION NUMBER: ASSIGNMENT NUMBER: YOUR NAME: DATE: / #include <stdio.h> int main (void) { int num1, num2, sum; / variable declarations / printf(“Enter your first integer. \n”); /display user prompt / scanf(“%d”, &num1); / read first integer / printf(“Enter your second integer. \n”); /display user prompt / scanf(“%d”, &num2); / read second integer / sum = num1 + num2; /calculate sum / printf(“The sum is %d.\n”, sum); /print the sum / return(0); /programs ends correctly */ }

Literals are data values that are “hardwired” into the algorithm. The value of a literal is taken literally! Each of the following assignment statements contains a literal value. int num, score; char grade; num = 1; grade = ‘A’; score = 42; Constants A constant allows the designer of the algorithm to give a name (identifier) to a fixed value. This makes the program easier to read and understand. For example, suppose we define the following constants: #define PI 3. #define NUMBER_STUDENTS 60 Then instead of : area = 3.1415926 * radius * radius; we would have: area = PI * radius * radius; Or, instead of average_score = total_of_scores/60; we would have: average_score = total_of_scores/NUMBER_STUDENTS; Another Simple C Program Example Algorithms - 8 /* This program will determine the circumference and area of a circle given its radius / / LAB SECTION NUMBER: ASSIGNMENT NUMBER: YOUR NAME: DATE: / #include <stdio.h> #define PI 3. int main () { / variable declarations / double radius, diameter, circumference, area; / get the data values / printf(“Enter the radius”); scanf(“%d”, &radius); / perform the calculations / diameter = radius * 2; circumference – 2 * PI & radius; area = PI * radius * radius; / display the results */ printf(“\n\nThe circumference is: %d “, circumference); printf(“The area is %d.\n”, area); }

Using a graphical description such as a flowchart the algorithmic decision would be represented as: false true Using a programming language, such as C, the algorithmic decision would be expressed as: if (number_of_hours <= 15) … Relational Operators The general syntax of a conditional expression is: There are six relational operators:  greater than >  greater than or equal to >=  equal to ==  less than or equal to <=  less than <  not equal to != Each operand can be an indentifier, constant, literal, or an expression. Examples num1 < num num1 < PI num2 >= 50 (x * y) == (x + y) Although it is most common to compare numerical expressions, you may also compare characters with these operators as well, since they are stored internally as integer values. However, you cannot accurately compare credit hours

= 15

strings of characters with these operators. Characters are compared in alphabetical order, so for example, ‘a’ < ‘b’. Practice Problems Here are some examples of Boolean expressions. See if you can figure out if they are true or false. char ch; int x, y; ch = ‘j’; x = 62; y = 3x – 10 % x; (1) x + y > 40 (2) ch == ‘k’ (3) (x-y) != (7 * (3 – x % 7)) Boolean Operators All but the simplest of algorithms will require complex decisions to be made during execution of the algorithm. Frequently, the decision will have multiple parts. For example, if (the class is not full) AND (it does not conflict with a class in the schedule) … Boolean operators allow us to express compound conditional like the one above. There are three Boolean operators.  AND (&&) o Binary operator. o Requires that both conditions be true if the expression is to evaluate to true. o ((5 > 4) && (4 > 7)) evaluates to FALSE.  OR (||) o Binary operator.

Value of a Value of (!a) True False False True Truth table for NOT (!) operator Acting on Decisions Once the conditional expression has been evaluated (you know whether it is true or not) a control structure is required to dictate what happens next in the algorithm. Most modern programming languages have several different types of control structures. Perhaps the simplest of these is the if-then- else construct: general form: if <boolean_expression> statement 1; else statement 2; statement 3; statement 4; … Execution of an if-then-else statement is as follows:

  1. Check if the boolean expression is true.
  2. If so, go ahead an execute statement 1, then skip to the end of the if statement.
  3. Otherwise, go ahead and execute statement 2, then skip to the end of the if statement.
  4. Continue on, executing statement 3 followed by statement 4, and so on.  There is no way for all four of the statements in the above code segment to be executed in a single sequence.  What happens if you need to execute more than a single statement inside either the if clause or the else clause? C allows the use of a block of statements anywhere that a single statement can appear. A block of statements is a group of statements surrounded by curly braces ({ }) on both sides. The compiler treats this entire group of statements as a single statement, syntactically. Generalized form of if-then-else statement (construct)

if () { statement 11; statement 12; … statement 1n; } else { statement 21; statement 22; … statement 2m; } statement A; statement B; … This general form is executed as follows:

  1. Check if the boolean expression is true.
  2. If so, go ahead and execute statement 11 through statement 1n in order.
  3. Otherwise, go ahead and execute statement 21 through 2m in order.
  4. Continue on, executing statement A, statement B, … Example
  5. Determine whether a given average score passes or fails. #define PASSING 60 int main ( ) { int pass; double average; scanf(“%lf”, &average); if (average < PASSING) pass = 0; else pass =1; if (pass) printf(“You passed.\n”); else printf(“You failed.\n”); }