notes4

notes4 - What we learned last week • Assignment/increment...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: What we learned last week • Assignment/increment operators (a++,++a,…) • for statement • Generating tables, etc. • break and continue statements • Reading for this week and next week: • Chap. 5 and Chap. 6 • This week: FUNCTIONS and MATH LIBRARY Additional notes on double/float • double – Same as float, only allots more memory to store the floating-point number (allows for larger, more precise floating point numbers) – Both float and double accept values in the following formats: • • • • float i = 105.5; float i = 1.055E2; ( scientific notation ) double j = 105.5; double j = 1.055E2; ( 1.055E2 = 1.055 x 102 = 105.5 ) Useful Data Types From Fig. 5.5 in book: data type double float int char printf conversion %f %f %d %c scanf conversion %lf %f %d %c Character string is not a data type but can be used in printf statement. %s Program Modules in C – Functions • All C programs are made up of components (modules) called functions. Each program contains a number of functions, one of which is called main. • C contains libraries of prewritten functions, and also allows users to write their own functions. • When using library functions, a statement telling C to use the library must be included in the header – Example: #include <math.h> • Many mathematical functions are available in the C math library. Math Library Functions • Math library functions – Perform common mathematical calculations (sin, exponent, absolute value, etc.) – Include in header: #include <math.h> • Format for calling functions – FunctionName( argument1 , argument2, … ); – Arguments may be constants, variables, or expressions – i = sqrt( 25.0 ); • sqrt is a function that accepts 1 argument of data type double • sqrt calculates the square root of the argument (in this case 25.0) • All math functions return data type double • Compiling programs with math library functions – Compile command must include the option –lm – Example: gcc –lm prog1.c – Example: gcc –lm –o prog1.out prog1.c Math Library Functions From Fig. 5.2 in book – commonly used math library functions: Function sqrt(x) exp(x) log(x) log10(x) fabs(x) ceil(x) floor(x) Description square root of x exponential function ex natural log of x [ ln(x) ] log (base 10) of x [ log10(x) ] absolute value of x rounds x to the smallest integer not less than x rounds x to the largest integer not greater than x Example sqrt( 900.0 ) is 30.0 sqrt( 4.0 ) is 2.0 exp( 1.0 ) is 2.718282 exp( 2.0 ) is 7.389056 log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( 1.0 ) is 0.0 log10( 100.0 ) is 2.0 fabs( 3.5 ) is 3.5 fabs( -2.3 ) is 2.3 ceil( 9.2 ) is 10.0 ceil( -7.8 ) is -7.0 floor( 9.2 ) is 9.0 floor( -7.8 ) is -8.0 Math Library Functions From Fig. 5.2 (continued): Function pow(x,y) fmod(x,y) sin(x) cos(x) tan(x) Description x raised to power y ( xy ) Example pow( 2, 5 ) is 32.0 pow( 9, .5 ) is 3.0 fmod( 12.3, 2.1 ) is 1.8 fmod( 2.35, 1.02 ) is 0.31 sin( 0.0 ) is 0.0 sin( 3.14159/2 ) is 1.0 cos( 0.0 ) is 1.0 cos( 3.14159/2 ) is 0.0 tan( 0.0 ) is 0.0 tan( 3.14159/4 ) is 1.0 remainder of x/y as a floating point number trigonometric sine of x ( x in radians ) trigonometric cosine of x ( x in radians ) trigonometric tangent of x ( x in radians ) Example Program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* using math library functions */ #include <stdio.h> #include <math.h> int main() { float pie = 3.14159; double i = sin( 3.14159 ); double j = sin( pie/2 ); float k = cos( pie/2 ); float l = tan( pie ); double m = 2.3e5; printf( printf( printf( printf( printf( "\ni "\nj "\nk "\nl "\nm is is is is is %f", i %f", j %f", k %f", l %f\n", ); ); ); ); m ); return 0; /* indicate that program ended successfully */ } /* end function main */ Example Program Output Output for program on previous page: % a.out i j k l m % is is is is is 0.000003 1.000000 0.000001 -0.000003 230000.000000 Example Program: Compound Interest An investor plans to invest an amount of money p in an account with interest r (compounded annually). Write a program that asks the user to enter the initial investment amount (also called the principle) and the interest rate and then outputs a table showing the amount in the account at the end of each of the first 10 years. The formula for compound interest is: a = p (1 + r)n where p is the principle r is the annual interest rate n is the number of years a is the amount in the account after n years The function pow(x,y) calculates xy Sample output for this program is shown on the next page. Program Output: Compound Interest % a.out Enter the principle amount: 1200.00 Enter the annual interest rate: .04 Year 1 2 3 4 5 6 7 8 9 10 % Amount in account 1248.00 1297.92 1349.84 1403.83 1459.98 1518.38 1579.12 1642.28 1707.97 1776.29 Example Program: Compound Interest 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* calculating compound interest */ #include <stdio.h> #include <math.h> int main() { double amount; double principle; double rate; int year; printf( "\nEnter the principle amount: " ); scanf( "%lf", &principle ); printf( "Enter the annual interest rate: " ); scanf( "%lf", &rate ); Example Program: Compound Interest printf( "\n%4s%21s\n", "Year", "Amount in account" ); 18 19 for ( year = 1 ; year <= 10 ; year++ ) { 20 amount = principle * pow( 1.0 + rate, year ); 21 printf( "%4d%21.2f\n", year, amount ); 22 } 23 24 return 0; /* indicate that program ended successfully */ 25 26 27 } /* end function main */ Example Program: Calculating pi (π) In this program we will calculate the value of pi (π) using the following series: π = 4 − 4 + 4 − 4 + 4 − 4 + ... 3 5 7 9 11 The output should look like the following: % a.out This program calculates the value of pi. Enter the number of terms you want in the series: 1000000 Using 001000000 terms in the series, pi is approximately 3.141591653590 The actual value of pi, rounded to 12 decimal places, is 3.141592653589 % Example Program: Calculating pi (π) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* calculating pi by infinite series */ #include <stdio.h> int main() { int i; double iterm; int nterms; double num; double den; double pi; /* /* /* /* /* /* counter */ value of term number i in the series */ number of terms in series */ numerator */ denominator */ value of pi */ printf( "\nThis program calculates the value of pi." ); printf( "\nEnter the number of terms you want in the series: " ); scanf( "%d", &nterms ); Example Program: Calculating pi (π) 18 for ( i = 1, num = 4.0, pi = 0.0 ; i <= nterms ; i++ ) { den = (2*i - 1); /* denominator of term number i */ 19 iterm = num / den; /* value of term number i */ 20 21 if ( i % 2 == 0 ) 22 pi -= iterm; 23 else 24 pi += iterm; 25 26 } /* end for loop */ 27 28 printf( "\nUsing %.9d terms in the series, “); 29 printf( “pi is approximately %.12f", nterms, pi ); 30 31 printf( "\nThe actual value of pi, rounded to 12 "); 32 printf( "decimal places, is 3.141592653589\n\n" ); 33 34 return 0; /* indicate that program ended successfully */ 35 36 37 } /* end function main */ Notes on Calculating π • The more terms you use in the series, the closer your estimate to the true value of π. • The more terms you use in the series, the more calculations your program must perform, so it takes a longer time for the program to run. • Good algorithms not only perform the necessary actions but also do them in the least amount of time possible. – When possible, reduce the number of calculations your program must perform (see next example). Example Program: Testing for Primes In this program we will ask the user to enter a positive integer and check to see if it is a prime number. The output should look like the following (see next page for more examples): % a.out This program will test to see if a number is prime. Enter a positive integer: 478 478 is not prime. % Example Program: Testing for Primes Another example of this program’s output: % a.out This program will test to see if a number is prime. Enter a positive integer: 29 29 is prime. % Try the following numbers in the program: 538214572 479736919 Can you make the program run faster? Example Program: Testing for Primes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* test to see if a number is prime */ #include <stdio.h> int main() { int i; /* counter */ int num; /* number entered by user */ int primetest = 0; /* used to check if num is prime */ printf( "\nThis program will test to see if a number is prime." ); printf( "\nEnter a positive integer: " ); scanf( "%d", &num ); Example Program: Testing for Primes 15 for ( i = 2 ; i <= num - 1 ; i++ ) { 16 if ( num % i == 0 ) { 17 primetest = 1; 18 } 19 20 } /* end for loop */ 21 22 if ( primetest == 0 ) 23 printf( "\n%d is prime.\n\n", num ); 24 else 25 printf( "\n%d is not prime.\n\n", num); 26 27 return 0; /* indicate that program ended successfully */ 28 29 30 } /* end function main */ Example Program Let’s write a program that inputs 2 floating point numbers and outputs all integers between these 2 numbers that are divisible by 7. The output should print in 3 columns. Example output is shown on the next page. Example Program % a.out Enter 2 floating point numbers (max 2 dec places): -27.62 49.01 -21 0 21 42 % a.out Enter 2 floating point numbers (max 2 dec places): 52.35 -25.1 -21 0 21 42 % -14 7 28 49 -7 14 35 -14 7 28 49 -7 14 35 Example Program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* print all numbers divisible by 7 between 2 floating point numbers */ #include <stdio.h> #include <math.h> int main() { int int1, int2, i, j=0; float entry1, entry2, num1, num2; printf( "\nEnter 2 floating point numbers " ); printf( "(max 2 decimal places): " ); scanf( "%f%f", &entry1, &entry2 ); if ( entry1 < entry2 ) { num1 = ceil( entry1 ); num2 = floor( entry2 ); } else { num1 = ceil( entry2 ); num2 = floor( entry1 ); } Example Program 24 int1 = (int)num1; 25 int2 = (int)num2; 26 27 printf( "\n" ); 28 29 for ( i = num1 ; i <= num2 ; i++ ) { 30 if ( i % 7 == 0 ) { 31 printf( "%6d", i ); 32 j++; 33 if ( j % 3 == 0 ) 34 printf( "\n" ); 35 } 36 } 37 38 if ( j == 0) { 39 printf( "There are no integers divisible by 7 " ); 40 printf( "between %.2f and %.2f", entry1, entry2 ); 41 } 42 43 printf( "\n\n" ); 44 return 0; /* indicate that program ended successfully */ 45 46 } /* end function main */ Writing Custom Functions • In addition to functions which are defined in libraries, C allows you to write your own customized functions. • When you use a customized function, you must include the following in your program: – Declare the function at the beginning (or include a custom header file where the function is defined) – Call the function in the main body of your program – Define the function Function Declaration • Included in your header • Declares the output type and the input parameters for the function • Declaration format: return-value-type function-name( parameter list ); • Examples: – int cube( int x ); – float maxtest( float a, float b, float c ); – char primetest( int num ); Function Definition • Function definition is done after the main body of your program • Function definition format: return-value-type function-name( parameter list ) { declarations and statements } • Function body (block) – Variables can be defined inside blocks – Functions cannot be defined inside other functions Example Program: Custom Functions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 /* Creating and using custom functions */ #include <stdio.h> int cube( int y ); int main() { int i; /* function prototype */ /* counter */ /* calculate and print the cube of integers between 1 and 10 */ for ( i = 1 ; i <= 10 ; i++ ) { printf( "%d ", cube( i ) ); } /* end for */ printf( "\n\n" ); return 0; /* indicate successful termination */ } /* end main */ /* define cube function to return the cube of an integer */ int cube( int y ) { return y*y*y; /* returns cube of y as an int */ } /* end function cube */ Example Program Output Output for program on previous page: % a.out 1 8 27 64 125 216 343 512 729 1000 % Example Output: Program 2 Have the user input 3 floating point numbers. Write 2 functions, one that determines the smallest of the 3 numbers, and one that determines the largest. Use these functions to output the largest and the smallest number. Example output: % a.out Enter 3 floating point numbers: 3.9 -12.2 2.7 3.90 is the largest. -12.20 is the smallest. % Example Program 2: Custom Functions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* creating and using custom functions */ #include <stdio.h> float maxtest( float a, float b, float c ); /* custom func */ float mintest( float d, float e, float f ); /* custom func */ int main() { float n1, n2, n3; printf( "\nEnter 3 floating point numbers: " ); scanf( "%f%f%f", &n1, &n2, &n3 ); printf("\n%.2f is the largest.", maxtest( n1, n2, n3 )); printf("\n%.2f is the smallest.\n", mintest( n1, n2, n3 )); return 0; /* indicate successful termination */ } /* end main */ continued next page Example Program 2: Custom Functions 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 /* define maxtest function */ float maxtest( float a, float b, { if ( a >= b && a >= c ) return a; /* returns a else if ( b >= a && b >= c ) return b; /* returns b else return c; /* returns c } /* end function maxtest */ float c ) if a is largest */ if b is largest */ if c is largest */ /* define mintest function */ float mintest( float d, float e, { if ( d <= e && d <= f ) return d; /* returns d else if ( e <= d && e <= f ) return e; /* returns e else return f; /* returns f } /* end function mintest */ float f ) if d is smallest */ if e is smallest */ if f is smallest */ Example Output: Program 3 Have the user input a positive integer. Write a function which outputs the character ‘y’ if the integer is prime and ‘n’ if it is not prime. Have the program print the output of this function. Example program output: % a.out This program tests for primes (y=yes, n=no). Enter a positive integer: 17 y % a.out This program tests for primes (y=yes, n=no). Enter a positive integer: 27 n % Example Program 3: Custom Functions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* test to see if a number is prime */ #include <stdio.h> #include <math.h> char primetest( int x ); int main() { int num; /* function prototype */ /* number entered by user */ printf( "\nThis program tests for primes (y=yes, n=no)." ); printf( "\nEnter a positive integer: " ); scanf( "%d", &num ); printf( "\n%c\n\n", primetest( num ) ); return 0; /* end program */ } /* end main */ continued next page Example Program 3: Custom Functions /* function primetest */ 21 char primetest( int x ) 22 { int test = 0; /* used to check if num is prime */ 23 int i; /* counter */ 24 25 for ( i = 2 ; i <= sqrt(x) ; i++ ) { 26 27 if ( x % i == 0 ) { 28 test = 1; 29 break; 30 } /* end if statement */ 31 32 } /* end for loop */ 33 34 if ( test == 0 ) 35 return 'y'; 36 else 37 return 'n'; 38 39 40 } /* end primetest */ ...
View Full Document

This note was uploaded on 03/02/2009 for the course ENGR 3 taught by Professor Ben-yaakov during the Fall '08 term at UCSB.

Ask a homework question - tutors are online