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

Electrical Engr Computations

by: Jessica Nienow II

Electrical Engr Computations ECE 206

Jessica Nienow II
GPA 3.6


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

Class Notes
25 ?




Popular in Course

Popular in Electronics and Computer Technology

This 145 page Class Notes was uploaded by Jessica Nienow II on Monday October 26, 2015. The Class Notes belongs to ECE 206 at University of Tennessee - Knoxville taught by Staff in Fall. Since its upload, it has received 26 views. For similar materials see /class/229855/ece-206-university-of-tennessee-knoxville in Electronics and Computer Technology at University of Tennessee - Knoxville.

Popular in Electronics and Computer Technology


Reviews for Electrical Engr Computations


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: 10/26/15
ECE206 Programming Lecture 3 Operators and Data Type 083007 Recap El Programming environment Preroomplied lib 000110101 011111000 001010101 intmain 0 10010100 000 110 101 0 11 111000 001010 101 0 10100101 Primary memory 001001010 Arithmetic operators El modulus El Increment and Decrement I prefix form x and x I postfix form x and x El Precedence of arithmetic operators I highest I middle I lowest Examples for operators x 10 x 10 y Hx y x cout ltlt y What s y cout ltlt y What s y cout ltlt x What s x cout ltlt x What s x y Hy y ytt cout ltlt y What s y cout ltlt y What s y y ytt coutltlty What s y coutltlty What 5 y El When using the prefix form C performs the increment or decrement prior to obtaining the operand s value El When using the postfix form Cf will obtain the decrementing it 4 Examples for operators El El El can be applied to any data type the modulus operation yields the remainder of an integer division so it can NOT be used on type float or double When is applied to an integer or a character any remainder will be truncated include ltiostreamgt using namespace std int main int x y 0 x 1 y 3 cout ltltx y cout ltlt n cout ltlt x y I tum 39 Relational operators El Compare values mostly used in control structures I gt greater than I gt greater than or equal to I lt less than I lt less than or equal to I equal to I I not equal to Logical operators El Deal with multiple conditions also common used in control structures I ampamp AND I H OR I NOT El Short circuit evaluation I exprl ampamp expr2 ampamp expr3 I exprl expr2 expr3 I How to improve performance Assignments III a expr I the value of expr is computed and saved in variable a Eaabltgtab I the values of b and a are summed and the result is stored in a I Similar for a b a b a b a b Conditional operator El I One of C most fascinating operator I Require three parameters I Condition is evaluated If true return exp1 If false return epo I Can be used to replace ifelse statement cout ltlt guess magic Right Sorry you39re wrongquot Variable declaration El Specify name and type int a float b10 I I ng and informative names RACTER NAMES for variables other than iterators It s case sensitive for C program Variable type int short long float double char boolean pointers Use reasonably lo USE SINGLE CHA I it takes El Describe the variable s purpose in a comment El Variables need to be declared before the first use Reserve space in memory and optionally initialize DO NOT The size of a variable is measured by how many bits Basic data types Type Typical Bit Width Typical Range char 8 128 to 127 int 32bit 32 2 147483648 to 2147483647 oat 32 34E38 to 34 E38 double 64 17E308 to 17E308 bool 1 true or false void N A valueless Roundoff errors El Finite memory space to represent infinite digits of real numbers El Apply equality operator to floatdouble data is dangerous double x 335e17 double y if ygtx XZO cout ltlt y is greaterthan xquot What39s the output double x y i39fquot39x v coutltlt x equals to yquot double X itquotl fa bs cout li Xy lt 1e10 ltlt x equals to yquot 12 Mixed Type Expression El Data of different types in a single expression are converted to the same type El Explicit type conversion cast charch int m9n5 float x y inti oat f x floatmn 39 Y mn double d cout ltlt x ltlt endl cout ltlt y ltlt endl resultchifd fi Constants El Constants refers to fixed values that cannot be altered by the program El Example constants I define intCons 50 I define charCons c I define USAGE Usage Hellon El Another way I const int intCons50 I const char charCons c El Backslash character constants I n new line t tab ECE206 Programming Midterm Review 10407 Computer Architecture and programming environment III EIEIEIEI III What is a computer What are the basic components of a von Neumann machine What does a compiler do What does a linker do What does a loader do What is the difference between machine language and high level language In the header file you wrote why do you need to add ifndef XXX at the beginning of the file Operator and data type El El El EIEIEIEIEIEI What is the size of the following data types I int char boolean float double What is the difference between and What is the difference between xquot and xquot What does x aquot do What are the results of 9020 and 92quot Knowing the precedence of different operators Knowing how to use the 00quot operator and the operator Understand the difference between logical operators and relational operators Knowing two ways to declare a constant Control strutu res III Knowing how to use different selection and repetition structures I if else switch case for while do while El Knowing how continue and break work El How to write infinite loops using different control structures III Knowing how to convert from for loop to while loop FuncUons EIIIIEIEIEIEI El Why do we use functions What is function prototype Why do we use it Is there any difference between function prototype and function header Knowing how to receive command line arguments in the main function Why do we need to separate function definition and prototype into two files How to do that What s the difference between cabyvaue and callbk reference Under what situations we need to use ca y reference From the function call can you tell if it is cabyvaue or call byreference Knowing how to use callbyvalue cabyreference by reference and callbyreference by pornter to pass parameters to functions ECE206 Programming Lecture 14 Project 3 amp Lab 98 112007 Project 3 El How many data members we need El How many member functions we need Header File Public constructor Turtle create map void CreateMapintint create map size specified by row amp column amen void MoveUpint steps as input void MoveDownint void MoveRightint void MoveLeft int void getCurrentPositionO s void PenUp void PrintMap print map to screen void SaveMap save map to disk file Header File Cont d private int rowcol array size int xy position x is column index y is row index 39n pen Oup 1down int pMap map array Implementation void TuttleCIeateMapint Lint c don39t intget tn set anayshe to datamember cnlc pMap new int I fni0ilti pMapinew int c initialize map fni0ilti fntj0jltcj PMaPIii1 ifpMapNULL coutltltquotmap successquotltltendl Implementation Cont d void TurtleMoveUpint step ifysteplt0 StePY ifpen1 pen is down forint i0iltstepi pMapyix1 used as array name Yvstep move turtle Implementation Cont d void TurtleMoveDownint step ifystepgtrow row used for decision steprowy ifpen1 pen is down forint i0iltstepi PMaPvix1 yystep move turtle Lab 9 On Inheritance class SavingAccount public Account public SavingAccount SavingAccountdouble initial void CalcuIateInterestdoubledouble time period and rate double getInterest private double interest I Lab9 Constructor Function for Derived Class SavingAccount SavingAccount interest0 SavingAccountSavingAccountdouble initialAccountinitial interest0 SavingAccount bais 0r SavingAccount bais 100 Lab9 Examples of Implementation void SavingAccountCalculateInterestdouble timedouble rate interestAccountgetBalance timerate Comments Derived class can not access the private member WRONG of its parent class interestbalancetimerate Lab9 Examples of Implementation Cont d void CheckingAccountcreditdouhle cre Anuum quot 39 Auum quot 39 cre fee fee0 setBalanceAccountgetBalance fee Comments Class CheckingAccount can nut access balance But it can access fee N Account quot can be omitted Lab9 Makefile 08 39fractiono AR a INCLUDE Iincude libeceZOGa 031 vuOBJ r a n ib d fractiiono fractionopp g c fra e ti onrpp INCLUDE Comments 1 Using variable Macro 2 Automatic variable 6 3 Building library comman 3 ar with parameters rvu b ranlib 0 Lab9 Makefile COnt d Lab8 c BefOre oVerload and operatdr we need to 39makecleair what s their meaning Example int a 1 int ha fl 7 int c1 int dc 39I d Lab 8 Overloading prefix friend Fraction operatorFraction 81 prototype Fraction operatorFraction ampa implementation anumeratoranumeratoradenominator a increase areduce return a result in the expression value increase Fraction cl2 Fraction bc Fraction boperator c i b c Lab 8 Overloading postfix friend Fraction operatorFraction amp int prototype Fraction operatorFraction ampaint implementation Fraction tempa anumeratoranumeratoradenominator a increase return temp expression value doan t change Fraction c l 2 Fraction bc Fraction b operator c int bc Lab 8 Overloading prefix Fraction operator prototype Fraction Fractionoperator Implementation numeratornumerator denominator ObJECt decreases return this expreSSIon value decreases Fraction cl2 Fraction b c Fraction b c operator 0 bc Lab 8 Overloading postfix Fraction operator int prototype Fraction Fractionoperator int implementation Fraction tempthis numeratornumerator denominator object decreases return temp expressmn value doesn t change Fraction c l 2 Fraction b c Fraction b c operator int bc Embodied Thought Recent Robotics some highlights 200839013908 cs 102 ECE 206 with Robots r 1948 Grey Walter s Tortoises Simple neural net 7 inspired brain Showed simple brains can lead to complex life like intelligent behavior J Could find their way to recharging station 391 Simple Pavlovian learning 4 Similarities to Braitenberg vehicles LCR ch 6 and Scribblers 200801 08 Ancestors of the Scribbler Grey Walter s tortoises b Seymour Papert s turtles turtle graphics the Scribbler 200801 08 Importance of Embodied Intelligence 9 Traditional dualist view mind is essentially independent of the body 7 i in principle could have an intent b 0 Now we understand that much of our knowledge is implicit in the fact that we have a body 0 Also our body teaches us about the world 0 Structure of body is foundation for structure of knowledge 0 Knowledge is in the environment rather than a representation of the environment 20080108 4 Structure of Embodied Intelligence o Representational primitives are skills not concepts 0 Higherlevel skills are built on lowerlevel o Lowestlevel skills are grounded in the body 200801 08 Embodied amp Situated Artificial Intelligence 0 Therefore a genuine AI must be I embedded in a body embodied a capable of interacting significantly with its world N situated 0 Intelligence develops as consequence of interaction of body with environment including other agents 0 How can we investigate embodied situated intelligence 200801 08 1990s Ant Microrobots Rodney Brooks MIT 20080108 0 About1 cubic inch 0 17 sensors 9 Can communicate with each other 0 Goal push limits of microrobotics 0 Goal explore social interactions inspired by ant colony 9 Applications explosives disposal Mars exploration r 1990s Clustering Around Food 0 Food amongst other objects In enVIronment H Clustering 0 First ant to encounter Around food Signals others Egg 0 Others cluster at food 39 source 200801 08 8 V 19905 Tag Game 0 It robot wanders until bumps something o Transmits Tag a A Not Itquot robot replies I got taggedquot o First becomes Not Itquot o Second becomes It Tag The ExtendedrRemm Version fr 200801 08 9 19905 Genghis Brooks MIT o Subsumption architecture Inspired by evolution more complex behaviors build on simpler ones 0 Individual legs do their jobs 0 Legs are coordinated to achieve stability 0 Leg motion coordinated to achieve locomotion to goal 200801 08 19905 Genghis Brooks MIT Front view amp infrared sensing of person 200801 08 1998 Cog Brooks MIT oi Humanoid intelligence requires humanoid 3 interactions with the 39 world 0 Form of body is fundamental to cognitive representation a no brains in vatsquot o Humanlike intelligence requires humanlike body 20080108 12 2001 Leonardo 0 Cynthia Breazeal s Lab MIT o Sociable Robots Project 0 Vehicle for exploring socially guided learnin amp cooperative activity 20080108 13 r 2001 TouchSensitive Skin o Touchsensitive silicone skin over entire body 0 Mapped to neural net ike homunculus 9 Here Leo is programmed to notice amp withdraw from contact 20080108 14 2004 7 Socially Guided Learning a Leo is taught to turn on all the lights 0 Leo generalizes to I mcpmc 3059155 new Situation cm I mam vr um Ul 0 Leo displays Rnhmclric 3in MIT h39esna Usomoquot commitment to joint activity in spite of incorrect action 200801 08 2004 7 Collaborative tasks 0 Leo and human collaborate on a task makin sailboat and smiley ace from colored blocks 0 Have a common goal toward which the are working o Use gestures and social cues to cooperate 200801 08 F sum w m T Consciousness and selfawareness 200801 08 gt The Algorithm Slides with modi cations from Institute for Personal Robots in Education IPRE 11309 CS 102 ECE 206 with Robots r The Algorithm Algorithm n A nite set of unambiguous instructions performed In a prescribed sequence to aChleve a goal The American Heritage Science Dictionary 11309 The Algorithm AlKhwarizmi was a Persian mathematician who wrote a book on calculating with Hindu numerals in the 9th century CE When translated to Latin a pluralized form of his name algorismus became synonymous with a system of calculation 11309 0 01191 139 Pizza Dough Recipe Algorithml 1 Gather Ingredients 2 Combine sugar 1tbs salt 1tbs olive oil 1tbs flour 1c in mixing bowl 3 Turn on mixer 4 Add 14 cup of flour 5 If dough comes off the sides go to step 6 othenNise go back to step 4 6 Knead 15 minutes 7 Let rest for at least 45 minutes in warm area 1 dough ball 11309 21 NPizza Dough Algorithm Gather Ingredients Combine sugar N tbs salt N tbs olive oil N tbs flour N c in mixing bowl Turn on mixer Add N4 cup of flour If dough comes off the sides go to step 6 othenvise go back to step 4 Knead 15 minutes Let rest for at least 45 minutes in warm area N dough balls 11309 22 r NPizza Dough Algorithm Gather Ingredients Q Combine sugar N tbs salt N tbs olive oil N tbs flour N c in mixing bowl 0 Turn on mixer 0 Add N4 cup of flour 0 If dough comes off the sides go to step 6 otherwise go back to step 4 O Knead 15 minutes 0 Let rest for at least 45 minutes in warm area 11309 Sequence of m gt N dough balls r NPizza Dough Algorithm 0 Gather Ingredients Combine sugar N 39tbS salt NV tbs eliv ekzou cN tbs flour N Va 39able in mixing bowl 0 Turn on mixer 0 Add N4 cup of flour 0 If dough comes off the sides go to step 6 otherwise go back to step 4 O Knead 15 minutes N dough balls 0 Let rest for at least 45 minutes in warm area 11309 24 r NPizza Dough Algorithm 0 Gather Ingredients 9 Combine sugar N tbs salt N tbs olive oil N tbs flour N c in mixing bowl 9 Turn on mixer Add N4 cup of flour If dough comes off the sides go to step 6 otherwise go back to step 4 O Knead 15 minutes 0 Let rest for at least 45 minutes in warm area Conditional 11309 25 r NPizza Dough Algorithm 0 Gather Ingredients 9 Combine sugar N tbs salt N tbs olive oil N tbs flour N c in mixin bowl 0 Add N4 cup of flour 9 If dough comes off the sides go to step 6 otherwise 0 back to ste 4 9 Let rest for at least 45 minutes in warm area 11309 26 Programs Algorithms at Work 0 Programs are the way we communicate with a computer 0 Specify the algorithm 0 This class uses the C programming language 0 Rather than pizza dough we will use a robot as our favorite example mi 5 11309 27 The Way of the Program 11309 CS 102 ECE 206 with Robots Programming languages 0 There are thousands of programming languages 0 Highlevel languages a These are some languages l have programmed in A Ada Algol 60 Algol 68 APL Argot BASIC BCPL Bliss Chrysalis COBOL C FORTRAN FP GPL LISP Mathematica NetLogo Pascal I PLM Prolog Python Scheme Simula 67 Smalltalk StarLogo Q 9 These are some wellknown and popular languages that l have not programmed in C C Forth Haskel Java MatLab Miranda Pearl PLl o The point In your career you Will have to learn and use many HLle 0 The key skill is how to program a You should also be able to pick up new HLLs quickly 0 There are also lowlevel languages 11309 29 Interpreters r source O O CO 39 gtlt Interpretergt Q quot J F k 2 The interpreter and the result reads the appears on source code the screen 11309 30 Compiler source object r code Qpig code JQKUT CD K J The compiler and gengmes You execute the and the result reads the objec coda program one way appears on source code or another the Queen 11309 What is a program o A program is a sequence of instructions for performing a computation 0 That is a precise description of an algorithm 0 Instructions include a input 9 output a math a testing I repetition Programs need to be comprehensible to people as well as computers 11309 Debugging Compiletime errors Runtime errors 0 Logic errors Experimental debugging hypothesis testing 11309 Formal vs natural languages 0 Natural languages 9 ambiguity a redundancy m literalness 0 Formal languages 0 Programming Ian uages are formal languages for expressing a gont ms 11309 ECE206 Programming Lecture 6 Function 091107 Modules in C El Functions and classes I C standard library Prepackaged I User defined El Divide and conquer I Construct programs from small simple pieces Why function El More manageable program simplify the problem by decomposing it into small pieces Software reusability using existing functions as building blocks to create new programs El Avoid repeating code Information hiding all variables declared in function definitions are local variables I I Problem decomposition using functions The boss doesn t care how each individual does hisher job but requires an agreed upon interface workerIO W0rker2 W0rker3 W0rker2 can have people working for her Function format El Function prototype I return type function name parameter types ii El Function definition Hi return type function name parameter list declarations and statements function body El Prototype and definition must be consistent Function definition return value type function namedata type paral data type paran declaration s and statemen ts int square1nt x return xx Void printlnt int x i cout ltlt x int maxlmum1nt x int y int 2 int max x if y gt max max y if z gt max max 2 return max void function Function prototype El Function prototype must agree with function definition return value type function nameuiata type data type square1nt 3 int maleum1nt int int lt int square1nt X int maleum1nt X int y int 2 l l return XX int maX X Void printlnt1nt max y if z gt maX maX z Void printlnt int X cout ltlt X L LLlLIJ llld 7 Function declaration El Just like variable declaration before you can use a function you need to declare it There are two ways that you can declare a function I A function prototype or I The function definition Why do we need prototype Ij 39 Function Call El Functions can return values I Returned value MUST match the type specified in the prototype El Function augments I Variables constants expressions I How to transfer data int max maximuma b c augments Calling function Function name a Yuoc39do c k 7 Called function CallbyValue amp CallbyReference El There are two ways that a computer language can pass an argument to a function El callbyvalue A copy of the argument s value is made and passed to the called function Therefore changes to the copy do NOT affect the original variable s value in the caller El callbyreference The caller gives the called function the ability to directly access the caller s data It can be achieved in two ways I reference I pointer References El An alias must be initialized El Returned values can be references but be careful returned is undefined References must include ltiostream using namespace std be initialized gt int mainO int X 3 ampy x y is now an alias for X cout ltlt quotx quot ltlt x ltlt endl ltlt quoty quot ltlt y ltlt endl cout ltlt quotx quot ltlt x ltlt endl ltlt quoty quot ltlt y ltlt endl return 0 A reference to an auto variable that is Pros and cons El callbyreference is good for performance reasons because it eliminates the overhead of copying large amounts of data El callbyreference can weaken security because the called function can corrupt the caller s data Ca IlbyReference LI To indicate thTatTa functi0n parameter is passed by reference two39 steps need to be done I inquot the function pr ot ot pe fallow the parameter type by an St I in the function definition7 follow the same convention inE r39efere ndeExafhpnl39ekiint amp futhion p fototyp39e int main a Eeferehc eES a mple a Calltb yirefer enc e 71m quotquot ampgt lt function deflhitioh Good programming practice El Split your declaration of a function s prototype and definition of the function s implementation into two files El A header file ltnamegth containing the prototype with any necessary additional dependency information and El An implementation file ltnamegtcpp containing the C source code El Keep the implementation private and publicize only the prototype header file Example the main source file saved as testscpp lnclude lt1ostreamgt mclude testsh u51ng namespace std lnl main int a b c Cln gtgt a gtgt b cout ltlt Maximum 15 cout ltlt Enter three integers gtgt c cout ltlt maximuma b 3 ltlt endl cout ltlt m1nimuma b c ltlt endl return 0 the function fllei saved as maximumcpp include leslsh 1nl maximum1nt x ml y Lnl z 1nt max x if y gt max magtlt y 1f 2 gt max max 2 return max 1nl m1n1mum1nt x ml y Lnl z 1nl mln x 1f y lt min mln y 1f 2 lt min mln 2 re tu r n min Compile and link El Compile each cpp file individually I g c maximumcpp I g c testscpp El Link all object files I g 0 tests testso maximumo El Modifications in one cpp file DO NOT affect the compilation of other files Avoid duplicate function definitions Using commandline arguments El On many systems DOS UNIX in particular it is possible to pass arguments to the main function from a command line by including the following two parameters in the parameter list I int argc argc receives the number of commandline arguments I char argv an array of strings where the actual commandline arguments are stored Example Newton s method include ltiostreamgt using namespace std int mainint argc char argv l float xi epsilon if argc l 3 cout ltlt Usage newton initialiguess tolerancen else l xi atofargvl epsilon atofargv2 l return 0 Commonly used math library functions All require and return values of type double Other types may be casted into type double include ltcmathgt using namespace std double ceildouble x double log double x double floor double x double loglO double x double exp double x double Sin double x double pow double x double y double cos double x double fabs double x double tan double x double fmod double x double sqrt double x Header files El Standard header files are used to provide function prototypes for functions defined in the standard C library El There are two header styles I The older style uses an extension of I The new style has no extension not supported by all compilers El Access standard header files I include ltheadernamegt El Access userdefined header files I include myfunctionsh Oldstyle standard C headers Old names new names ltasserthgt ltcassertgt ltctypehgt ltcctypegt ltfloathgt ltcfloatgt ltlimitshgt ltclimitsgt ltmathhgt ltcmathgt ltstdiohgt ltcstdiogt ltstdlibhgt ltcstdlibgt ltstringhgt ltcstringgt lttimehgt ltctimegt ltiostreamhgt ltiostreamgt ltiomaniphgt ltiomanipgt ltfstreamhgt ltfstreamgt Newstyle standard C headers ltutilitygt ltVectorgtltlistgt ltdequegtltqueuegt ltstackgtltmapgt ltsetgtltbitsetgt ltfunctionalgt ltiteratorgt ltalgorithmgt ltexceptiongt ltstdexceptgt ltstringgt ltsstreamgt ltlocalegt ltlimitsgt lttypeinfogt Attributes of C identifiers El El El I Name type size value Storage class determines the period during which that an identifier exists in memory Scope where an identifier can be referenced Linkage determines whether it is known in the source file it is declared or across multiple files that are complied and linked together Storage classes El Automatic storage class exists when block is active and destroyed when program exits the block I auto default not visible outside that block I register a suggestion to the compiler to use a CPU register for performance Static storage class last for the duration of program I static known only in the function where it is define but is never destroyed I extern declared outside any class or function and its definition is determined during linking Mutable exclusively for class Default Variable Classes El Variables defined inside a function or procedure are by default auto El Variables defined outside all functions and procedures are by default extern and are global El Only variables can be in the auto storage class not function El Function names are by default extern C Scope Rules El There are five scopes I function scope file scope block scope functionprototype scope I I I I class scope discuss later File Scope El Identifiers declared outside any function have file scope El These identifiers are known from their point of declaration until the end of the file El Identifiers with file scope I global variables I function definitions I function prototypes placed outside all functions Function Scope El Labels which are identifiers followed by a colon El Labels contained in a function can be used anywhere in that function but are not visible outside that function El Labels are used in switch statements case labels and with goto statements Block Scope El Blocks are portions of C code contained within races El Identifiers declared within a block have block scope and are visible from their points of definition to the end of the innermost containing block El A duplicate identifier name in a block hides the value of an identifier with the same name defined outside that block El Auto variables with block scope are created upon their drefirg iltioln and destroyed when execution goes outside t e oc El Static variables within a block still have block scope but exist from the beginning of execution until the program exits FunctionPrototype Scope El Variables appearing in the parameter lists of function prototypes have function prototype scope El These variables are only placeholders no storage is allocated or reserved El They are not visible outside of the function prototype El Variable identifiers in function prototypes are optional only types are required Scope resolution operator El Local variables may hide variables in an outer block or global variables El The unary scope resolution operator allows access to the hidden variable El A binary scope resolution operator also is used with classes and will be discussed later Example include ltiostreamgt I using namespace std mid f0 void f f is global int X 44 void g0 go is global cout ltlt quotIn f X quot ltlt X ltlt endl IntX 11 this X Is global int main VDid go intx 22 coutltltquot1ngXquotltltXltltendl internal block n X cout ltlt quotIn block inside main X quot ltlt X ltlt endl cout ltlt quotIn main X quot ltlt X ltlt endl cout ltlt quotIn main X quot ltlt X ltlt endl f0 90 return 0 36 ECE206 Programming Lecture 13 Template and STL 111507 Turtle class El Design a class to fit the problem No need to define irrelevant properties of a turtle such as size color age The main task of a turtle is to move and draw then what are needed Move map with a certain size position direction I Draw pen El Member functions I Constructor and destructors assessors mutators I create print and write map I Turn left turn right move Template El Avoid redundancy I No need to write overloaded functions with the same codes and different data types El More general than overloading I Specify an entire range of functions and classes using a single code segment El Can be used to produce both functions and classes I Function template I Template classes A more general way to define FU nCtiOl39 templates functions with similar operations Class template without my Standard Template Library STL El Motivation reuse reuse reuse El STL includes many reusable components El Three fundamental items of STL I containers defines most often used classes data structures with a set of member functions I iterators are objects that are more or less pointers They give you a way to cycle through the contents of a container I algorithms acts on the contents of containers They include capabilities for initializing sorting searching etc 9 Vectors El The most generalpurpose container El Supports a dynamic array El An example Tr my a 17 W1 5 Clare an ite39rat 39r39 ECE206 Programming Lecture 5 Control Structure II 090607 Recap El Sequence structure El Selection structure I ififeseifese if laddernested ifs I Conditional expressions I Switchcasecontroling expression I Dangling else problem El Repetition structure Why repetition int numberl numberZ number3 float avg cout ltlt Please input 3 integer numbersn lt Calculate sum Cll gtgt numberl gtgt numberZ gtgt number3 avg numberlnubmer2number330 cout ltlt The average 15 ltlt avg ltlt endl What about 1000 numbers Key components in repetition El Where to start and when to stop I Countercontrolled I Sentinelcontrolled I Taskcontrolled El Controlling expression El What action to perform El How to jump out from repetition for loop for initialization xpression increment statement sequenCE Initialization 1 True Statement sequence increment Example 1 for Cout for 110 1gt710 1175 i for 10 1110 1 ltlt 1 ltlt cout ltlt 1 ltlt quot for 10 1lt5 1 for char lZ A 1lt F39 H1 cout ltlt 1 ltlt N t ltlt 1 ltlt l C Calculate the sum of all even int total 0 numbers less than 1000 gt for int even2 evenlt1000 eveneven2 total even Exploring for loop El The infinite loop for l r El Time delay loops for XO xltlOOO x for x0 xltlOOO x for y0 yltlOOO y How to stop infinite loop while loop initialization while i condition statements C gt while Find the smallest power of 2 greater than 1000 product int product l product 7 a lt 1000 2 product Example 2 while This program dlsplays all prlntable characters a Since ch is an unsigned character the values from o o 255 when it holds the value it can only hol incremented its value will quotwrap aroundquot to d 255 and is then ero lnclude ltiostreamgt using namespace std introduces namespace std int maln VOld l unsigned char ch 32 whlle ch cout ltlt charch ch l return 0 do while loop do l statements l while expression c Flnd the smallest power of 2 int prOdHCt 7 1quot greater than 1000 do product product lwhlle product lt 1000 Examples 3 while and dowhile x while x gt 0 l cout ltlt x l x 10 do i x77 cout ltlt x l while xgt0 El The difference lies in the order of execution in dowhie the statement is executed first then the condition in while the condition is executed first then the statement if condition is satisfied Example 4 the jump structure El continue to force an early iteration of a loop to bypass the loop s normal control structure El break to force an immediate exit from a loop int x for xO xltlOO x if x 2 continue COUt ltlt x ltlt int x for XO xltlOO x if COUt ltlt x ltlt Some notes El Convert for to while any exception for initialization expression increment l statement sequence i initialization while expression l statement sequence increment l El Incrementing ancl decrementing counters I for counter 0 counter lt 10 counter I l for counter Nil counter gt 0 counteree 1339 Selfstudy problems El Factorial computation 5 54321 El Fibonacci series F0 0 F1 1 Fi F1 F2 0 1 1 2 3 5 8 13 21 ECE206 Programming Lecture 2 Programming Environment and Elements of Computing Systems 082807 Programming paradigms III Structured programming I Emphasis on actions verbs l A complex program is modularized as a collection of subtasks functions that manipulate the data I Pascal C III Objectoriented programming OOP l Focuses on things or objects nouns l Object is a basic building block I Java C OOP concept member functions data members Object Advantages of OOP III Objects promote safety I Encapsulation information hiding III Objects facilitate code reuse l Very useful in developing large applications I Rapid Application Development RAID III Objects facilitate code maintenance and upgrades Basis structure of a C program This program conver rs gallons lo li rers This is our firs r C program Auihor Dale 100799 include ltiosireamgt using namespace sid in r main floa r gallons liiers cou r ltlt En rer number of gallons cin gtgt gallons li rers gallons 37854 conver rs lo li rers cou r ltlt Li rers ltlt li rers ltlt n reiurn O This inpu rs from The user gt Header comment multiline comment lgt header file is included in the system by include Here ltiostreamgt is used to support the C lO system The using statement informs the compiler that you want to use the std namespace This is the namespace in which the entire Standard C library is declared By using the std namespace you simplify access to the standard library lgt The only function that any C program must include is the main function Components of C program EIEIEIEIEIEIEIEI Comments I for single line or for multiple lines Complier directive I include Header file I ltiostreamgt inputoutput stream header Function block I int main Braces I begins the body of a function and ends the body Statement I liters gallons 37854 Statement terminator 39 Return Programming environment PreCornpiled Library Codes lO math func Editor Source Compiler Object Code Code Hellocpp Helloo Linker Output Debugger Executable Code Hello LinuxUNIX software development environment III GNU xemacsemacsvi visual editor to create and edit source and make files III GNU g compilerlinker to compile C or C source files into object format and link object files into an executable file III GNU gdb source level debugger and ddd X windows interface to debug your software Linux commands Editor Hellocpp g c Hellocpp Compiler Hello execution result g 0 Hello Helloo 4 gt Hello Good programming style III Spacing III Commenting Header comments III Naming l the Taligent name convention III Indenting III ANSI and ISO l American National Standards Institute I International Organization for Standardization 10 Commonly used indenting styles f0rlt00r1dgt for ltCondgt for ltcondgt for ltCondgt ltbOdygt ltbOdygt ltb0dygt ltbodygt The KampR st Ie y The Auman The Whitesmiths The GNU style style Style Check httpenwikipediaorcIwikiIndent style for more discussions 11 Good programming stxles example include ltiosTreamgt using namespace sTd inT main floaT abcdefg cingtgtogtgtbgtgtcgtgtdgtgte fabcde gf5 couTltltf reTurn O This code calculaTes The average score of each aThIeTe during The 5 round 3m spring board diving Input The five scores The average score AuThor Hairong Qi hgiuTkedu DaTe 08262004 include ltiosTreamgt using namespace sTd inT main floaT scorei score2 score3 score4 score5 sum avg inpuT The individual scores couT ltlt Please inpuT The five scores couT ltlt Use space To separaTe each score ltlt endl cin gtgt scorei gtgt score2 gtgt score3 gtgt score4 gtgt score5 calculaTe The average score sum scorei score2 score3 score4 score5 avg sum 5 couT ltlt The average score is ltlt ava ltlt endl 12 reTurn 0 About piping I laverage gtgt outputtxt 13 A road map of computing systems HighLevel Language Applications Operating System Compiler Assembler Machine Language Computer Architecture ALU I Memory Elements Boolean Arithmetic I Sequential Logic Boolean Logic 14 Application or system design HighLevel Compiler Language amp Software Operat39ng System hierarchy Assembly Language Assembler Computer Architecture Machine Language Hardware hierarchy I Gate Logic lHardware Platforml Chips and Logic Gates Electrical Engineering PhysiCs Boolean logic l Transistors H Logicgates H chips HDigital device Basic switching Implement device Boolean function Truth table lists all possible combinations of inputs and give proper outputs Primitive gates I Nand I Not And Or Xor Multiplexer Demultiplexer El Computer hardware is typically designed to operate on multI bit arrays called buses 16 Boolean arithmetic Binary numbers Binary addition Signed binary numbers I The 2 s complement method also called the radix complement Adders I Halfadder add two bits I Fulladder add three bits I Adder add two nbit numbers ALU cannot maintain state store and recall values Output C S l OH 0 0 0 1 0 1 1 0 17 ALU desig n zx nX zy ny f no X 16 bits fx y out 16 bits y 16 bits zx nx zy ny f no out If zx then If nx then If zy then If ny then If f then If no then fxy x0 xx y0 yy outxy else outout outxampy 1 O 1 O 1 O O 1 1 1 1 O X1 18 Sequential logic III A type of logic circuit whose output depends not only on the present input but also on the history of the input I Trhe memory elements are built from sequential c Ips l Implementation of memory elements III Synchronization III Clocking III Feedback loops l The lowlevel sequential gate Flipflops DFF III Registers III Memories 19 Machine language III A machine language can be viewed as an agreedupon formalism designed to manipulate a memory using a processor and a set of registers III The processor CPU is a device capable of performing a fixed set of elementary operations including arithmetic and logic operations memory access operations and control operations 20 Computer architecture CPU Input Memory ALU data Instructions CODiFOl Output 21 ECE206 Programming Lecture 12 Func oriAdvanced Features 111307 What do you need to know El Fundamentals El Advanced topics I Function declaration I EUIUCtign of oading I nine unCIons I Forward pr t tYpe I Functions with default I Forward definition augments I Callbyvalue vs call I Function templates byreference l Recursive functions I Command ne I Function pointer arguments I Storage class C storage classes revisit El Each C variable has several attributes I name type size value I storage dassscopehnkage El C has four storage classes I auto the default Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition They are not visible outside that block I register a type of auto variable a suggestion to the compiler to use a CPU register for performance I static a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function It exists from the time the program begins execution l extern a static variable whose definition and placement is determined when all object and library modules are combined linked to form the executable code file It can be visible outside the file where it is defined 3 Example register include ltc timegt register int i 3 int starttime endtime starttime clock 0 for i0 iltLARGENUM i endtime clock cout ltlt the duration is ltlt endtime starttime A few more things about register El A modern processor normally has at least 32 registers for integer variables and 32 registers for floating point variables Each register is 32 bit or 64 bit depending on different computer architectures An optimized compiler should allocate the most frequently accessed variables in the register with or without explicitly specifying register storage class There s only limited amount of registers What if all the registered are occupied I I El Example static variables x float 39ravg i statgm float sum sti e int count 90 sum i count return sum count Another example class definition class Complex public Complex Complex float float Complex void setcomple x loat L void pfin tComplexr float ge tRe alO39 const float gatImagO const void setR alEloat void se tImag floaty static int geutCounl 0 private I float real loat imag stati x i m count Inline functions El Short frequently used functions are good candidates for inline functions El An inline function s body is inserted directly in the compiled code at the point where the function would normally be called El The advantage is efficiency El Like the register keyword inline is only a suggestion to the compiler Efxa m p le Default arguments El Default arguments have a defined value if they are not preSent in the Calling parameter list El Default argument must be the rightmost parameters so they can be omitted El Default arguments must be specified only once first appearance of function name usually in function prototype Example inline function definition inline int volume int length int width 1 int height l No function call return length width height Multiple copies ofthe int main function implementation in the int v1 v2 v3 object code v1 volume 15 value is 5 Q V 1 5 1 v2 volume 4 value is 4 IE V 4 1 1 v3 Volume 222 value is 8 E12 V3 2 2 2 11 Function overloading El One of C s most exciting feature El C allows several functions with the same name to be defined as long as the types andor numbers of their arguments differ El The functions that share the same name are said to be overloaded El Function overloading is one way that C achieves polymorphism overloading abs include ltiostreamgt using namespace std Example absi is overloaded in two ways D Consider 2 functions int absint i double absdouble d located In the standard library abs fabs quott 3 El They are first defined by cout ltlt abs10 ltlt Mn the C language and for rltoabsquot11 W compatibility are also included in C El So for similar tasks 1m abs1nt 1 programmer has two if m return i names to remember not else return 1 just one El C can resolve this double absldouble 1 problem by function if d lto0 return d overloading else return d Function Templates El I I Function templates allow the definition of functions independent of the type of the arguments and return value This implements a philosophy of write once useanywhere by allowing parameterized types Templates form the basis for the C Standard Template Library STL of algorithms which we will discuss later A Function Template Example int maximum int valuel int value2 int value3 if value2 gt max max value2 if value3 gt max max value3 1m ma1n return max 1m a1b3c3 int m template ltc1ass T 1 maximum T va1ue1 T va1ue2 T value3 xm Ktha39 1quot C T max valuel return 0 if value2 gt max max value 2 if value3 gt max max 5 value3 return max A list39offomtql tjpeparameterspxecededby the class quotkeyw0rd is speci ed between the lt gt and is usedinplace af xing1 in the mction e ng39tion Recursion El Recursive functions calls itself directly or through another function El Any C function call call itself but functions that use static and extern variables must do so carefully El Recursion can be used to solve problems by induction I Do one step and call itself to solve the remaining problem I Detect and perform the last step base case Factorial a recursive example El The factorial of a positive integer n is the product of all integers between 1 and n inclusive El The factorial can also be defined in terms of itself I For ngtO n n n1 I For nO n 1 El This can be translated directly to a C implementation Recursive factorial in C int factorial int n i if n0 return 1 do the last step else if ngt0 return nfactorial n l do one step else return 1 indicator of error nlt0 l l Many problems can be solved using this same structure Take care of the last step and possible error conditions and then do one simple step Recursive process Factorial3 WW9 aw 1Factorlal0 Pros and cons of using recursive functions El If an algorithm can be expressed in a recursive form with a simple algorithm for each step the recursive implementation can be very easy to verify El Recursion incurs overhead in creation and destruction of automatic variables and in function calls El Recursion may hide gross inefficiencies eg the Fibonacci example watch for explosive numbers of recursive calls ECE206 Programming Lecture 10 Operator Overloading 103007 Recap EIEIEIEIEIEIEIEIEIEI Class definition object instantiation Separate interface from implementation Access specifier public private Constructors and destructors Memberwise copy and copy constructor Accessors and mutators Constant function The this pointer Dynamic allocation of objects The static data member and functions Complexh class Complex public Complex Complex float float Complexconst Complex amp testComplexcpp Complex void setComplexfloat float int main float getReal const float getImag const Complex numberl number2 Complex addComplex amp private number1setComplex21 32 float real number2setComplex30 20 float imag Complex number3 number3 number1addnumber2 Com lexc p pp prefer the following Complex ComplexaddComplex ampa number3 numberl number2 Complex temp tempreal real areal tempimag imag aimag return 0 return temp 3 Operator overloading III Operator overloading makes the operators have meaning appropriate to the new types III C does not allow new operators to be created but it does allow most existing operators to be overloaded III Use of C buildin operators to userdefined class objects Operator classification Operators Unary Binary lt Prefix Post X D amp9 ND D D D quot39 new delete Operators that cannot be overloaded sizeof Two ways of operator overloading III Using member function I the left operand must be an object of same class l O gt or assignment operators must be declared as member function III Using global function I the left operand can be an object of a different class or other type eg gtgt or ltlt I Use friend function if it needs to access private members directly III No matter which way is used the operator is used the same way in expression I object objectl object2 class Complex public Complex Complex void printComplex const float mag float phase void setComplexfloat float float getReal const float getImag const void setRealfloat void setImagfloat Complex operatorComplex amp private float real float imag Complex ComplexoperatorComplex Complex temp tempreal tempimag real areal imag aimag return temp Overloading binary operators int main Complex numberl number2 number2 number3 number3 numberl number2 number3 setComplex2 3 setReal 3 setImag2 numberloperatornumber2 numberl number2 return 0 Overloading unary operators preform class Complex public Complex Comp1ex void printComplex const float mag float phase lnt ma1n void setComplexfloat float Complex number3 float getReal const float getImag const void setRealfloat void setImagfloat Complex operatorComplex Complex ampoperator private float real float imag number3setComplex2 3 number3operator number3 return 0 Overloading unary operator postform class Complex public private Complex Complexoperatorint Complex temp this Complex NC mple real v01d pr1ntComplex const 1mag float mag float phase return temp v01d setComplexfloat float float getReal const int main float getImag const void setRealfloat void setImagfloat Complex operatorComplex Complex number3 number3 setComplex 2 3 Complex ampoperator 222l2 22eratorint number3operatorint number3 float real float imag return 039 The friend function Overloading steam IO operators class definition class Complex friend ostream amp operatorltltostream amp Complexlt public Complex Complexfloat float main Complex u void setComplexfloat float Complex numberl void printComplex float getRea1 ConSt number1setComplex10 20 float getImag const V id setRealfl at opratorltltcout numberl void setImagfloat cout ltlt numberl Complex operator u private float real float imag ostream amp operatorltltostream ampout Complex a out ltlt areal ltlt ltlt aimag ltlt i ltlt endl return out class definition class Complex friend ostream amp operatorltltostream amp Complex friend Complex operatorComplex Complex ciomplexo Overloading by Complexfloat float women frlend function void setComplexfloat float void printComplex float getReal const float getImag const void setRealfloat void setImagfloat Complex operator private float real float imag public ECE206 Programming Lecture 7 Array II 092507 Array Fundamentals El Declaration specify type name size constant integer I double myArraylO El Accessing array elements I myArrayO myArrayl El Multidimensional array I int myArray2 3 El Char arrays and string I char myCharH Hello world Void modifyA rray int b int leeOfArray for int j D j lt sizeofArray j bj 2 Return arrays from functions El Array can NOT be returned from a function El Array cannot be assigned int a5r 1 2 3 int b5 brr 5 Wrong Sorting an array El Insertion sort III Selection sort El Merge sort El Bubble sort El Bubble sort El Bubble sort uses repeated comparison to exchange adjacent elements in the array if they are not in order El In this process small values move toward one end and large ones toward the other end that s why it s also called sinking sort El Simplest but El the most inefficient Bubble sort pseudocode El Search for adjacent pairs that are out of order El Switch the outoforder keys El Repeat this n1 times El After the first iteration the last key is guaranteed to be the largest II If no switches are done in an iteration we can stop Example First pass Second pass 1o 12 8 68 45 1o s 12 45 68 10 12 s 68 45 8 1o 12 45 68 10 8 112 68 45 8 10 112 45 68 10 8 1i 68 45 8 10 1i 45 68 10 8 1i 45 68 8 10 1i 45 68 ECE206 Programming Lecture 7 Array 092007 What is an array El An array is a collection of data elements or objects of the same type El Arrays are static entities because they remain the same size throughout program execution El When declaring an array a consecutive group of memory is allocated Array declaration type array namearray size Vector0 50 El Example To declare a one vectorm 1L0 dimensional array with 10 double vectorm 75 0 variables the following statement 39 is used Vector3 00 39 t 4 323 double vector10 I39gt vec OH vector 5 525 where a contiguous space for 10 double variables is allocated in the VeCtOrm 5396 memory by compiler vectorm 1000 El Arraysize must be an integer VectorlSJ 01 constant vector9 350 Array name El Name of an array indicates the address of the memory which the array is stored it is a constant pointer Printing the memory location of an array include ltiostreamgt using namespace std int main l int aH cout ltlt quota ill 22 33 ltlt a ltlt endl return 0 Array subscripts El El Individual elements of an array are referenced by a subscript vector 0 50 vector 1 2vector0 1 0 An array element can be used anywhere a scalar variable of the same type can be used Array subscripts can be non negative integers or expressions that evaluate to a non negative integer value vector a 1 vector alo 90 For an array with N elements array subscripts can range from 0 through N 1 not from 1 through N Array initialization El El El Arrays can be initialized by a list of constant values double vector3 00 10 20 Empty list double vector 3 The number of elements in an array can be inferred by the compiler from the number of Inltlallzmg constants int vector 0 l 2 3 4 l a Selement array Initialization with tailing zeros float vector5 02 23 40 Using for loop int vector 10 forint i 0 i lt 10 i vectori i2 Multidimensional arrays El More than one subscript can be used to reference an array element A 3x2 matrix with 3 rows and 2 columns can be declared as l double matrix 3 2 gt matrixu 0 l l El Space is allocated matrix contiguously with the rightmost subscript incrementing the fastest WNNl l O oooooo 2D array initialization El Array initialization is like double matrix3 2 i001010202030 El Without enough initializer 1 0 int a23 H1i345 3 4 int b23 l2345 1 2 int c23 H12ii3iiv 4 5 l 2 3 0 Example uninitialized array lStatic arrays are initialized when the program is loaded and are Inltlallzed to zero by default Auto arrays are not initializing an array with a declaration include ltiostreamgt using namespace std int main l int a 7 int b 7 l an uninitialized array static int c7 l376l for int i 0 7 i cout ltlt ai ltlt quot quot ltlt bi ltlt quot quot ltlt ci ltlt endl L Lulu v Example array operation 1D Compute the average of the array include ltiostreamgt using namespace std int main in t a 13 5 16 45 66 23 double total 0 aver size sizeofa sizeofint for int i 0 i lt size i total ai average totalsize cout ltlt quotThe average is quot ltlt average ltlt endl return 0 Example array operation 2D Compute the average of the array include ltiostreamgt using namespace std int main i int a3 7 double total iil3 5 16 45 66 t 0 average 23 for int row 0 row lt 2 row for int column t 0 column lt 3 column total arowcolumn average totalrowtcolumn cout ltlt quotThe average is quot ltlt average ltlt endl return 0 Nobound checking El Nothing in C stops a program from trying to refer to elements outside of an array include ltiostreamgt using namespace std int main i double a4 111 222 333 444 for int i0 ilt7 i cout ltlt quottaquot ltlt i ltlt quot quot ltlt a i ltlt endl a4 555 n i Char arrays and strings El Char arrays can hold strings El A string is stored as an array of characters terminated with a NULL character value of zero El There are two ways to initialize char arrays with strings the NULL character is automatically inserted char strl Helloln an Scelement array expllc1t NULL seelement array char str2 l H e 139 139 0 i39 n O39 El Pay attention that string uses double quote while character uses single quote quot Char array input and output El cin gtgt can be used to input a char array from keyboard stop at space El cout ltlt can be used to output a char array to screen El What about other data type Passing arrays to functions El Arrays can be passed as arguments to functions El C automatically passes arrays to functions using simulated callby reference EI How to prevent called functions from changing array values Parameter passing El Call by value I For small objects that should not be altered by the function El Call by reference I For large objects that may be altered by the function and the copy would be too expensive El Call by constant reference I For large objects that should not be altered by the function inl b inl sizeofArray 3 lt slzeOfArray j Return arrays from functions El Array can NOT be returned from a function El Instead array storage must either be passed to the procedure or must be dynamically allocated in the procedure Array cannot be assigned int a 5 1 2 3 intb 5 ba Sort an array Bubble sort El Bubble sort uses repeated comparison to exchange adjacent elements in the array if they are not in order El In this process small values move toward one end and large ones toward the other end that s why it s also called sinking sort El Simplest but El the most inefficient Bubble sort thinking Bubble Sort Thinking excerpt There is a famous computer Sort algo thm Called the bubble sort It is the most natural most o en tried sort in the history of computing ltisabsolutely obvious Andit is absolutely abysmal because it is the slowest sort known to science It isn39t known why the bubble sort is so obvious to therhuman mentality But every other sort known to computer science is faster You name it the insertion sort shell sort quicksort heapsort are all better and faster Press Teukolsky etal in their book Numerical Recipes say quotWe will draw the line at the inef ci entN squared algorithm beloved of elementary computer sciencertexts called bubble 39sort If you know what therbubble sort is wipe itfrom your mind39 if you don39t know make a point of never nding out http wwwmacopinion comcolumnsutopia ar chiveupilll btml 21 Bubble sort pseudocode El Search for adjacent pairs that are out of order El Switch the outoforder keys El Repeat this n1 times El After the first iteration the last key is guaranteed to be the largest El If no switches are done in an iteration we can stop What do you need to know Ei HOW to declare and initialize an array Eli Multidim ension a l array El How to pass an array to a function El Char array and string Ij How to sort an array


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

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

Amaris Trozzo George Washington University

"I made $350 in just two days after posting my first study guide."

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


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

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.