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

Computational Physics

by: Jairo Dooley

Computational Physics PHY 4151C

Jairo Dooley
GPA 3.9

David Rabson

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

David Rabson
Class Notes
25 ?




Popular in Course

Popular in Physics 2

This 6 page Class Notes was uploaded by Jairo Dooley on Wednesday September 23, 2015. The Class Notes belongs to PHY 4151C at University of South Florida taught by David Rabson in Fall. Since its upload, it has received 38 views. For similar materials see /class/212685/phy-4151c-university-of-south-florida in Physics 2 at University of South Florida.


Reviews for Computational Physics


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/23/15
Physics PHY4151C fall semester 2003 First Week of C for Matlab Programmers Matlab is an interpreted language to run a Matlab program the user must be running Matlab Matlab is itself program one that reads the user s input for example the line v e eig m and decides what to do with it The user s input does not contain explicit instructions to the CPU central processing unit Matlab must convert what the user says into something the CPU understands The Matlab executable does consist of instructions coded as zeros and ones that correspond to instructions the CPU can execute However it s quite unlikely that the people who wrote Matlab sat down and started typing 0 1 1 0 0 0 0 1 1 0 1 0 0 1 1 1 Probably they wrote it in a compiled language like C The compiler is a program that takes humanreadable code rather reminiscent of a Matlab m le and converts it into the zeros and ones of a binary executable This tutorial will serve only as a rst introduction to C suitable for a light oneweek minicourse Really to understand C one should read the book There is only one worth owning written by the languages authors Kernighan and Ritchie The C Programming Language PrenticeHall ISBN 0131103628 approx 40 In particular this week s tutorial will not cover the language features that make C much more adaptable than Matlab such as pointers except tangentially structures and dynamic memory management 1 Writing a program that prints something on the screen Kernighan and Ritchie observe that the rst program to write is the same for all languages print the words hello world7 77 This will exemplify the skeletal structure of a program in the new language and demonstrate most of the steps required to make any program run Begin by entering the program with an editor Just as Matlab expected a program name to end in m the C compiler expects a program name to end in c so you should call your program something like hello c Unlike in Matlab the name of the le is not tied to the name of the subroutine inside in fact a C le may contain an arbitrary number of subroutines The circled notations are not part of the program don t enter them D hello c DAR 1103 Print Hhello world usage hello include ltstdlibhgt standard declarations include ltstdiohgt declarations for standard IO in mainvoid printf hello worldn n means the newline character return 0 required in ANSI C Notes D A comment in C begins with and ends at the rst instance of Line breaks are immaterial not just with comments Comments may not be nested These two lines include certain standard declarations so that the compiler will know what main and printf mean This particular program would have compiled correctly without them but it s a better idea to include them 3 This line and the next declare main as a function of no arguments void returning an integer The analogue in Matlab would be function imain77 Other subroutine names are arbitrary as in Matlab 1 but every program must have exactly one subroutine called main which will be the rst subroutine called when the program runs The open brace begins a block of code in this case the subroutine The matching close brace analogous to end in Matlab ends the block of code The string Hhello worldn is analogous to the same thing in Matlab but inside single quotation marks instead of double quotation marks he function printf prints its argument to standard output7 which is usually the screen7 but the user can redirect output to a le The sequence n stands for the single character newline77 Experiment to see what happens without it Every C statement77 must end in a semicolon Since C does not usually give any meaning to the end of a line7 semicolon takes its place in letting the compiler know when one statement ends and the next begins In Matlab terms7 it is as though every line of C automatically ends in 77 The lines that do not end in semicolon are not considered statements The subroutine main is required by the ANSI standard to return an integer which is passed back to the shell T e shell understands 0 to mean successful completion and nonzero to mean that the program did not complete successfully so here we return 0 Continuing the Matlab analogy of CD this line is analogous to i0 if i is the Matlab output variable C does not have output variables it returns a single value Structures and pointers provide mechanisms for returning more complicated things Now to compile and run the program I ll give the onestep command a program that consisted of several different c les would have to be compiled in two steps physicscasusf edu quot4 cc o hello hello c physics cas usf edu quot4 hello hello world physics cas usf edu quotA 2 Variables Matlab lets the programmer start using a new variable anytime she wishes C variables however7 must be declared and de ned before use For this tutorial the declaration7 telling the compiler what type a variable has7 and the de nition7 telling the compiler where to allocate storage for the variable are the same Here is a typical declaration int i Optionally one may usually initialize a variable on the declaration line int i42 All declarations in a program block enclosed in must precede the rst nondeclaration line The three simple types you will need in C are int which stores an integer of standard size for the machine 4 bytes on current hardware7 char7 which stores a single character 1 byte7 and double7 which stores a oatingpoint number All variables in Matlab are of type double7 which explains why one doesn t need to tell Matlab about types There are other simple types7 for example float and short7 but they re less common Arithmetic performed on an integer variable is automatically truncated7 as though one had called floor in Matlab int mainvoid int i17 double X y z declare three uninitialized doubles X i2 y i subtle difference z double i2 another way to achieve the same thing 2 printf Ihe value of X is quot4f but yf and zfn X y Z return 0 This example also illustrates how to print a double using printf There must be one additional argument to printf for each quot4f in the format string To print an int use quotd intead of quotti Do not use quotd to print a double7 even if you know as here that it will take an integral value doing so will pass the wrong number of bytes to pr intf and may result in a completely baf ing error at some apparently random point of execution later in the program Similarly you must be careful that the number of percentsign directives inside the format string matches the number of subsequent arguments Some alternative formats for printing a double include quot4e and quot g For more information7 consult the Unix manual page on printf physicscasusfedu quotA man 3 printf The 3 tells the Unix man command to look in Section 3 library subroutines rather than Section 1 commands that may be issued from the shell 3 Reading variables from standard input Here is some code to read one number the rst column7 if there is more than one from standard input while writing its square to standard output square c DAR 1103 Write the square of a column of numbers usage square lt input gt output A line with no number yields a blank line of output include ltstdlibhgt include ltstdio hgt int mainvoid char buf1024 room for one line if exceeded truncate double X store what s read whilefgetsbufsizeofbufstdin loop until no more input ifsscanfbuf HquotAlfquot ampX1 did we get something printf fn XX yes print the square else printf n blank line return 0 This introduces many different ideas First char buf 1024 declares buf to be an array of 1024 characters This is where we re going to put each successive line of input The parentheses around the arguments to while and if are mandatory in C they were optional in Matlab The fgets3 function the 3 says it s in Section 3 of the manual takes three arguments The rst tells where to put the characters7 the second how many there are and the third from where to get them stdin was declared in ltstdiohgt The function returns nonzero true while there s still input to get and it returns 0 false once standard input has reached the end The sscanf3 library function mirrors for input what printf3 does for 3 output7 but there are some differences The rst argument tells it where to look for input in this case7 the buffer7 buf The second argument is a format string7 in which quot41f tells it to expect a double Do not use quot4f herel The third argument tells it where to put the double The ampersand in front of X results in a pointer to the variable X it tells where in memory X is located One can read ampersand as address of or pointer to If one left off the ampersand one would pass to sscanf 3 the value of X instead of its address and the program would die horribly On errors in Unix you may have thought that Matlab error messages were dif cult to decipher but at least they were informative They told you where the error occured and roughly what it was Unix in contrast7 has only three error messages Individual programs of course7 may choose to be more helpful The rst error message is Segmentation fault on some systems7 segmentation violat ion It means you made a mistake The second error7 bus error also means you made a mistake The ordinary user hopes never to see the third error7 but in the exceedingly unlikely event this misfortune should ever befall you7 it is panic It means that the person who wrote the operating system Linus Torvalds in our case made a mistake7 and the computer just before crashing had the presence of mind or silicon to admit it I haven t seen this error in many years on a commercial Unix On Linux7 I ve seen it mostly when there s some awful bug in the hardware and it s now called Oops In the example above7 the code block for the while is enclosed in open and close braces7 although in this case it didn t need to be If there had been another statement after the second printf at the same indentation as if and else7 the braces would have been necessary to tell the compiler what s inside and what s outside the while Similarly7 I could have put braces around each of the two blocks of the if statement but they weren t required because each block contained only a single statement Once you ve compiled square7 you would like to run it on some input If you just type square assuming that s what you called the output of cc 17 it will sit there waiting for you to type something Go ahead When you re nished supplying all the input lines you can type CTRLD that s controlD A more useful way of running the program is to use an editor to make an input le say input Then physics cas usf edu quotA square lt input will use your input and type the output to the screen If you say physicscasusfedu quotA square lt input gt output the output will go into the le output7 which you may view with an editor or with cat 1 or more1 See my 26page manua 4 A traveler s MatlabC dictionary This table should get one started Matlab meaning C end of statement end of line line continuation not needed comment quotA begin block if7 for7 etc end block end 1 holds an integer int i X holds a real number double X not needed assignment increment i ii1 ii1 or i1 or i or i if block if test if test statement statement else else statement statement end for loop foristart iltend istep for istartzstep end statement statement end general for loop foronce test endeachiteration statement While loop whiletest while test statement statement end do loop do statement while test A statement may be replaced by a program block statement statement equality test inequality test Boolean false 0 0 Boolean true nonzero non zero Boolean and With shortcut ampamp ampamp Boolean or With shortcut I I function called f of one inte int function if j ger argument called j return f int j ing one integer ivtzlue return value 5 Beyond the rst week I ve left off almost all mention of strings argument parsing dynamic memory allocation vectors ma trices structures linked lists and other derived data types since to use these correctly requires a thorough understanding of pointers Bit operations scope and static variables and functions are similarly more advanced topics as are debuggers optimizers pro lers make les preprocessors and sourcecodecontrol systems However all of these things become easy once one has some experience programming


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

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

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!"

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.