Program Appl in Elec Comp Engr
Program Appl in Elec Comp Engr ECE 3331
Popular in Course
Popular in Electrical Engineering
This 8 page Class Notes was uploaded by Karolann Wiegand on Saturday September 19, 2015. The Class Notes belongs to ECE 3331 at University of Houston taught by Staff in Fall. Since its upload, it has received 9 views. For similar materials see /class/208308/ece-3331-university-of-houston in Electrical Engineering at University of Houston.
Reviews for Program Appl in Elec Comp Engr
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: 09/19/15
Functions Purpose functions break large computing tasks into smaller ones and enable programmers to use routines that others have written I 3 Aspects of Functions A Definition B DeclarationPrototype C InvocationCall ll Function Definition A Syntax returntype functionname argumentlist declarations and statements B Properties 1 The returntype argumentlist and declarations and statements may all be omitted The functionname must be present Example dummy l l This function does nothing and returns nothing This kind of function is useful during program development 2 If the returntype is omitted the default return type is int 3 Communication between functions is by the arguments and values returned by the function 4 Functions may occur in any order in a source file They may be spread out among several source files 5 A function definition may not be enclosed within another function definition 6 The return statement is the mechanism for returning a value from the called function to the caller return expression Both the return statement and the expression are optional 7 If there is no expression after the return statement the function returns a value which is unknown garbage If the returntype ofthe function is void then there must not be an expression following the return statement 8 The calling function is free to ignore the return value B Example void mess int n in l r for 10 iltn i printfquotGo Coogsl nquot Umbme 1 Line 1 of the example shows the header of the function definition 2 Line 2 gives the local variable declarations 3 Lines 3 and 4 show the local statements Another Example NewtonRaphson fx flxa x 361 fx we x x rm x x02 If x x ltlt lthen fx 2 foe M x x If we wish to solve 0 then we can solve the above equation forx yielding fxx x E x fx p To solve make an initial guess forxa and solve for x lffx is sufficiently close to zero then the solution has been reached Otherwise replace xa withx and repeat The process is repeated until the solution is reached or a maximum number of iterations is performed 1 double nr double x double eps int maxiter 2 int 1 er39 3 double Xa 4 double fdouble X 5 double f1double X 6 for iterl iterltmaxiter 1ter 7 xa X 8 Xxa e fxaflxa 9 1f fabs xexa lt eps break 10 11 1f lter gt maxiter 12 printfquotToo many iteration5nquot 13 return i 0 14 15 else 16 return X 17 1 Again notice the function header in line 1 2 Lines ll7 comprise the function definition 3 Notice the two function declarations on lines 4 and 5 4 Notice the two function invocations on line 8 5 If line 13 is reached there will be an immediate return to the calling function No other statements in that function are executed Function DeclarationPrototype A Functions have a scope defined by the location of their declaration B Example File 1 File 2 funcl funcl func2 y39 void main void main func2 l l funcl funcl l l func2 func2 l l 1 In file 1 the declarations offunc andfunc2 allow global use of these functions by all functions in this file In file 2 onlyfunc can be used by any function within the file The function func2 may only be invoked within the main function or within itself Function InvocationC all A Call by value In C arguments are passed to the function by their value not as a reference to their memory address New memory is allocated automatically to store the values of the arguments being passed Actual Arguments reside in the invocation may be expressions lt correspondence between gt There should be a ltol arguments and they should match in type Dummy Formal Arguments reside in the header where the function is defined cannot be expres sions If the compiler encounters a prototype before it encounters an invocation then each actual argument will be implicitly converted to the type of its corresponding dummy argument as defined by the prototype If the compiler encounters an invocation before a prototype or definition then each oat is converted to double and each char are converted to int 1 double fun nt float 2 void main l 3 float y 5 4 4 double 5 Z fun7 y2 6 fun fun7 y2 Illegall 7 8 9 double funint n float X l 10 return XXn39 l l Recursion A A function may call imelf directly or indirectly B Direct recursive calls are the most common and easiest to understand C Be very careful of indirect recursive calls as they tend to be difficult to trace and debug D If it is possible to write a function as nonrecursive this is generally preferred since it is easier to debug and tends to have faster execution speeds D Example Factorial recursive and nonrecursive versions long factint n l computes the factorial of n recursive ve rsion if ngtO return nfact nil else if n 0 return 1 else return 0 long factint n l computes the factorial of n nonerecursive version long value 1 int i if n lt 0 return 0 for i2 iltn i value i return value Preprocessor Another example Fibonacci sequence int fibint n computes the value of the nth position in a Fibonacci sequence if n gt 2 return fibnl fibn2 else if n 1 H n return 1 else return 0 long factint int fibint void main long n6 n factfibn y39 n Purpose provides a separate first step in compilation I ll H1 H1 Preprocessor directives commands that are executed prior to the source code being compiled Two most commonly used A B define include Macro Substitution define A Syntax define name replacementtext Notice that there is no semi colon at the end of the line This is because this is not a statement it is a preprocessor directive Examples define PI 3141592653589793238462643383279502884197 define rtdrad rad 1800PI define dtr deg deg PI1800 File lnclusion include A Syntax include filename or include ltfilename gt When the filename is enclosed in quotation marks the search for the file begins in the directory where the program is located lfthe file is not found then the searchmay continue in other directories based on the implementation When the filename is enclosed in angled brackem the search for the file begins at an implementation defined location Some common standard libraries included in this class are ltstdiohgt ltctype hgt ltstringhgt ltstdlib hgt ltstdarg hgt lttimehgt ltlimits hgt Input and output Character functions and tests String manipulation functions Utility functions eg requests for memory allocation Variable argument lists Time and date functions Implementation defined limits Contrary to popular belief ltmathhgt is not a standard C library although it is provided in many implementations For the UNIX operating system please read the compiler documentation on how to include the math library String Functions Input include ltstdiohgt 1Using s with scanf or fscanf skips leading white space to first nonwhite space begins converting stopping with next white space adds null Addition of field width sets maximum number of characters to look at will still stop sooner if encounters white space 7s will input no more than 7 characters 2char getschar string reads until encounters new line or end of file Does not store new line does add terminating null Returns pointer to string stored 3char fgetschar stringint nFLE ptr reads no more than n characters from file pointed to by ptr stops with end of line and DOES store it also adds null Returns pointer to string stored Outputinclude ltstdiohgt 1Using s with printf or fprintf outputs characters in string up to but not including null Can use field width to get extra blanks normally rightjustified use flag to leftjustify use precision to specify maximum number of characters to output 2int putsconst char string writes string up to null then writes new line returns positive integer if successful 3int fputsconst char stringFlLE ptr write string including new line if present to file pointed to by ptr Does not follow with new line unless already in string Manipulationinclude ltstringhgt 1sizet strlenconst str returns number of characters in str up to but not including null 2 a char strcpychar s1const char s2 copies the string s2 into the string s1 including the terminating null Programmer is responsible for enough room in st The value of s1 is returned b char strncpychar s1const char s2sizet n same as strcpy except precisely n characters are written into s1 The characters are taken from s2 until the null is reached or n characters have been taken whichever comes first Any remaining characters in st are replaced by nulls 3 a char strcatchar s1const char s2 concatenates strings s1 and s2 that is the string s2 is appended to the end of st with the first character in s2 replacing the hull of the original s1 Programmer is responsible for enough room in st Returns the value of st b char strncatchar s1const char s2sizet n same as strcat except at most n characters of s2 not including the null are appended followed by the null 4 a int strcmpconst char s1const char s2 compares strings s1 and s2 lexicographically Returns a value that is less than equal to or greater than 0 depending on whether s1 is lexicographically less than equal to or greater than s2 b int strncmpconst char s l const char s2sizet n same as strcmp except compares at most n characters stopping when nth characters are compared or a null is reached whichever happens first 5 char strstrconst char s1const char s2 searches in st for the first occurence of the substring s2 If the search is successful a pointer to the base address ofthe substring in s1 is returned otherwise a NULL pointer is returned 6 char strchrconst char strint c searches in str for the first occurrence of the character c lfthe search is successful the address of the character is returned otherwise a NULL pointer is returned Conversioninclude ltstdlibhgt All ato functions behave similarly in that they are used to convert a string to a value The string itself does not change the value ofthe appropriate type is returned The string can begin with white space which is ignored The conversion stops at the first inappropriate character If no conversion takes place 0 is returned 1 double atofconst char s returns equivalent floating point number as a double 2 int atoiconst char s returns equivalent integer number Character Functions Input a single character include ltstdiohgt int getcharvoid returns next character read from standard input or EOF if end of file declared as int rather than char because value of EOF may not be in range allowed for char data type int fgetcFlLE returns next character read from file pointed to by argument or EOF if end of file or error int getcFlLE same as fgetc except usually implemented as macro Output a single character include ltstdiohgt int putcharint character write single character argument to standard output may not actually appear until new line is written due to buffering Returns character written or EOF in case of error int fputcint character FILE fileptr writes character which is first argument to file pointed to by fileptr returns the character written if successful or EOF in case of error int putcint character FILE fileptr same as fputc except usually implemented as macro All ofthe following require include ltctypehgt Testing a character All these functions take a single character argument and return a nonzero true value ifthe test is true and zero false if the test is false int isalnumint c is alphanumeric int isalphaint c is alphabetic int iscntrlint c is control character int isdigitint c is digit int islowerint c is lowercase letter int ispunctint c is punctuation int isspaceint c is white space int isupperint c is uppercase letter Converting a character int tolowerint c given an uppercase letter c the equivalent lowercase letter is returned otherwise c is returned int toupperint c given a lowercase letter c the equivalent uppercase letter is returned otherwise c is returned
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'