New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Dr. Garrison Mohr


Dr. Garrison Mohr
GPA 3.87

Wayne Goddard

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Wayne Goddard
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 27 page Class Notes was uploaded by Dr. Garrison Mohr on Saturday September 26, 2015. The Class Notes belongs to CP SC 111 at Clemson University taught by Wayne Goddard in Fall. Since its upload, it has received 50 views. For similar materials see /class/214263/cp-sc-111-clemson-university in ComputerScienence at Clemson University.

Similar to CP SC 111 at Clemson

Popular in ComputerScienence




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/26/15
A Rudimentary Intro to C programming Wayne Goddard School of Computing Clemson University 2008 Part 4 Strings and Pointers 18 Strings D1 19 String Functions D3 20 Pointers D5 21 Strings and Pointers D7 22 More on Pointers D10 CpSc111 7 Goddard 7 Notes Chapter 18 Strings 181 Strings are Nullterminated Arrays We have used strings with double quotesithese are constant strings But what about testing and changing strings In C a string is a null terminated sequence of characters that is there is a special characteriwritten 390397after the last normal character The standard approach for a user created string is to store it inside a character array In particular this means that the array must have size at least 1 more than the length of the string For example a string like quothappyquot which has length 5 is stored in a char array of size at least 6 as 0 1 2 3 4 5 6onwards an Constant strings like the ones we provide to printf automatically have the null character added to them But any user created string must have 39039 explicitly added To print a string with printf or read a string with scanf use oos Note that scanf is passed just the name of the char array well see why laterino ampersand Also scanf ignores whitespace before the string and treats a whitespace as the end of string So if you want to read a string that might have a space in it you need to read in one char at a time using getcharO 182 Example Program stringReadc stringReadC adapted from Jamsa read a string from user and echo it include ltstdiohgt const Char EDL n const int SIZE 100 int mainvoid Char stringA SIZE stringB SIZE int index Char letter read a string using getchar D1 printfquotEnter string A quot index 0 letter getchar while letter EDL stringAindeX letter indeX letter getchar stringAindeX O read a string using scanf printfquotEnter string B quot scanfquotsquot stringB printfquotThe first string was snquot stringA printfquotThe second string was snquot stringB return 0 has sample output Enter string A happy days Enter string B happy days The first string was happy days The second string was happy Practice Adapt the above program to read a sentence7 terminated by a period D2 CpSc111 7 Goddard 7 Notes Chapter 19 String Functions You can create your functions to do many things with strings For standard tasks7 there are function in the string library 191 Creating Your Own String Function Almost all string functions have a main loop that iterates until the end of the string is detected For example7 here is code to compute the length of a string int strlenchar s int X 0 while sx 0 XX1 return X It returns 5 when called by Char test quothappyquot strlentest Or suppose you wanted to convert a string to all capitals void toUpperCaseChar s int X for XO sX O X if sXgt a ampamp sxlt z SEX 7A7 7a7 192 String Library Further string functions are available in the string library But beware If the array you are copying to is not big enough7 then crash the null character terminator gets lost These functions include o strcpydestsrc copies one string into another 0 strcatdestsrc appends one string to another D3 o strlens returns the string length 0 strcmpfirstsecond compares the strings alphabetically it returns a negative value if the rst comes before the secondl7 0 if the two strings are the same7 and a positive value if the rst comes after the second The only one you have to know is strlen 193 Example Program stringLibraryc include ltstdiohgt include ltstringhgt int main void Char alpha I39alphaquot Char beta I betaquot Char final100 strcpy final alpha if strcmp f inal alpha O true printf quot os and oos are the samenquot final alpha strcat finalbeta final is now I alphabetaquot if strcmp f inal alpha gt0 true printfquots comes after snquot final alpha return 0 D4 CpSc111 7 Goddard 7 Notes Chapter 20 Pointers 201 Computer Memory We have thus far ignored the details of how variables are stored in memory Indeed in some high level languages this ignorance is encouraged But in C one is encouraged to know and exploit how variables are stored Memory is arranged as a collection of cells numbered from 0 up to how ever many is available on the machine A single variable is stored in a cell or in a block of cells depending on its size We shall see that a cell is big enough to store a single character but a string is stored in a block of cells Indeed any array is stored as a block of cells So what happens when we de ne a variable say int A The compiler and operating system together choose a memory cell to store Aiyou can think of a name tag stuck on the cell door But this cell also has a numberiwhat we call the address of A We have already seen that ampA will give us this address But other than passing that information to scanf we have not used this address 202 Pointers Addresses and Dereferences The language C has a data type called a pointer This is a variable that stores the address of another variable Pointers use the notation In fact pointer syntax uses stars in two dz erent meanings We declare that a variable is a pointer by prefacing it with a star int p Note that while an address is really just a number a pointer holds the address of a variable of a speci c type That is the pointer p stores the address of a variable of type int Well actually at the start p contains garbage until we initialize it We say it points to a speci c cell in memory We initialize a pointer by setting it to the address of a variable This can be done in two ways either set it to the address of some variable using the amp notation or set it to another pointer Here is the former int p ampA Now we need to be able to work with the variable that p points to This value is accessed by p sometimes called demferencing The following code creates a variable x and a pointer p to it Once that is set up changing the value of p changes the value of x and vice versa D5 intx2 int p ampX printfquotdquotp prints 2 p 11 printfquotdquotx prints 11 X 5 printfquotdquotp prints 5 because p still points to X 203 Pointer Arithmetic and Arrays lncrementing a pointer moves it to the next cell77 in memory The actual change in the address depends on the size of the variable that the pointer points to This pointer arithmetic is useful in array manipulation The pointer can be initialized with the name of the arrayibecause the name of the array is equivalent to the address of the rst cell lndeed7 the name of the array is a pointer The following code prints out the array int B 14916 int p B initialize p to point to start of array B forint i0 ilt4 i printfquotdquot p p J It is good practice to set unused pointers to NULL a special constant de ned in C to be equal to 07 to emphasize that we know its not yet or no longer usable D6 CpSc111 7 Goddard 7 Notes Chapter 21 Strings and Pointers 211 Strings via Pointers We have seen that in C a string is stored as an arry of chars It turns out that any block of chars can be interpreted as a string This block can be accessed Via the array name or more generally Via a pointer In general a string function can take as its argument either an array name or a pointer to the rst char in the string Here is another implementation of the function to calculate the length of a string using pointer arithmetic int strlenchar s int lenO while s O s 1en return len We can use pointer arithmetic to achieve the same effect int strlenchar s Char t s while t O t return t s Here is a further implementation of strlen that uses the fact that the O character is equal to zero when used in a calculation That is the boolean condition s is true if s is nonzero meaning 5 points to anything except the O character It also uses the comma construct which for example allows two statements to be included in the update portion of a for loop int strlenchar s int XO for s s X notice the comma empty body return X D7 So7 most of the time when you see char P written7 the pointer P is going to point to the rst char in some string But sometimes it really points only to a single char Only later code or comments can clarify which 212 Example Program strstrc The following program contains a function that searches for the rst occurrence of one string called needle inside another called haystack strstrc adapted from nkraft Find first occurrence of substring needle in string haystack include ltstdiohgt The function returns pointer to beginning of substring or NULL if substring is not found char strstr char haystack char needle char start forstart haystack start O start char p needle char q start while p 707 ampamp q o ampamp p q P q if p O return start reached end of needle without mismatch return NULL int main void char one quotconcatenatequot char two quotcatquot char ans strstr one two if ans NULL printf I39needle not foundnquot else printf quotneedle starts in position d of haystacknquot ans one D8 return 0 213 Changing Strings One can also write code that alters a string For example7 what does the following code do to a string that was de ned by char beth while beth 7 beth It removes any leading spaces But note that this assumes that beth is stored in an array lfone writes a declaration as Char beth quot happyquot7 the string happy77 is a constant and not alterable you7ll get a segmentation fault D9 CpSclll 7 Goddard 7 Notes Chapter 22 More on Pointers 221 Pass by Value In C7 all function arguments are passed by value That is7 the function receives a copy of the value7 and cannot change the original So while the contents of an array that is passed to a function can change7 ints passed to a function cannot change And yet scanf does its job The solution is that you can pass the function the address of a variable For example7 a function to swap the values of two numbers uses pointers swaps the values pointed to by a and b void swapint a int b int temp a a b b temp The calling code might look something like int Xy X and y initialized swap ampX ampy An array is automatically passed as an address7 equivalent to a pointer to the base type 222 Dynamic Memory Allocation One can create an array on the y this uses dynamic memory allocation This is espe cially important for arrays and more advanced structures that exist only temporarily The function calloc is contained in stdlibh lt reservesallocates and initializes a block of memory The function takes two int arguments the rst argument is the number of elements to be stored and the second argument is the size in bytes think cells of the element that is to be stored which is obtained using the sizeof The calloc function returns the address of the beginning of the block int intPtr intPtr calloc 1000 sizeofint intPtr 10 will create an array with 1000 elements and set the rst value to 10 the rest being zero Memory that is allocated with calloc must be released afterwards using the free command freeintPtr This allows memory to be recycled A Rudimentary Intro to C programming Wayne Goddard School of Computing Clemson University 2008 Part 2 Decisions and Repetition For Loops Bl While Loops and Other Loops B4 lfs B6 More lfs B8 Booleans B11 Programming lssues B14 CpSclll 7 Goddard 7 Notes Chapter 6 For Loops Loops are designed for repetition 61 Boolean Conditions and Relational Operators A boolean condition is an expression that is either false or true A simple boolean condition is a comparison between two values using one of the six relational opera tors ltgtltgt The tests for equality the tests for inequality There must be no space between the characters in these operators We will see later how to make more complex conditions 62 The For Loop A loop is used when you have code to be repeated A forloop is often used when you know how many times something needs to be repeated This is sometimes called count based looping The basic structure is int indexvar for indexvar initvalue continuecondition update indexvar bodycode l The code that is repeated each time is called the body The variable that keeps track of the number of times through the loop is called the index variable Execution of the for loop is as follows Initialize index variable Check condition If false then stop Execute body code Update index variable Goto 2 Uiqgtcowgta B1 For example7 here is C code to count from 1 up to 10 int i fori1 ilt10 i printfquotdquot i Note that braces are optional if the loop body consists of only one statement It is important to note that the continue condition is checked before the body is executed so it is possible that the body will not be executed at all 63 Over ow Both the int and the double oat types have nite precision As a consequence7 one can over ow them or get incorrect results 64 Sample Program factorialc This program prints out the factorials up to a given value Note that it uses the previous value of fact to get the new value of fact calculates first few factorials will overflow wdg 2008 include ltstdiohgt int main void int max fact current printfquotlnput max quot scanfquotdquot ampmax fact 1 for current 1 currentlt max current fact fact current printfquotd is dnquot current fact return 0 B2 Run the program If you put in a large value of max7 the value of fact will over ow an int variable can only store values within a xed range 65 Nested Loops and Sample Program squareDraWc A loop within a loop is called a nested loop there is an outer and an inner loop Here is a program to draw a square of stars7 such as Notice that the body of the outer i loop prints a single row of stars This program draws a square of stars wdg 2008 include ltstdiohgt Main function int mainvoid const int SIZE5 const Char GLYPH int ij foriO iltSIZE i forj0 jltSIZE j printfquot oCquot GLYPH printf I39nquot return 0 Practice Adapt the above program to print a triangle of stars7 rather than a square B3 CpSclll 7 Goddard 7 Notes Chapter 7 While Loops and Other Loops 71 The While Loop The second common loop is the whileloop The basic structure is while continuationcondition bodycode As in the for loop7 the body might never be executed As an example7 here is code to count up to 10 with a while loop int i1 while ilt1O printfquot odquot 1 i Note that initialization occurs before the loop7 and update occurs at the end of the body The while loop is often used for sentinel based looping a sentinel is a distinguish ing value that tells the loop to stop For example7 the user inputs values until she inputs 1 not to continue 72 Other Loop Stuff There is also a do loop which is occasionally useful Also occasionally useful are the break and continue constructs these allow one to jump out or jump ahead in a loop well do an example later B4 73 Sample Program averagec This program averages some user supplied numbers include ltstdiohgt Main function int mainvoid int count 0 float value average float totalSoFar 00 printfquotEnter first value negative to finish quot scanfquotfquot ampvalue while valuegt00 count totalSoFar value printfquotEnter next value negative to finish quot scanfquotfquot ampvalue average totalSoFarCount printfquotAverage is 2fnquot average return 0 B5 CpSclll 7 Goddard 7 Notes Chapter 8 Ifs 81 The If Statement The if statement is the primary selection control structure The format is if condition thencode The condition is a boolean condition as before If the condition is true the thencode is executed if the condition is false the thencode is skipped A statement is a single piece of code a block is several statements enclosed in braces Here is an example if gradePointAverage gt 30 printfquotScholarship retainedquot 82 Sample Program listMaXc Here is a standard way of determining the maximum of a collection of values The idea is to maintain a variable maxSoFar with the maximum value seen so far this variable is updated each time a new value is seen by comparing it with that value There is a standard problem of how to initialize the value of maxSoFar This program sidesteps this by assuming that all values are nonnegative7 and therefore the maximum is at least zero Another approach is to initialize the value of maxSoFar to the rst value that is read calculate maximum of user input Assumes values nonnegative wdg 2008 include ltstdiohgt int mainvoid const int LENGTH 10 printfquotEnter ood valuesnquot LENGTH float maXSoFar 00 B6 int 1 float value fori0 iltLENGTH i printfquotEnter value quot scanfquotfquot ampvalue if value gt maXSoFar maXSoFar value printf quotMax is Z41fnquot maXSoFar return 0 B7 CpSclll 7 Goddard 7 Notes Chapter 9 More Ifs 91 The If Else Statement A more general version of the if statement is the ifielse structure for executing a statement when the condition is not true Here the format is if condition thencode else otherwisecode Here is an example ifdenom0 printfquotUnable to process fractionquot else printfquotFraction in decimal is Z42fquot floatnumerdenom Note the cast77 is the previous line it tells the compiler to treat the numer value as a oat In other words7 the else part is optional A common error is to miss the semi colon before the else7 or to have a semi colon after the condition 92 Selection from More Choices The otherwisecode might itself be an ifielse construct This is commonly thought of as if ese if ese Here is an example if waterTempgt1000 printfquotGasquot else if waterTempgt00 printfquotLiquidquot else printfquotSolidquot 93 The Switch Statement If you have a long sequence of else if77 statements all testing equality of the same variable7 then you might prefer a switch statement The following code looks at the B8 value of key and does the appropriate action more usually a switch is done with an int variable At execution7 the value of key is examined and control jumps to the appropriate label given by case statement default is like an else char key switch key case A printfquotalphaquot break case B printfquotbravoquot break case C printfquotcharliequot break default printfquotzuluquot break The break command transfers execution to the rst statement after the switch Without the break7s7 an A would trigger all four printf7s 94 Sample Program graderc This program converts user supplied number to letter grade wdg 2008 include ltstdiohgt Main function int mainvoid float rawGrade char letterGrade printfquotEnter grade quot scanfquotfquot amprawGrade if rawGradelt00 printfquotCannot be negativequot else if rawGradegt900 letterGrade A else if rawGradegt800 letterGrade B else if rawGradegt700 letterGrade C B9 else rawGradelt700 letterGrade F printfquotValue 2f is worth a Cnquot rawGrade letterGrade return 0 CpSc111 7 Goddard 7 Notes Chapter 10 Booleans 101 Boolean Variables A ag is a variable that has only two possible values think truefalse or onoff In C a ag is often simulated by an int variable Note that C interprets U as false and arty other value as true An example usage could be where we have a loop that can end for many reasons bad input7 problem solved7 time elapsed In this case7 we do a loop which repeatedly checks the ag in the body of the loop there are several places where the ag can be set to set a ag is to make it true to clear a ag is to make it false Other programming languages such as C and Java have a boolean data type built in This can be achieved in newer versions of C by loading the stdbool header include ltstdbool hgt bool done false while done if done true if done true 102 Logical Operators For more complex boolean conditions7 one can combine conditions with one of the logical operators The three most common of these are ampamp The ampamp means and the overall condition is true if both parts are true The means or the overall condition is true if either or both parts are true sometimes called the inclusive or The operator means not it converts false to true and vice versa It is useful to know that the logical operators have lower precedence than the other operators such as arithmetic and relational So to test if a given char is an upper case letter7 it is suf cient to write as follows without more brackets if myChar gt A ampamp myCharlt Z B11 It is also sometimes useful to know that the ampamp and I are shortcircuit evaluators for example7 if the rst part of an ampamp evaluates to false7 so that the result is guaranteed to be false7 then the remaining part is not evaluated For example7 to do something with a fraction might write if denomO ampamp numdenom gt threshold If it turns out that denom is zero7 then the division will not be performed and so one will not trigger a division by Zero problem 103 Sample Program sequencec Here is a program that reads in a sequence from the user and then prints a message as to whether the sequence is strictly increasing7 strictly decreasing7 or neither reads 10 numbers from user and says whether increasing or decreasing include ltstdiohgt include ltstdboolhgt int main void const int LENGTH 10 bool islncreasing true isDecreasing true float prev current int i foriO iltLENGTH i printfquotEnter value quot scanfquotfquot ampcurrent if igtO ampamp currentltprev islncreasing false if igtO ampamp currentgtprev isDecreasing false prev current if islncreasing printfquotls strictly increasingnquot else if isDecreasing printfquotls strictly decreasingnquot else printfquotNot strictly monotonicnquot B12 return 0 CpSc111 7 Goddard 7 Notes Chapter 11 Programming Issues We mention some more issues brie y 111 Style Good programming means extensive comments and documentation At the very least one should always explain the purpose of each variable You should also strive for a consistent layout and for expressive variable names 112 Testing Testing should fully exercise your code You should use both normal data and excep tional data Pay special attention to outlying data or boundary values 0 as a value an empty list etc Add watches or debug statements or printouts so that you know what is happening at all times 113 Development Try to get the program working one part at a time Print out print out Print out partial results print out what you7ve just read print out a message to say where you are etc Don7t make assumptions


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


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'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.