CS 108 Computing Fundamentals Notes for Thursday, September 17, 2015
Example Program Using a PCF #include //My file 1.c #define PI double area (double) ; int main (void) { double radius = 0.0, result = 0.0 ; printf( "Please enter the radius of a circle in inches: " ); scanf( "%lf", &radius ) ; result = area( radius ) ; printf( "\n\nA radius of %.2lf inches gives the circle an area %.2lf square inches.\n\n", radius, result) ; printf( "Thank you for using this program to calculate the area of a circle.\n\n" ) ; return (0) ; } double area (double p_radius) { double total = 0.0 ; total = ( PI * (p_radius * p_radius) ) ; return total ; }
Math Library Functions Math library contains common math functions #include Format for calling functions: function_name( parameter(s) ); answer = sqrt( 25.0 ); Multiple arguments: use comma-separated list answer = pow ( 2, 4 ) All math functions return data type double
Computers use a form of scientific notation for floating-point representation Numbers written in scientific notation have three components: Data Representation: float vs. double
Computer representation of a floating-point number consists of three fixed-size fields: This is the standard arrangement of these fields. Data Representation: float vs. double
The one-bit sign field is the sign of the stored value. The size of the exponent field, determines the range of values that can be represented. The size of the significand determines the precision of the representation. Data Representation: float vs. double
The IEEE-754 single precision floating point standard uses an 8-bit exponent and a 23-bit significand (32 total bits… think C data type float) The IEEE-754 double precision standard uses an 11-bit exponent and a 52-bit significand (64 total bits… think C data type double) Next, let’s look at examples of using math library functions Data Representation: float vs. double
#include // file 2.c in my DogNet directory #include // Preprocessor directive to link to math library int main (void) { double input = 0.0, result = 0.0 ; printf("\n\n Enter an value to be cubed: "); scanf ("%lf", &input) ; result = pow(input, 3) ; // Math library function "pow" call printf("\n\n\n The value of %.2lf cubed is %.2lf.\n\n\n", input, result ); printf("\n\n Enter an value to find the square root: "); scanf ("%lf", &input) ; result = sqrt(input) ; // Math library function "sqrt" call printf("\n\n\n The value of the square root of %.2lf is %.2lf.\n\n\n", input, result ); return (0) ; }
Math Library Functions Prototypes of Library Functions: –act as guides for implementation –not for inclusion in your programs Parameters may be constants, variables, or expressions Compiler directive to access math library (DogNet) –Think of –lm switch as "link to math" gcc -lm your_file_name.c // result is a.out file OR gcc -lm your_file_name.c -o your_file_name.exe -lm switch
#include // file 3.c in my DogNet directory #include // Preprocessor directive to link to math library int main (void) { double input = 0.0, result = 0.0 ; printf("\n\n Enter an value to be cubed: "); scanf ("%lf", &input) ; result = pow(input, 3) ; // Math library function call printf("\n\n\n The value of %lf cubed is %lf.\n\n\n", input, result ); printf("\n\n Enter an value to find the square root: "); scanf ("%lf", &input) ; result = sqrt(input) ; // Math library function call printf("\n\n\n The value of the square root of %lf is %lf.\n\n\n", input, result ); return (0) ; } // Notice lack of formatting of output
Function Prototype Thoughts return_type function name ( parameter(s) ) ; // use ; here Always specify a return type (void if nothing returned) Select a meaningful name Always specify parameters (void if nothing passed to the function) Names of parameters in the prototype are acceptable BUT - be aware that names are for your clarity not the compiler’s - parameters are passed by position and not by name - naming parameters in prototypes can confuse some students
Function Declaration Thoughts return_type function name ( parameter(s) ) // do not use ; here Specify same return type as prototype (void if nothing returned) Specify same name as prototype Specify names and data types for parameters (void if nothing to pass) Names of parameters should be meaningful Remember: positional matching Parameter names are used as variables in function block Local variables (in addition to parameters) can be declared inside function bock
Parameter Rules A function can have zero or more parameters. Data type and position of parameters found in prototype (remember: identifier are not useful here but are acceptable): int final_average (int, int, int ) ; Names, data types, and position found in declaration header: int final_average (int test1, int test2, int test3) In a function call, data types do not appear… only values, variables, constants, expressions, or (an)other function call(s) student_average = final_average (exam1, exam2, exam3) ;
Parameter Rules... continued The parameters in the prototype and declaration, must precisely match the arguments in a function call Once again: parameters and arguments are passed (linked, associated, etc…) by position - the first parameter in the call parameter list (actual parameter/actual arguments list) is linked/associated with the first parameter in the prototype and the declaration header (formal parameter/formal argument list) - the second parameter in the call parameter list (actual parameter/atual arguments list) is linked/associated with the second parameter in the prototype and declaration header (formal parameter/ formal argument list) ˗ etc…
Parameter Rules... continued Arguments (actual parameters/actual arguments) in the function call must have compatible data types with the parameters (formal parameters/formal arguments) to which they are associated in function prototypes/declarations. Again, arguments (actual parameters/actual arguments) may be variables, constants, or expressions but the data type and position must be compatible with their associated parameters (formal parameters/formal arguments) An argument's name need not match its positionally-matched parameter's name, but it may… remember: it’s about matching the position and data type, it's not about matching the name This matching by position and not name applies to function prototypes, too
#include // file 4.c in my DogNet directory float averager (int, int, int ) ; //Function "averager" prototype int main (void) { int first = 0, second = 0, third = 0 ; // Not a great way to get input!!! Control?? float avg = 0.0 ; printf("\n Please enter three integers each separated by a space: ") ; scanf("%d %d %d", &first, &second, &third) ; avg = averager ( first, second, third ); // Function "averager" call printf ("\n\n% The average of your numbers is: %.2f. \n\n\n", avg); return 0; } float averager (int num1, int num2, int num3) //Function "averager" declaration { float answer = 0.0 ; answer = (float) (num1 + num2 + num3) / 3.0 ; return answer ; }
Example Let’s look at a programming example that implements programmer-created functions and passes parameters "by value" (passing "by address" will be introduced in a week or two). The following example is a "hyper-function" approach (it really emphasizes modularization). This is a good exam-style question.
Let’s write a C program that implements the following algorithm: 1. Introduce the program: the program converts degrees Fahrenheit into degrees Centigrade (ultimately accomplished with a programmer-created function named intro_msg ( ) ) 2. Prompt the user to enter degrees in Fahrenheit (ultimately accomplished with programmer-created function named get_input ( ) ) 3. Read the user’s input for degrees in Fahrenheit (ultimately accomplished with programmer-created function named get_input ( ) ) 4. Perform conversion calculation using this formula: degrees Centigrade = 5/9 * (degrees Fahrenheit – 32) (ultimately accomplished with programmer-created function named calc_answer ( ) ) 5. Display results (ultimately accomplished with programmer-created function named display_results ( ) ) 6. Sign-off with user 7. Terminate
Let's Use the Tools We Have The "Inside-Out" Method The template
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 1.Determine desired output(s) and input(s), then develop your algorithm 2.Place the algorithm in your "header" and as a series of comments inside the main( ) block of statements (use my "C Program Template") as a guide 3.Focus on the first step of the algorithm 4.Begin coding by translating this step of the algorithm to C source-code (save changes!!) 5.Add any additional C code necessary to support the translation of the single algorithm step (save changes!!) 6.Compile (troubleshoot/fix, save changes, and recompile, if necessary) 7.Run and Test (troubleshoot/fix, save changes, recompile, rerun, retest and repeat, as necessary) 8.Comment thoroughly (save changes, compile, and test one last time) 9.Move on to the next step of the algorithm and proceed with "Inside-Out Method" step 4 through 8 until all steps of the algorithm have been satisfied 10.Terminate
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 1. Develop your algorithm Done
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 2.Place the algorithm in your "header" and as a series of comments inside the main( ) block of statements (use my "C Program Template") as a guide 2.To save space on the links, I have left the algorithm out of the "header"… you will not do this when you complete you GHPs (the algorithm always goes in the header on all GHPs)
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 3. Focus on the first step of the algorithm 1. Introduce the program: the program converts degrees Fahrenheit into degrees Centigrade (ultimately accomplished with a programmer-created function named intro_msg ( ) )
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 4.Begin coding by translating this step of the algorithm to C source-code (save changes!!) /*************************************************************************************/ /* ALGORITHM STEP 1: INTRODUCE THE PROGRAM: THE PROGRAM CONVERTS DEGREES */ /* FAHRENHEIT INTO DEGREES CENTIGRADE (ULTIMATELY */ /* ACCOMPLISHED WITH A PROGRAMMER-CREATED FUNCTION NAMED */ /* intro_msg ( ) ) */ /*************************************************************************************/ printf("\n This program converts degrees Fahrenheit into ") ; printf("\n degrees Centigrade. I hope you find it useful. \n\n ") ;
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 5.Add any additional C code necessary to support the translation of the single algorithm step (save changes!!) /*************************************************************************************/ /* #include PREPROCESSOR DIRECTIVE(S) (IF ANY) ARE DIRECTLY BELOW */ /*************************************************************************************/ #include
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 6.Compile (troubleshoot/fix, save changes, and recompile, if necessary) Use gcc and pico, as necessary
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 7.Run and Test (troubleshoot/fix, save changes, recompile, rerun, retest and repeat, as necessary)./a.out… then use gcc, pico, and a.out as necessary
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" 8. Comment thoroughly (save changes, compile, and test one last time) 9.Move on to the next step of the algorithm and proceed with "Inside-Out Method" step 4 through 8 until all steps of the algorithm have been satisfied
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 2: PROMPT THE USER TO ENTER DEGREES IN FAHRENHEIT */ /* (ULTIMATELY ACCOMPLISHED WITH PROGRAMMER-CREATED */ /* FUNCTION NAMED get_input ( ) ) */ /************************************************************************************/ printf("\n Enter the temperature in degrees Fahrenheit: ") ;
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 3: READ THE USER’S INPUT FOR DEGREES IN FAHRENHEIT */ /* (ULTIMATELY ACCOMPLISHED WITH PROGRAMMER-CREATED */ /* FUNCTION NAMED get_input ( ) ) */ /************************************************************************************/ scanf("%lf", °rees_f ) ; printf("\n TEST TEST input: %lf \n\n ", degrees_f ) ;
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 4: PERFORM CONVERSION CALCULATION USING THIS FORMULA: */ /* DEGREES CENTIGRADE = 5/9 * (DEGREES FAHRENHEIT – 32) */ /* (ULTIMATELY ACCOMPLISHED WITH PROGRAMMER-CREATED */ /* FUNCTION NAMED calc_answer ( ) ) */ /************************************************************************************/ degrees_c = 5.0 / 9.0 * ( degrees_f - 32 ) ; printf("\n TEST TEST degrees_c: %lf \n\n ", degrees_c ) ;
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 5: DISPLAY RESULTS (ULTIMATELY ACCOMPLISHED WITH */ /* PROGRAMMER-CREATED FUNCTION NAMED display_results ( ) ) */ /************************************************************************************/ printf("\n\n %.1lf degrees Fahrenheit ", degrees_f ) ; printf("is equal to %.1lf degrees Centigrade. \n\n\n", degrees_c );
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 6: SIGN-OFF WITH USER */ /************************************************************************************/ printf("\n Thanks for using my program. Bye. \n\n\n\n ") ;
Let’s Write the Code Using the "Urban Inside-Out 1-Step-at-a-Time Method" /************************************************************************************/ /* ALGORITHM STEP 7: TERMINATE */ /************************************************************************************/ return ( 0 ) ;
How Do We Handle the "Ultimately" Stuff? 1. Introduce the program: the program converts degrees Fahrenheit into degrees Centigrade (ultimately accomplished with a programmer-created function named intro_msg ( ) ) 2. Prompt the user to enter degrees in Fahrenheit (ultimately accomplished with programmer-created function named get_input ( ) ) 3. Read the user’s input for degrees in Fahrenheit (ultimately accomplished with programmer-created function named get_input ( ) ) 4. Perform conversion calculation using this formula: degrees Centigrade = 5/9 * (degrees Fahrenheit – 32) (ultimately accomplished with programmer-created function named calc_answer ( ) ) 5. Display results (ultimately accomplished with programmer-created function named display_results ( ) ) 6. Sign-off with user 7. Terminate
How Do We Handle the "Ultimately" Stuff? One algorithm step at a time!! 1. Introduce the program: the program converts degrees Fahrenheit into degrees Centigrade (ultimately accomplished with a programmer-created function named intro_msg ( ) ) /*************************************************************************************/ /* ALGORITHM STEP 1: INTRODUCE THE PROGRAM: THE PROGRAM CONVERTS DEGREES */ /* FAHRENHEIT INTO DEGREES CENTIGRADE (ULTIMATELY */ /* ACCOMPLISHED WITH A PROGRAMMER-CREATED FUNCTION NAMED */ /* intro_msg ( ) ) */ /*************************************************************************************/ // printf("\n This program converts degrees Fahrenheit into ") ; // printf("\n degrees Centigrade. I hope you find it useful. \n\n ") ; intro_msg ( ) ; What else needs to be created to allow this function call to be used?
How Do We Handle the "Ultimately" Stuff? /*************************************************************************************/ /* ALGORITHM STEP 1: INTRODUCE THE PROGRAM: THE PROGRAM CONVERTS DEGREES */ /* FAHRENHEIT INTO DEGREES CENTIGRADE (ULTIMATELY */ /* ACCOMPLISHED WITH A PROGRAMMER-CREATED FUNCTION NAMED */ /* intro_msg ( ) ) */ /*************************************************************************************/ // printf("\n This program converts degrees Fahrenheit into ") ; // printf("\n degrees Centigrade. I hope you find it useful. \n\n ") ; intro_msg ( ) ; What else needs to be created to allow this function call to be used? Two things: a function prototype and a function declaration
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Two things: a function prototype (below) and a function declaration (next slide). /*************************************************************************************/ /* PROGRAMMER-CREATED FUNCTION (PCF) PROTOTYPE(S) (IF ANY) ARE */ /* DIRECTLY BELOW */ /*************************************************************************************/ void intro_msg ( void ) ;
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Two things: a function prototype (previous slide) and a function declaration (below). /*************************************************************************************/ /* PROGRAMMER-CREATED FUNCTION (PCF) DEFINITION(S)/DECLARATION(S) (IF ANY) */ /* ARE DIRECTLY BELOW; EACH PCF MUST HAVE ITS OWN PCF DESCRIPTIVE HEADER */ /* DIRECTLY ABOVE ITS SOURCE CODE. */ /*************************************************************************************/ void intro_msg (void) { printf("\n This program converts degrees Fahrenheit into ") ; printf("\n degrees Centigrade. I hope you find it useful. \n\n ") ; return ; }
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? The function declaration needs a descriptive header
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Let's move on to algorithm step 2.
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Let's move on to algorithm step 3.
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Let's move on to algorithm step 4.
How Do We Handle the "Ultimately" Stuff? What else needs to be created to allow this function call to be used? Let's move on to algorithm step 5.
How Do We Handle the "Ultimately" Stuff? The completed program.
How Do We Handle the "Ultimately" Stuff? Compare version "g" with version "m" Both versions do exactly the same thing, however, version "m" uses PCFs
Let’s Move on to Chapter 4 To this point you have learned to solve simple problems by learning to program one category of instruction type: sequential instructions Computers and C do sequential instructions very well Sequence is sufficient to solve simple problems only… we need to expand our repertoire Let’s add a new category of instructions: selection
Selection Think choices… think decisions In a selection structure, a question is asked, and depending on the answer, the program takes an action and then moves on. In other words, selection allows us to "skip" some steps (essentially violate sequence when necessary/desirable) and then resume sequence. Let’s talk more about decisions.
Decision-Making What is a decision? How do we make a decision?
Decision-Making A decision is a choice from a set of alternatives We make our choices based on some decision or judgement criteria Decision criteria are often expressed as conditions Often decision criteria or conditions need to be linked in a logical/reasonable way… Boolean algebra to the rescue: NOT AND OR
Boolean Operators - Order of Evaluation Evaluate NOT first Evaluate AND next Evaluate OR last Think of the Matrix (sort of) NEO … NAO For equal precedence operators, the computer works from left to right Use ( ) to change the order or force a desired order
Boolean Algebra: NOT Negation Condition: it’s raining NOT (It’s raining) TIt’s raining F NOT (It’s raining) FIt’s raining T
Boolean Algebra: AND (a AND b) is only TRUE when both a and b are TRUE FFFT AND FTFT FFTT a b a and b
Boolean Algebra: AND If it’s my birthday AND I’m 21 THEN I get a free beer FFFT AND FTFT FFTT Birthday? 21? Free beer
Boolean Algebra: OR (a OR b) is TRUE when either a is TRUE or b is TRUE FTTT OR FTFT FFTT a b a or b
Boolean Algebra: OR If it’s precipitating OR if it’s cold THEN I’ll wear a coat FTTT OR FTFT FFTT Precipitating? Cold? Wear a coat
Boolean Algebra: Practice Think about an ATM… assuming that you have a valid card in your hand (the card may be yours or you may have picked it up as it was lying next to the ATM machine), develop the decision conditions that allow someone to withdraw money once the card is "swiped" through the card reader.
Boolean Algebra: AND If I enter the correct PIN AND if I have a balance greater than the amount of the withdrawal request THEN I’ll receive money FFFT AND FTFT FFTT PIN? Balance? Receive money
C and Boolean Algebra C has no Boolean data type C interprets 0 as FALSE and everything else as TRUE
See Table 4.6 for more on Operator Precedence C and Relational Operators
Simple if Statement Simple if statement has a single "action block" that is activated or selected when a condition is satisfied (that’s to say that a condition tests TRUE) if ( decision criteria or condition is true) { statements within an "action block" ; }
Simple if Statement
Example (a snippet of code): scanf("%d", &age); if ( age >= 21) { printf("\n This person may have a beer. ") ; } The printf( ) is executed only if age is 21 or greater (only if the condition is true) The print( ) is skipped if the condition is false
if … else Statement The if … else statement has two action blocks, one for the case of condition satisfied, and one another for the case of condition unsatisfied. if (decision criteria or condition is true) { TRUE Action Block Statement(s) ; } else { FALSE Action Block Statement(s) ; }
if … else Statement.
if … else Statement Example (a snippet of code): scanf("%d", &age); if ( age >= 21) { printf("\n This person may have a beer. ") ; } else { printf("\n Show this person to the door.") ; }
if … else Statement scanf("%d", &age); if ( age >= 21) //{ printf("\n This person may have a beer. "); //} else //{ printf("\n Show this person to the door"); //} For single-line action blocks the { } may be omitted… however, I recommend that you always use them
GHP #6 See our homework page