Programming Fundamentals II
Programming Fundamentals II CSCI 152
Popular in Course
Janiya Renner MD
verified elite notetaker
Popular in ComputerScienence
This 79 page Class Notes was uploaded by Janiya Renner MD on Friday October 30, 2015. The Class Notes belongs to CSCI 152 at Texas A&M University - Commerce taught by Staff in Fall. Since its upload, it has received 9 views. For similar materials see /class/232410/csci-152-texas-a-m-university-commerce in ComputerScienence at Texas A&M University - Commerce.
Reviews for Programming Fundamentals II
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/30/15
CSCI 152 Programming Fundamentals ll iSummer 2008 Control Structures Selection amp Looping controls June 5 2008 Objectives g election Control Structures Ch 4 In this lecturechapter you should review and Examine relational and logical operators Explore how to form and evaluate logical Boolean expressions Discover how to use the selection control structures if ifelse and switch in a program Control Structures A computer can proceed In sequence Selectively branch making a choice Repetitively iteratively looping Some statements are executed only if certain conditions are met A condition is represented by a logical Boolean expression that can be true or false I A condition is met if it evaluates to true 3 Sequence b Selectiun c Repetition Figure 41 Flaw of executiun Relational Operators Relational operators Allow comparisons Require two operands binary Return 1 if expression is true 0 otherwise Comparing values of different data types may produce unpredictable results For example 8 lt 39539 should not be done Any nonzero value is treated as true I Table 41 Relational Operators in C 3 equal to I not equal to lt less than less than air equal to 2 grealer than gt greater than nr equal tn Logical Boolean Operators Logical Boolean operators enable you to combine logical expreSSIons Three logical Boolean operators not ampamp and or Logical operators take logical values as operands and yield logical values as results is unary ampamp and H are binary operators Putting in front of a logical expression reverses its value OneWay if Selection f I The syntax of oneway selection is ifexpression statement I Statement is executed if the value of the expression is true I Statement is bypassed if the value is false program goes to the next statement OneWay if Selection N conUnued The expression is sometimes called a decision maker because it decides whether to execute the statement that follows it The statement following the expression is sometimes called the action statement The expression is usually a logical expression The statement is any C statement 3 Figure 42 Oneway selection TwoWay ifese Selection I Twoway selection takes the form ifexpression statementl else statement2 If expression is true statementl is executed otherwise statement2 is executed statementl and statement2 are any C statements else is a reserved word Figure 4 3 Two way safemen Compound Block of itatement I Compound statement block of statements statementl statement2 statementn I A compound statement is a single ml InmnnI Compound Statement Example 39 fage gt 18 coutltltquot Eligible to votequotltltendl coutltltquot No longer a minorquotltltendl else coutltltquotNot eligible to votequotltltendl coutltltquotStill a minorquotltltendl Nested if Nesting one control statement in another I An else is associated with the most recent if that has not been paired with an else I For example ifscore gt 90 coutltltquotThe grade is Aquotltltendl else ifscore gt 80 coutltltquotThe grade is Bquotltltendl else coutltltquotThe grade is Fquotltltendl switch Structures 7 Switch structure alternate to if else Switch expression is evaluated first Value of the expression determines which corresponding action is taken Expression is sometimes called the colorinr switch Structures continued Expression value can be only integral I Its value determines which statement is selected for execution A particular case value should appear only once lms E q Figure 44 switch statement switch Structures Vcontinued 39 One or more statements may follow a case label Braces are not needed to turn multiple statements into a single compound statement I The break statement may or may not appear after each statement switch case break and default are reserved words switch Statement Rules I When value of the expression is matched against a case value I Statements execute until break statement is found or the end of switch structure is reached I If value of the expression does not match any of the case values I Statements following the default label execute If no default label and no match the entire switch statement is skipped I A break statement causes an immediate AL C LIA LI LL Summary I Control structures alter normal control flow I Most common control structures are selection and repetition I Relational operators lt lt gt gt I Logical expressions evaluate to 1 true or 0 false I Logical operators not ampamp and H orl Summary 39 I Two selection structures oneway selection and twoway selection I The expression in an if or ifese structure is usually a logical expression I A sequence of statements enclosed between braces and is called a compound statement or block of statements I Switch structure handles multiway selection Objectives Looping Control Structures Ch 5 In this lecturechapter you should review and I Learn about repetition looping control structures Explore how to construct and use count controlled sentinelcontrolled flagcontrolled and EOFcontrolled repetition structures Examine break and continue statements Why Is Repetition Needed Repetition allows you to efficiently use variables I Can input add and average multiple numbers using a limited number of variables I For example to add five numbers Declare a variable for each number input the numbers and add the variables together Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers The while Loop The general form of the while statement is whileexpression statement while is a reserved word Statement can be simple or compound Expression acts as a decision maker and is usually a logical expression The while Loop continued Expression provides an entry condition Statement executes if the expression initially evaluates to true Loop condition is then reevaluated Statement continues to execute until the expression is no longer true The while Loop continued Infinite loop continues to execute endlessly Can be avoided by including statements in the loop body that assure exit condition will eventually be false Figure 51 while lonp CounterControlled while Loops If you know exactly how many pieces of data need to be read the while loop becomes a counter controlled loop I The syntax is counter O whilecounter lt N counter SentinelControlled while Loops Sentinel variable is tested in the condition and loop ends when sentinel is encountered The syntax is cingtgtvariable whilevariable sentinel cingtgt variable FlagControlled while Loops 39 A flagcontrolled while loop uses a Boolean variable to control the loop The flagcontrolled while loop takes the form found false whiefound ifexpression found true EOFControlled while Loops 7 Use an EOF End Of Filecontrolled while loop The logical value returned by cin can determine if the program has ended Input The syntax is cin gtgt variable while cin cin gtgt variable The eof Function The function eof can determine the end of file status Like other O functions get ignore peek eof is a member of data type istream The syntax for the function eof is istreamVareof where istreamVar is an input TheforLoop I The general form of the for statement is forinitial statement loop condition update statement statement The initial statement loop condition and update statement are called for loop control statements false up ate statement Figure 52 for loop TheforLoopcoanued The for loop executes as follows initial statement executes loop condition is evaluated If loop condition evaluates to true Execute for loop statement Execute update statement Repeat previous step until the loop condition evaluates to false initial statement initializes a variable TheforLoopconUnued gl initial statement in the for loop is the first to be executed and is executed only once I If the loop condition is initially false the loop body does not execute I The update expression changes the value of the loop control variable which eventually sets the value of the loop condition to false I The for loop executes indefinitely if the loop condition is always true TheforLoopconUnued Fractional values can be used for loop control variables A semicolon at the end of the for statement is a semantic error In this case the action of the for loop is empty If the loop condition is omitted It is assumed to be true TheforLoopconUnued In a for statement all three statements initial statement loop condition and update statement can be omitted The following is a legal for loop for coutltltquotHeIoquotltltend Summary 7 I C has three looping repetition structures while for and dowhie I while for and do are reserved words I while and for loops are called pretest loops CSCI 152 Hierarchical Nested Structures GLOBAL TYPE DECLARATIONS 1 struct Date 2 3 int month 4 int day 5 int year 6 7 struct Machine 8 9 int id 10 bool serviceContract 11 float failRate 12 Date lastServiced 13 int downDays 14 Date purchaseDate 15 float co 16 float deprValue 17 LOCAL VARIABLE DECLARATIONS 18 Date yesterday 9 today 20 Machine press 21 Machine station 100 The following statements demonstrate references to fields fully qualified names must be used for all field identifiers 22 cout ltlt quotDate quot ltlt todaymonth ltlt quotquot ltlt todayday ltlt quotquot ltlt todayyear 23 cout ltlt quotMachine quot ltlt pressid ltlt endl 24 cout ltlt quotPurchase date quot ltlt presspurchaseDatemonth ltlt quotquot 25 ltlt presspurchaseDateday ltlt quot 26 ltlt presspurchaseDateyear ltlt endl 27 cout ltlt quotOriginal cost quot ltlt setprecision2 ltlt presscost ltlt endl 28 cout ltlt quotDepreciation value quot ltlt pressdeprValue ltlt endl 29 cout ltlt quotTotal down days since purchase quot ltlt pressdownDays ltlt endl 3O cout ltlt quotLast serviced quot ltlt press1astServicedday ltlt quot 31 ltlt press1astServicedmonth ltlt quot 32 ltlt press1astServicedyear ltlt endl 33 if pressfailRate gt 010 34 cout ltlt quotExcessive downtimenquot 35 if i pressserviceContract or if pressserviceContract false 36 cout ltlt quotService contract has expirednquot The only defined operations for structure variables the entire structure of the same type are assignment pass as a parameter to a function either by value or by reference return by a function 37 presslastServiced today is equivalent to 38 press1astServicedmonth todaymonth 39 press1astServicedday todayday press lastServiced year today year station5 press is equivalent to station5id pressid station5serviceContract pressserviceContract 5failRate pressfailRate station51astServicedmonth press1astServicedmonth station51astServicedday press1astServicedday station51astServicedyear press1astServicedyear station 5downDa s pressdownDays station5purchaseDatemonth presspurchaseDatemonth station5purchaseDateday presspurchaseDateday station5purchaseDateyear presspurchaseDateyear station 5cost presscost station 5deprValue pressdeprValue Arrays as fields in a structure Type declarations struct COURSE string dept int int char i courseNum section letterGrade struct ADDRESS string street string CityState string zipCode i struct STUDENT string me ADDRESS localAddress ADDRESS permanentAddress COURSE i gradeslO Variable declarations COURSE ADDRESS STUDENT STUDENT To refer to The number of my course My zip code The name of the first student The initial of the second student The fourth grade of the tenth student DJ I Fr myCourse myAddress udent studentslOO Use this name myCoursecourseNum myAddresszipCode students0name studentslname0 students9grades3letterGrade The local address a record of the last student students 99 localAddress The zip code of the local address of the first student students 0 localAddress zipCode CSCI 152 Programming Fundamentals Summer 2008 User Defined Functions June 5 2008 Objectives User Defined Functions Ch 6 amp 7 In this lecturechapter you should review and I Learn about userdefined functions I Examine valuereturning functions including actual and formal parameters I Explore how to construct and use a value returning userdefined function in a program I Learn how to construct and use void FuncUons Functions are like building blocks They allow complicated programs to be divided into manageable pieces Some advantages of functions A programmer can focus on just that part of the program and construct it debug it and perfect it Different people can work on different functions simultaneously Can be used in more than one place A A nunmuA A u AIC AAAI nunmuAmAA UserDefined Functions I Void functions do not have a data type I Valuereturning functions have a data type I To use these functions you need to I Include the correct header file Know the name of the function Know the number of parameters if any Know the data type of each parameter Know the data type of the value computed by the function called the type of the 1 ARI lam ValueReturning Functions Because the value returned by a valuereturning function is unique we must Save the value for further calculation Use the value in some calculation Print the value A valuereturning function is used in an assignment or in an output ValueReturning Functions v5continued properties that formithe fUthiO definition 1 Name of the function 2 Number of parameters 3 Data type of each parameter 4 5 Type of the function Code required to accomplish the task the body of the function ValueReturning Functions continued I Heading first four properties above Formal Parameter variable declared in the heading Actual Parameter variable or expression listed in a call to a function ValueReturning Functions continued The syntax is functionType functionNameformal parameter list statements functionType type of the value returned by the function Also called the data type Syntax The syntax of the formal parameter list is dataType identifier dataType identifier The syntax for a function call is functionNameactual parameter list The syntax for the actual parameter list is expression or variableexpression or FuncUons I The formal parameter list can be empty I If the formal parameter list is empty I Parentheses are still needed I Function heading of the valuereturning function takes either of the following forms functionType functionName functionType functionNamevoid I In a function call the actual parameter is empty I A call to a valuereturning function with an empty formal parameter list is functionName ValueReturning Functions To call a valuereturning function Use its name with the actual parameters if any in parentheses There is a onetoone correspondence between actual and formal parameters ValueReturning Functions continued A valuereturning function is called in an expression Expression may be part of an assignment statement or an output statement A function call in a program results in the execution of the body of the called function The return Statement g Once the function computes the value the function returns the value via the return statement The syntax of the return statement Is return expression or variable When a return statement executes Function immediately terminates Control goes back to the caller When a return statement executes in the function main the orooram Function Prototype 39 Function Prototype function heading without the body of the function The syntax is functionType functionNameparameter list It is not necessary to specify the variable name in the parameter ist The data type of each parameter must be specified Flow of Execution g Execution always begins at The first statement in the function main no matter where main is placed in the program Other functions are executed only when they are called Flow of Execution Continued Function prototypes appear before any function definition The compiler translates these first The compiler can then correctly translate a function call Flow of Execution Econtinued A function call statement results in Transfer of control to the first statement in the body of the called function After the last statement of the called function is executed Control is passed back to the point immediately following the function call Flow of Execution gcontinued A valuereturningifunction returns a value After executing the function The value that the function returns replaces the function call statement Summary I Functions modules are miniature programs I Functions enable you to divide a program into manageable tasks I C provides the standard functions I Two types of userdefined functions valuereturning functions and void functions I Variables defined in a function heading are called formal parameters I Expressions variables or constant Inlimc in a flinrl39inn rnll am r nllnrl Summary I In a function call the number of actual parameters and their types must match with the formal parameters in the order given I To call a function use its name together with the actual parameter list I Function heading and the body of the function are called the definition of the function I If a function has no parameters you need empty parentheses in heading and call A Inrnhrninn 39Fllnrl39inn rnhlrnc il39c Summary A prototype is the function heading without the body of the function prototypes end with the semicolon Prototypes are placed before every function definition including main Userdefined functions execute only when they are called In a call statement specify only the actual parameters not their 42139 hnnc CSCI 152 Simple Structures GLOBAL TYPE DECLARATIONS mmiwaH struct Date l int int int l struct Machine l id serviceContract failRate downDays cost deprValue int bool float int float l LOCAL VARIABLE DECLARATIONS 16 17 18 19 Date yesterday Date today i 3 2 2004 i compiletime initialization Machine press Machine station 100 The following statements demonstrate references to fields fully qualified names must be used for all field identifiers You can do anything with a field that you can do with a single variable of the same type 20 21 22 cout ltlt quotDate quot ltlt todaymonth ltlt quotquot ltlt todayday ltlt quotquot ltlt todayyear ltlt endl cout ltlt quotMachine quot ltlt pressid ltlt endl cout ltlt quotOriginal cost quot ltlt setiosflagsiosshowpoint ltlt setprecision2 ltlt presscost ltlt endl cout ltlt quotDepreciation value quot ltlt pressdeprValue ltlt endl cout ltlt quot down days since purchase quot ltlt pressdownDays ltlt endl if pressfailRate gt MAXiFAILiRATE cout ltlt quotExcessive downtimenquot pressserviceContract false or iflpressserviceContract cout ltlt quotService contract has expirednquot if it The only defined operations for structure variables the entire structure of the same type are assignment pass as a parameter to a function either by value or by reference return by a function yesterday today is equivalent to these three statements yesterdaymonth todaymonth 31 32 yesterdayday yesterdayyear todayday todayyear Another example of structure assignments l lo t wm station5 7 press is equivalent to station5id pressid station5serviceContract pressserviceContract stationl5failRate pressfailRate stationlSdownDays pressdownDays stationl5lcost presscost stationl5deprValue pressdeprValue The following statements demonstrate references to elements of an array of structures Values are input from a text file to be assigned to successive elements of the station array do t w char contractCode int statioanr n bool found statioanr O number of elements currently assigned in array and subscript of next available array element while inFile gtgt stationstatioanrid gtgt contractCode i if contractCode 39YW stationstatioanrserviceContract true else stationstatioanrserviceContract false inFile gtgt stationstatioanrfailRate inFile gtgt stationstatioanrdownDays inFile gtgt stationstatioanrcost gtgt stationstatioanrdeprValue statioanr r l After the station array has been loaded it can be searched to see if a particular machine is represented in the array For example the following code will search the array to see if there is a match on press assume the press structure variable has been assigned values n 0 found false while n lt statioanr ampamp i found if stationnid pressid found true else n If press is not in the array insert it into the array in the next available position assuming there is space in the array if i l stationstatioanr statioanr found press structuretostructure assignment Arrays of Char VS C Strings Action Arrav of char Declare variable char array 5 Declare variable and initialize char array 5 39A39 39B39 39C39 39D39 39E39 or char array 39A39 39B39 39C39 39D39 39E39 Print first char cout ltlt array0 Print all chars for n 0 n lt 5 n cout ltlt arrayn Read first char cin gtgt array0 or arrayO cinget or cingetarray0 Read all chars for n 0 n lt 5 n cin gt gt arrayn Assign first char char ch to another variable ch array0 Assign all chars char copy 5 to another for n 0 n lt 5 n variable copy n array n Comparison Test for equality equal true for n 0 n lt 5 n if arrayn COPYn equal false break or or or or or or or or Strina char cstr 5 stores only 4 chars of a string char cstr 5 quotABCDquot char cstr5 39A39 39B39 39C39 39D39 39039 char cstr quotABCDquot char cstr5 39A39 39B39 39C39 39D39 39039 cout ltlt cstr0 cout ltlt cstr for n 0 cstrn 39039 n cout ltlt cstr0 cin gtgt cstr0 cstrO cinget cingetcstr0 cin gtgt cstr reads up to whitespace for n 0 n lt 4 n cin gtgt cstrn cstrn 39039 char ch ch cstr0 char copy 5 strcpy copy cstr strcpy copy quotCSCIquot or same as for the array of char strcmp cstr copy returns a value less than 0 if cstr lt copy or a value of 0 if cstr co or a value greater than 0 if cstr gt copy if strcmp cstr copy 0 String Operations found in C library ltcstringgt Operation Description strcat 51 52 strncat 51 52 n strcy 51 52 strncpy 51 52 n strlen s strcmp 51 52 strncmp 51 52 n strchr s c strrchr s c strstr 51 52 strpbrk 51 52 strspn 51 52 strcspn 51 52 Appends 52 to 51 Appends at most n characters of 52 to 51 Copies 52 into 51 Copies first n charcters of 52 into 51 Returns length of s not counting the terminating null character Compares 51 with 52 and returns an integer less than equal to or greater than 0 according to whether 51 is less than equal to or greater than 52 Same as strcmp but compares only the first n characters of 51 and 52 Returns a pointer to the first occurrence of c character in s or NULL if not found Like strchr but locates the last occurrence of c in 5 Returns a pointer to the first occurrence in 51 of 52 or NULL if not found Returns a pointer to the first occurrence in 51 of any character of 52 or NULL if not found Returns the number of characters in 51 before any character in 52 Returns the number of characters in 51 before a character not in 52 String Operations found in C library ltcstdibgt double atof 5 int atoi 5 long atoll 5 Returns the value obtained by converting the character string 5 to double Returns the value obtained by converting the character string 5 to int Returns the value obtained by converting the character string 5 to long int CSCI 152 C INTERACTIVE INPUT AND OUTPUT Output The insertion operator ltlt is used for general output of values of multiple types It has been defined to output values in a default format for all ofthe builtin basic C types Because of the way the operator is defined it is possible to output multiple values in the same statement by chaining them together with the ltlt insertion operator cout ltlt valuel ltlt valueZ is thesarneas cout ltlt valuel cout ltlt valueZ where the variables or constants or expressions may be of any of the builtn basic types The insertion operator converts values to text form By default values are displayed in a width equal to their size and formatted as follows char A type char value if it represents a printable character is displayed as a character in a field one character wide int Numeric integer types are displayed as decimal integers in a field just wide enough to hold the number and if the value is negative a minus sign float Floatingpoint types are displayed with 6 places to the right of the decimal except that trailing fractional zeros aren39t displayed If there are no significant digits to the right of the decimal point printing ofthe decimal point is suppressed along with the trailing zeros The number may be displayed in Enotation depending upon the value of the number which depends on the implementation being used Again the field isjust wide enough to hold the number and for a negative value a minus sign string Strings are displayed in a field width equal in width to the length ofthe string Examples of default field widths these defaults may vary from one compiler to another 1 i ncl ude lti ost reamgt 2 using nanespace std 3 int nai n value displayed Nm 1701 4 Gout ltlt 3939 ltlt quotNoo1701quot ltlt quotnquot 5 charch39K39 intt273 6 Gout ltlt 3939 ltlt ch ltlt quotnquot K 7 cout ltlt 3939 ltltt ltlt quotnquot 273quot 8 cout ltlt 3939 ltlt t ltlt quotnquot 273 9 double f1 1200 10 cout ltlt 3939 ltlt f1 ltlt quotnquot 11 cout ltlt 3939 ltlt f1 10 90 ltlt nquot H 1311111 12 double f2 16 13 cout ltlt 3939 ltlt f2 ltlt quotnquot 16000000 14 com ltlt W ltlt 2 10 9 0 ltlt quotnquot 16000000111111 5 Gout ltlt ltlt f2 20e5 ltlt quotnquot 162e07 16 float f323e4 cout ltlt 3939 ltlt f3 ltlt quotnquot39 000023 17 18 cout ltlt 3939 ltlt f3 10 ltlt quotnquot 2 3e05 The pant where the defaut siM39tches fromfXed t0 scentfc is dependent 0n the carrpfer you use 19 float f450 20 cout ltlt 3939 ltlt f4 ltlt quotnquot 5 21 return 0 To override any of C39s default formatting C provides manipulators which have special meaning in the context of input andor output constructs Each causes a corresponding library function to be called which changes the state of the specified stream as requested To use any of these manipulators simply insert them within the lO stream preceding the value they are to manipulate Manipulators Having No Parameters defined in iostreamh Manipulator Purpose dec Sets the stream39s radix base to decimal default endl Inserts a newline and flushes the stream output only By default output streams are buffered so use flush or endl to write out immediately ends Inserts a null character output only flush Flushes the stream output only hex Sets the stream39s radix base to hexadecimal oct Sets the stream39s radix base to octal ws Skips leading white space on input default The following manipulators were added as part of the new ANSI standard boolalpha Causes boolean values to be inputoutput as strings true and false instead of 1 and 0 noboolalpha Causes boolean values to be inputoutput as integers 1 and 0 fixed Causes float values to be displayed in fixed decimal format scientific Displays float values in exponential notation internal Pads after sign or base indicator to fill specified field width left Causes output to be leftjustified right Causes output to be rightjustified default showbase Shows the base for octal 0 and hexadecimal Ox numbers noshowbase Does not show the base for hexadecimal and octal output showpoint Shows the decimal point and trailing zeros for float values noshowpoint Suppresses display of decimal point for float values with a zero fractional part Displays trailing zeros for float values with a nonzero fractional part showpos Adds leading to positive numbers noshowpos Does not show for positive numbers default skipws Skips leading whitespace on input default noskipws Does not skip leading whitespace on input unitbuf Flushes the output buffer after each insertion operation nounitbuf Does not flush output buffer after each insertion operation uppercase Shows hexadecimal numbers and exponent in uppercase nouppercase Displays hexadecimal numbers and exponents in lower case If your program includes the statement using namespace std the preceding manipulators may be inserted directly into the output stream Without the namespace statement they can only be used with the setiosflags and resetiosflags manipulators below See the sample program on p 3 for examples of using them in a program Manipulators Having One Parameter defined in iomaniph Manipulator Purpose setprecision int p Sets the number of digits displayed after a decimal point for floats affects output only if the fractional portion ofthe number is nonzero setw int w Sets field width for next output value only setiosflags long f Sets format state flags specified inf resetiosflags long f Turn off reset to default the format state flags specified inf setbase int base Sets number base to 8 10 or 16 default is 10 setfill int ch Sets fill character default is blank The generalpurpose manipulators setiosflags and resetiosflags have a parameter of a set of bitflags Each open stream maintains a series of bitflags Each flag records whether a particular attribute is or is not set This set of flags records the stream39s format state In iostreamh an enumerated type is defined with a set of enumeration constant names for each format state Example 1 in 2 in 3 usi 4 int 5 6 7 8 9 1O 11 12 Output of using manipulators Clude ltiostreamgt or include ltiostreamhgt Clude ltiomanipgt or include ltiomaniphgt ng namespace std main cout ltlt setw10 ltlt 123 ltlt 12378 ltlt endl cout ltlt 3939 ltlt setw8 ltlt setprecision3 ltlt 12378 ltlt 3939 ltlt endl cout ltlt 3939 ltlt 15 ltlt 3939 ltlt 154321 ltlt 3939 ltlt endl cout ltlt left ltlt 3939 ltlt setw4 ltlt setprecision2 ltlt 10 ltlt 3939 ltlt endl If not using namespace std you have to do it the old way cout ltlt setiosflagsios1eft ltlt 3939 ltlt setw4 ltlt setprecision2 ltlt 10 ltlt 39 ltlt e cout ltlt showpoint ltlt right If not using namespace std you have to do it the old way cout ltlt setiosflagsios cout ltlt setiosflagsios cout ltlt setiosflagsios showpoint showpoint showpoint ltlt resetiosflagsios1eft ltlt setiosflagsiosright 39 szzri 39 r cout ltlt 3939 ltlt setw8 ltlt 10 ltlt 3939 ltlt endl cout ltlt setprecision1 ltlt fixed ltlt 3939 ltlt setw6 ltlt 1264 ltlt 3939 ltlt endl If not using namespace std you have to do it the old way cout ltlt setprecision1 ltlt setiosflagsiosfixed ltlt 3939 ltlt setw6 1264 ltlt 3939 ltlt endl return 0 1234567890123456 column positionm 12312378 1238 151543 1 A 100 A A 13 Input The extraction operator gtgt is used for general input of values of multiple types The extraction operator is defined for all the builtin basic C types As with the insertion operator it is possible to input values for multiple variables in the same statement by chaining them together with the extraction operator cin gtgt valuel gtgt value2 isthe same as cin gtgt valuel cin gtgt value2 To input a numeric value leading whitespace is skipped and then characters are input until a character inappropriate for the type is encountered The default input base is decimal numbers without an explicit base are assumed to be decimal but it is possible to input octal or hexadecimal values by explicitly entering the base 024 would be read as an octal 24 decimal 20 and 0x14 would be read as a hexadecimal 1 decimal 20 Leading whitespace is also skipped when characters and strings are input When a value is to be read for a char variable the first nonwhitespace character is input When a value is to be read for a string variable characters are read starting with the first nonwhitespace character until whitespace endofline blank tab endoffile is encountered Additional Functions for Specialized IO defined in iostreamh istream amp get char amp c inputs the next character even if it is whitespace storing the input character in the char parameter This form ofthe function returns 0 false if end of file is encountered before a character can be input Example cin get ch int get void inputs the next character even if it is whitespace returning the character input or returning EOF if end of file EOF is a predefined constant for the endoffile symbol Example ch Cinget or while ch Cinget i 39n39 read chars across a line until the endof line marker is found Examples of reading chars until the endofline marker n is found assume the declaration char ch a b c cin gtgt ch cingetch whilech39n39 whilech39n39 Whilechcinget39n39 cout ltlt ch cout ltlt ch cout ltlt ch cin gtgt ch cingetch Input for each program is the 7 characters H Nbrrl followed by the enter key n symbol Output for each program a b C Hi me Hi me Hi me contnues n an infnfe loop istream amp ignore int len 1 int delim EOF skips over a designated number of characters first parameter default is 1 or terminates upon encountering a designated delimiter second parameter default is EOF which causes ignore to skip to the end of file when reading from a file The delimiter is skipped Example cin ignore 0 or cin ignore 2 or cin ignore 80 39 n39 ostream amp put char c outputs one character the parameter supplied Example coutput 39 a39 make computer beep or coutput 39A39 ostream amp put int n outputs the char equivalent of the parameter assumed to be an ASCII number Example coutput7 make computerbeep or coutput65 display A39 int peek void returns next character in the input stream but does not remove the character from the stream that character remains to be read Example ch Cinpeek or while ch Cinpeek l 39 39 or while cinpeek 39 n39 int eof void returns true if end of file has been reached or returns false otherwise Example While l cin eof you d have to enter the endof e symbol from the keyboard for DOS it s Ctr Z for Mac and UNIXLinux it s Ctr D CSCI 152 Structures and Functions GLOBAL TYPES struct Date int month int day PR OTOTYPES FOR USER DEFINED FUNCTIONS void PrintDate Date GetDate void ChangeDate int ChangeMonth void ChangeDay void PrintMonth int main Date bDay pass a struct by value return a struct pass a struct by reference return a value to be assigned to a eld int 5 day pass a struct eld by reference int month pass a struct eld by value void Date amp rBd Date birthday Create a Date structure birthday GetDate PrintDate birthday ChangeDate birthday PrintDate birthday pass by value birthdaymonth ChangeMonth name of eld must be quali ed ChangeDay birthday day name of eld must be quali ed return 0 function returns a copy of the struct pass by value pass by address using a reference Date GetDate void Date bd cout ltlt quotnIn what month were you born gt 1 Jan 2 Feb cin gtgt bdmonth cout ltlt quotnOn what day of quot PrintMonth bdmonth cout ltlt quot were you born gt quot cin gtgt bdday return bd void ChangeDate Date amp rBd cout ltlt quotnIn what month were you born gt 1 Jan 2 Feb cin gtgt rBdmonth cout ltlt quotnOn what day of quot PrintMonth rBdmonth cout ltlt quot were you born gt quot cin gtgt rBdday void PrintDate Date bDay or void PrintDate const Date amp bDay prototype would also have to be changed cout ltlt quotnHappy birthday on quot PrintMonth bDaymonth cout ltlt quot quot ltlt bDayday These two functions demonstrate passing individual elds in a struct variable as parameters if you don t need to pass the whole structure When you call the function you have to qualify the eld name to identify the valueaddress to be passed but the function sees only a single variable and doesn t know that it is actually part of a structure We could just as easily pass to ChangeMonth or ChangeDay one value that is an element in an array of ints the function sees only an int int ChangeMonth Return type is not quali ed because the return value is not part of a struct here the return value could be assigned to any integer variable int month cout ltlt quotnIn what month were you born 1 Jan 2 Feb 39U cin gtgt month return month void ChangeDay int 5 day Note parameter name is not quali ed cout ltlt quotOn what day of the month were you bornnquot cin gtgt day void PrintMonth int month parameter is not quali ed The function doesn39t know the int is part ofa struct switch month case 1 cout ltlt quotJanuaryquot break case 2 cout ltlt quotFebruaryquot break case 3 cout ltlt quotMarchquot break case 4 cout ltlt quotAprilquot break case 5 cout ltlt quotMayquot break case 6 cout ltlt quotJunequot break case 7 cout ltlt quotJulyquot break case 8 cout ltlt quotAugustquot break case 9 cout ltlt quotSeptemberquot break case 10 cout ltlt quotOctoberquot break case 11 cout ltlt quotNovemberquot break case 12 cout ltlt quotDecemberquot break default cout ltlt quotinvalid month numberquot