Honors Computer Science I
Honors Computer Science I COP 3502H
University of Central Florida
Popular in Course
Popular in Computer Programming
This 21 page Class Notes was uploaded by Luisa Beer on Thursday October 22, 2015. The Class Notes belongs to COP 3502H at University of Central Florida taught by Staff in Fall. Since its upload, it has received 30 views. For similar materials see /class/227472/cop-3502h-university-of-central-florida in Computer Programming at University of Central Florida.
Reviews for Honors Computer Science I
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/22/15
0 Atomic Data Numbers integers real floating point Characters alphabetic and symbols Booleans truefalse Pointers reference memory addresses locations 0 Operators Assignment number number2 Arithmetic quot InputOutput scanf printf in C Relational lt gt etc Boolean and or not 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 identi er is simply the algorithmic terminology for a name that we makeup to identify the variable Every variable must be given a unique identi er so that there will be no ambiguity as to which piece of data we are referencing int age declares a variable named age whose type is integer int testscore float average declares a variable named average of type float Algorithms 12 o A sequence of letters digits and the special character underscore o A letter or the underscore character must be the first character of an iden er o The C language is casesensitive This means that rst and First are two different identifiers 0 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 0 Characters char 1byte char yourgrade 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 Algorithms 13 Pointers are used to access memory and manipulate memory addresses int alpha alpha is an integervariable int ptr ptr is a pointer to an integer alpha 7 value of 7 is assigned to alpha ptr ampalpha ptr is assigned to reference the location named alpha ptr alpha printf dn ptr prints the contents of the address referenced by ptr We ll cover pointers in much more detail later for nowjust be aware that they are an atomic data type in C The four basic arithmetic operators are provided in C along with the modulus operator Addition Subtraction Multiplication Division Modulus Modulus or modulo operator produces the remainder portion of division Forexample11512032330 Let X 1 2 3 What is the value of this expression I hope you didn t say 9 The answer is clearly 7 since the multiplication operation has precedence over the addition operation Algorithms 14 quot ifil fllll ll ly il iiwii ii g l iiij 1o372o 10 3714 15526 general form variable expression 0 The expression can be a constant or a variable int x y X 5 y X X 6 o The expression can be an arithmetic expression Xyt yXZ x x 10 0 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 32 truncates the result to 8 y532 ok x 104 x is 2 this is integer division no remainder y 104 yis 20 y1040 y is 25 Algorithms 15 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 mallocsizeofint 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 ampalpha 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 after the assignment 4 Making one pointer variable refer to another pointer variable situation before assignment that this Algorithms 16 Input and output operators allow the program algorithm to communicate with the outside world the world beyond the algorithm Remember that we said an algorithm required input and produced some output we ll in C this is how it does this 1 scanf obtains reads an input value general format scanfformat control string input variable list Each read operation does two things 1 Obtains the next value from outside the algorithm 2 Stores this value in the specified variable For example scanf d ampnum The symbol amp represents the address operator The format d causes input characters typed at the keyboard to be interpreted as a decimal integer The value of this decimal integer is stored at the address of the variable num general format printfformat control string output variable list For example printf d num printf Hello World 0 scanf and printf can take any number of arguments however the number of conversion characters must equal the number of arguments Algorithms 17 0 Conversion characters for different types Cghnggcstigp Works V th 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 oating point in scienti c notation f printf or scanf as a oating point g printf in the e or f format whichever is shorter s printf or scanf as a string If scanf as a oating point double Lf scanf as a oating point long double DATE int main void LAB SECTION NUMBER ASSIGNMENT NUMBER YOUR NAME include ltstdiohgt int num1 num2 sum printf Enter your rst integer n scanf d ampnum1 printf Enter your second integer n scanf d ampnum2 sum num1 num2 printf The sum is dn sum return0 This program adds the two numbers that it reads and prints the sum variable declarations display user prompt read rst integer display user prompt read second integer calculate sum print the sum programs ends correctly Algorithms 18 Literals are data values that are hardwired into the algorithm The value ofa literal is taken literally Each of the following assignment statements contains a literal value int num score char grade num1 grade A score 42 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 31415926 define NUMBERSTUDENTS 60 Then instead of area 31415926 radius radius we would have area Pl radius radius Or instead of averagescore totalofscores60 we would have averagescore totalofscoresNUMBERSTUDENTS Algorithms 19 This program will determine the circumference and area ofa circle given its radius LAB SECTION NUMBER ASSIGNMENT NUMBER YOUR NAME DATE include ltstdiohgt de ne Pl 31415926 int main variable declarations double radius diameter circumference area get the data values printf Enter the radius scanf d ampradius perform the calculations diameter radius 2 circumference 2 Pl amp radius area Pl radius radius display the results printf nnThe circumference is d circumference printf The area is dn area All algorithmic decisions are based upon the evaluation of conditional expressions Conditionas allows us to make decisions about data The result of a conditional evaluation is always either true or false ie Boolean values Algorithms 20 Using natural language an algorithmic decision might be something like Is it true that the number of credit hours currently enrolled is greater than or equal to 15 Using a graphical description such as a flowchart the algorithmic decision would be represented as true false credit hours gt 15 Using a programming language such as C the algorithmic decision would be expressed as if numberofhours lt 15 The general syntax of a conditional expression is ltoperandgt ltreationaoperatorgt ltoperandgt There are six relational operators 0 greater than gt o greater than or equal to gt 0 equal to 0 less than or equal to lt 0 less than lt 0 not equal to Each operand can be an indentifier constant literal or an expression Exam l es num l lt num2 num l lt Pl num2 gt 50 XyXy Algorithms 21 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 strings of characters with these operators Characters are compared in alphabetical order so for example a lt b PraCtice Problem Here are some examples of Boolean expressions See if you can figure out ifthey are true or false char ch int x y ch j x62 y 3x 10x 1 xygt40 2 c k 3 Xy 73X7 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 0 AND ampamp o Binary operator 0 Requires that both conditions be true if the expression is to evaluate to true 0 5 gt 4 ampamp 4 gt 7 evaluates to FALSE Algorithms 22 OR II o Binary operator 0 Requires at least one condition be true if the expression is to evaluate to true 0 5 gt 4 4 gt 7 evaluates to TRUE 0 NOT l o Unary operator 0 Produces the reverse of the Boolean value ofthe operand o l4 gt 7 evaluates to TRUE Shown below are the generic truth tables for the Boolean operators It s a really good idea to memorize these right now You will see them over and over as you study computer science Valge of Value of Value of a ampamp b True True True True False False False True False False False False Truth table for AND ampamp operator Vaige of Value of Value of a H b True True True True False True False True True False False False Truth table for OR operator Algorithms 23 Va39ge 0f Value of la True False False True Truth table for lOT l operator 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 ifthenese construct general form if ltbooeanexpressiongt statement 1 else statement 2 statement 3 statement 4 Execution of an ifthenelse statement is as follows 1 Check ifthe boolean expression is true 2 If so go ahead an execute statement 1 then skip to the end of the if statement Othenvise go ahead and execute statement 2 then skip to the end of the if statement Continue on executing statement 3 followed by statement 4 and so on 00 A 0 There is no way for all four of the statements in the above code segment to be executed in a single sequence 0 What happens if you need to execute more than a single statement inside either the if clause orthe 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 Algorithms 24 if ltbooean expressiongt 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 ifthe 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 1 Determine whether a given average score passes or fails define PASSING 60 int main int pass double average scanf lfquot ampaverage if average lt PASSING pass 0 else pass 1 if pass printf You passedn else printf You failedn Algorithms 2 5 The if else statement can be nested to allow the programmer the ability to program a complex decision structure The general form of a nested if else statement is shown below if ltboolean expression1gt ltstatements 1 gt else if ltboolean expression2gt ltstatements 2gt else if ltboolean expression3gt ltstatements 3gt else ltstatements ngt statement A statement B This statement is executed as icnousoow x Check if ltboolean expression1gt is true If so then execute block of statements ltstatements 1gt If not check if ltboolean expression2gt is true If so then execute block of statements ltstatements 2gt If not check if ltboolean expression3gt is true Continue in this fashion until one ofthe boolean expressions is true Skip all remaining blocks of statements and continue execution with statement A Note The else clause is always optional There may be cases in which you do not want to execute any statements based upon a particular decision Algorithms 26 Note Having the conditions in the wrong order can lead to errors as the following example illustrates Algorithms 27 It is possible to have an if statement inside another if statement Similarly one ofthe statements inside of an else clause may be an if statement This can lead to a problem with matching the correct else clause to the correct if statement However the rule is always the same if month if day gt 15 printf Your late with your taxesn else printf Hurry file your taxes before 415n If the variable month were equal to 7 when this block of code began to execute what would be printed out Nothing If you wanted one of the two messages to be printed regardless of the value of the variable month you would need to do the following if month 4 if day gt 15 printf Your late with your taxesn else printf Hurry file your taxes before 415n The order of precedence of ampamp and H is lower than any arithmetic operator If you ever have any doubt how the computer will interpret your expressions use parentheses to explicitly dictate how the expression is to be evaluated By the way the precedence of ampamp is higher than H xgt7llylt6ampampz will be interpreted as Xgt7 ylt6 ampamp Z 1 Algorithms 28 More Examles Program Description This program asks the user for three values a b and c used in in the equation ax by c used to determine the slope of a line Using this information the algorithm will determine if the slope of the line is positive negative zero or unde ned vertical line include ltstdiohgt int main read in the values for a b and c double a b c printf Enter the values of a b and c for your line n scanf lflflf ampa ampb ampc handle the invalid case ifa 0 ampamp b printf Sorryl You did not enter a valid line equationn else Handle all valid cases separately if b printf The slope is unde ned This is a vertical linen else if a printf The slope ofthe line is 0n else if ab gt 0 printf The slope ofthe line is positiven else printf The slope ofthe line is negativen end main Consider the following problem Suppose that we need to determine if a specific desk will fit into a given room Suppose that we know the length and width of both the desk and the room We want to write a C program that will solve our problem assuming that the user inputs the length and width of the room and the desk Assume that the user will enter only positive numbers for each dimension Does the program below correctly solve our problem Algorithms 29 program to determine if a desk fits into a room given the length and width of both the desk and the room include ltstdiohgt int main int roomlen roomwid int desklen deskwid printf Enter the length and width of the roomnquot scanfddquot amproomlen amproomwid printf Enter the length and width of the desknquot scanfddquot ampdesklen ampdeskwid if deskwid lt roomwid ampamp desklen lt roomlen printf The desk will fit into the roomnquot else printf The desk will not fit into the roomnquot return 0 end main Question Will the program shown above generate the correct answer in every situation Why or why not Answer No Consider a room which has length 6 and width 4 and a desk with length 4 and width 6 The program above will tell you that the desk will not fit when clearly it would fit What is required is to rotate the desk See the following version ofthe algorithm for a better solution Algorithms 30 program to determine if a desk fits into a room given the length and width of both the desk and the room include ltstdiohgt int main int roomlen roomwid int desklen deskwid int temp used for temporarily holding a value printf Enter the length and width of the roomnquot scanfddquot amproomlen amproomwid printf Enter the length and width of the desknquot scanfddquot ampdesklen ampdeskwid adjust widths and lengths if necessary if roomlen lt roomwid temp roomlen roomlen roomwid roomwid temp if desklen lt deskwid temp desklen desklen deskwid deskwid temp if deskwid lt roomwid ampamp desklen lt roomlen printf The desk will fit into the roomnquot else printf The desk will not fit into the roomnquot return 0 end main Algorithms 31 Another way of solving the same problem is to use a more complicated decision structure program to determine if a desk fits into a room given the length and width of both the desk and the room include ltstdiohgt int main int roomlen roomwid int desklen deskwid printf Enter the length and width of the roomnquot scanfddquot amproomlen amproomwid printf Enter the length and width of the desknquot scanfddquot ampdesklen ampdeskwid if deskwid lt roomwid ampamp desklen lt roomlen printf The desk will fit into the roomnquot else if deskwid lt roomlen ampamp desklen lt roomwid printf The desk will fit into the roomnquot else printf The desk will not fit into the roomnquot return 0 end main Algorithms 32
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'