Docstoc

Introduction to Physics Computing

Document Sample
Introduction to Physics Computing Powered By Docstoc
					Introduction to
Physics Computing

   MT 2009
   Lecture 2
   J Tseng
Outline

n    Control flow
     q   Conditional
     q   Loops
     q   Statements and blocks
     q   Functions
n    Data structures
     q   Arrays
     q   Strings
     q   Structures


MT 2009 (2)           Introduction to Physics Computing (Tseng)   2
Control flow

                      n     A C program defines a sequence of
              BEGIN         actions (statements), separated by ;
                      n     The beginning is defined by main()
             Do       n     The end is specified by return
          something         statement

             Do                      #include <stdio.h>
          something
             else                    int main() {

                                          printf(“Hello world.\n”);
              END                         return 0;
                                     }


MT 2009 (2)               Introduction to Physics Computing (Tseng)   3
Conditional
                                                     n    “intelligence” (or at least
                                                          decision-making) is coded
              BEGIN                                       with conditionals (branches)
                                                     n    In C, basic conditional is
             Do                                           if…else
          something
                                                               int shampoo() {
                      YES                                        lather();
          Do more?
                                                                 rinse();
                             Do more                             if (isRequired()) {
                 NO
                            something                              lather();
                                                                   rinse();
                                                                 }
              END             END
                                                                 return 0;
                                                               }


MT 2009 (2)                   Introduction to Physics Computing (Tseng)                4
Conditional (2)
n    Basic forms:
                                                           #include <stdio.h>
     q   if (expression)
         statement1                                        int main() {
     q   if (expression)                                     int nDone;
         statement1 else                                     int nMore;
         statement2                                          int nLimit = 6;

     q   if (expression1)                                      printf(“How   many done? “);
         statement1 else if                                    scanf(“%d”,   &nDone);
         (expression2)                                         printf(“How   many wanted? “);
         statement2 else…                                      scanf(“%d”,   &nMore);

n    Value of expression                                       if (nDone + nMore > nLimit) {
     determines which statement is                               printf(“Will do too much.\n”);
     executed                                                  } else {
                                                                 printf(“Okay.\n”);
     q   Non-zero (“true”) for                                 }
         statement1                                            return 0;
     q   0 (“false”) for statement2                        }


MT 2009 (2)                 Introduction to Physics Computing (Tseng)                       5
Switch
n    If you have a number of possible actions given a
     value, you can use a switch statement
                                                                    switch (var) {
                                                                    case val1:
              if (var == val1) {                                      statement1;
                statement1;                                           break;
              } else if (var == val2) {                             case val2:
                statement2;                                           statement2;
              } else if (var == val3 ||                               break;
                         var == val4) {                             case val3:
                statement34;                                        case val4:
              } else {                                                statement34;
                default_statement;                                    break;
              }                                                     default:
                                                                      default_statement;
                                                                    }

MT 2009 (2)             Introduction to Physics Computing (Tseng)                     6
 Loops                                                                BEGIN


 n    Computers excel at repeating
      the same operation over and                                        Do
      over                                                            something

      q   “Loop”                                                                  YES
      q   Usually terminated by a condition                           Do more?

 n    C loops mimic human structures                                       NO
      q   Mostly differ in how/when                                     END
          termination condition is evaluated

while (expr) {       do {                           for (init; expr; update) {
  statement1;          statement1;                    statement1;
  statement2;          statement2;                    statement2;
}                    } while (expr);                }

 MT 2009 (2)              Introduction to Physics Computing (Tseng)                     7
Counting
n    All the following count from 0 to 9:
    int j = 0;                       int j = 0;
    while (j < 10) {                 do {
      printf(“%d\n”, j);               printf(“%d\n”, j);
      ++j;                             ++j;
    }                                } while (j < 10);

    int j;                                       int j = -1;
    for (j = 0; j < 10; ++j) {                   while (++j < 10) {
      printf(“%d\n”, j);                           printf(“%d\n”, j);
    }                                            }

    int j;
    for (j = 0; j < 10; ++j) printf(“%d\n”, j);


MT 2009 (2)           Introduction to Physics Computing (Tseng)         8
  Loop control

  n    continue skips the                             n    break exits the loop
       rest of the loop                                    entirely
       statements and                                      q    Also saw use in leaving a
       reevaluates the                                          switch
       expression
                                  int j;
                                    int =
                                  for (j j; 0; j < 10; ++j) {
                                    for (j    0; j < 8; j
                                    if (j % =2) continue; += 2) {
                                    if printf(“%d\n”, j);
                                        (j == 8) break;
                                    }
                                    printf(“%d\n”, j);
                                  }
Will this break be executed?


  MT 2009 (2)                  Introduction to Physics Computing (Tseng)                9
Blocks

n    Note that in previous examples, sometimes statements are
     given by themselves, and sometimes surrounded by {} (a
     “statement block”)
n    The rule is that a statement can be replaced by a statement
     block
n    Sometimes it is good to use {} just for clarity
      if (day == 7)      if (day == 7) {
        sleep(1);          sleep(1);
      workMore();        }
                         workMore();                                if (day == 7) {
                                                                      sleep(1);
    if (day == 7) sleep(1);                                           workMore();
    workMore();                                                     }

MT 2009 (2)             Introduction to Physics Computing (Tseng)                     10
Variable scope
                                                            #include <stdio.h>
n    Another function of a
     statement block: define the                            int main()
     range over which a name is                             {
                                                              int n;
     valid (“scope”)
                                                                n = 5;
                Outer scope
                                                                {
                Inner scope                                                     This will print “7”
                                                                       int n;
n    Local names take
                                                                       n = 7;
     precedence over others –                                          printf(“%d\n”, n);
     the closest definition                                     }
     matters most
                                                                printf(“%d\n”, n);
                                                                return 0;
                This will print “5”
                                                            }
MT 2009 (2)                Introduction to Physics Computing (Tseng)                          11
Functions

n    If you notice you are using a certain
     sequence of statements over and over, the
     sequence might be encapsulated in a
     function
     q    Saves typing the sequence repeatedly
     q    Saves having to modify the sequence in multiple
          places if you need to change it
n    Standard C library includes a number of
     useful functions such as printf(), scanf(),
     sin(x), exp(x)
MT 2009 (2)            Introduction to Physics Computing (Tseng)   12
Functions (2)

n    Bathing example again:


       int shampoo() {                         void cycle() {
         lather();                               lather();
         rinse();                                rinse();
         if (isRequired()) {                   }
           lather();
           rinse();                            int shampoo() {
         }                                       cycle();
         return 0;                               if (isRequired()) cycle();
       }                                       }




MT 2009 (2)            Introduction to Physics Computing (Tseng)         13
Functions (3)

n    Combinatorial:
                                           double factorial(int n) {
                                             double x = 1.0;
                                             while (n > 1) x *= n--;
                                             return x;
n    A function parameter                  }

     (n) is a local variable in            double comb(int n, int r) {
     the function                            return factorial(n) /
                                               (factorial(r) *
n    Note: there are more                       factorial(n-r));
     intelligent ways to                   }
     implement a factorial


MT 2009 (2)            Introduction to Physics Computing (Tseng)         14
Function parameters
n    A function is characterized by
     q   Its name
     q   The type of its return value
     q   The order and types of its parameters
                                 double cos(double x);
     q   It doesn’t make much sense to try to take the cosine of a string; if it happens,
         it’s probably a mistake
n    “header files” such as stdio.h declare a number of function prototypes
     so that the compiler can check your use of printf()
n    Slightly esoteric point: when you define a function, you also define the
     extent of the information on which the return value depends.
     Conversely, a function prototype encodes all the information needed to
     call the function.
     q   This point is violated by variables with “global” scope. In almost all cases
         where you might be tempted to use such variables, they are a bad idea and
         should be avoided. They will ruin your life and those of your friends.




MT 2009 (2)                    Introduction to Physics Computing (Tseng)                15
Outline

þ    Control flow
     þ   Conditional
     þ   Loops
     þ   Statements and blocks
     þ   Functions
n    Data structures
     q   Arrays
     q   Strings
     q   Structures


MT 2009 (2)           Introduction to Physics Computing (Tseng)   16
Data structures

n    Any program beyond a straightforward
     calculation will use collections of data
n    Many programs will perform repetitive
     calculations on repetitive data
     q   Main use of loops is to do exactly this




MT 2009 (2)            Introduction to Physics Computing (Tseng)   17
Arrays

n    An array is an ordered collection of identical objects
     q   A mathematical vector is often represented as (three) real
         numbers (x,y,z) or v=(v1,v2,v3)
n    In C, arrays are declared with their size, and
     indexed from 0
                                                                      /* space vector */
                                                                      float v[3];
v                  v1       v2             v3                         v[0] = 1.0;
                                                                      v[1] = 2.0;
float v[3]         v[0]     v[1]           v[2]                       v[2] = 3.0;
                                                                      printf(“(%f,%f,%f)\n”,
                                                                        v[0],v[1],v[2]);



MT 2009 (2)               Introduction to Physics Computing (Tseng)                     18
Arrays (2)

n    An array can also be thought of as a representation
     of memory
     q   Your college pigeonhole may be referred to as “John’s
         pigeonhole”, or “the pigeonhole four from the leftmost”

              Adam   Dan   Deb       Eve         John        Judy       Mark   Zeph




               0      1     2           3           4           5         6      7


MT 2009 (2)                 Introduction to Physics Computing (Tseng)                 19
Multidimensional arrays

n    Most college pigeonholes are not arranged in a line:
     Li is in the second row, 6 from the left
n    Two-dimensional arrays can be stored directly in C

                                                          float m[5][3];
Ab   Ad       Be   Do   Er   Fi   Fo   Gil                int j,k;

                                                          /* clear the matrix */
Hy   Ip       Jo   Ke   La   Le   Li   Lo                 for (j = 0; j < 5; ++j) {
                                                            for (k = 0; k < 3; ++k) {
                                                              m[j][k] = 0.0;
Lu   Ma       Ng   Ny   Ox   Po   Ri   St
                                                            }
                                                          }

MT 2009 (2)                            Introduction to Physics Computing (Tseng)        20
Strings
n    Strings in C are arrays of type char
n    They are an important enough type of array that they have
     their own conventions and library of common routines
     q    A string is terminated by a “null” character (==0)
     q    A string has a “capacity” (how many chars in the array) and a
          “length” (how many chars before the null terminator)

         #include <string.h>

         int main() {
           char s[10];
           strcpy(s, “hello”);
           printf(“string ‘%s’ has length %d\n”, s, strlen(s));
           return 0;
         }

MT 2009 (2)                 Introduction to Physics Computing (Tseng)     21
    Strings (2)

                                                    n     You can manipulate strings
int main() {
  char s[10];                                             on a character level by
                                                          simply modifying the array
    /* put a string into s */                             q    Sometimes useful practice:
    strcpy(s, “hello”);                                        guarantee that a string
                                                               terminates by assigning 0 to
    /* make sure it is terminated */
    s[9] = 0;
                                                               the last position in the array
                                                    n     C uses the double-quote
    /* change the string */                               mark (“) for strings and
    s[3] = ‘p’;
                                                          single-quote mark (‘) for
    s[4] = ‘!’;
    printf(“New string: %s\n”, s);                        char
}                                                         q    ‘c’ takes one char space
                                                          q    “c” takes two: ‘c’ and 0

    MT 2009 (2)         Introduction to Physics Computing (Tseng)                       22
Strings (3)

n    Note that C doesn’t check whether you’ve overrun
     the capacity of your string (or array)!

                char s[10];
                strcpy(s, “Hello, world!”);

n    Depending on circumstances, you may inadvertently
     overwrite other pigeonholes in your program
n    For simple programs, you are likely able to get away
     with this, but this kind of sloppiness is the root of
     many Internet vulnerabilities (“buffer overrun”)


MT 2009 (2)          Introduction to Physics Computing (Tseng)   23
Structures

n    C structures are collections                                     struct    nomen {
                                                                         char   first[50];
     of non-identical data                                               char   middle[50];
n    Similar to a database record                                        char   last[50];
                                                                      };
n    Particularly useful when
                                                                      struct person {
     combined with arrays                                               struct nomen name;
                                                                        float age; /* years */
              Miscellaneous note: it’s a good idea that                 float weight; /* lbs */
              you keep track of intended units in
              comments. Satellites have crashed for this              } staff[5];
              kind of reason!

         printf(“Employee %d (name %s %s %s) is aged %f years\n”,
           j, staff[j].name.first, staff[j].name.middle,
           staff[j].name.middle, staff[j].age);

MT 2009 (2)                        Introduction to Physics Computing (Tseng)                  24
Data structures and programs
n        Defining data structures is often one of the first
         tasks of programming
     n        List the quantities you want at the end
         n       Numbers, histograms, data files, etc.
         n       Data is often grouped logically, e.g., particle position and/or
                 momentum, mass, charge
     n        List the information which is to be provided
     n        List the relationships between the two sets of data
n        Data structures often have associated methods
         and relationships with other data structures
     q        One of the key reasons behind “object-oriented”
              programming languages, e.g., Smalltalk, Java



MT 2009 (2)                  Introduction to Physics Computing (Tseng)        25
Next lecture

n    Same time and place (Mon 10am Martin
     Wood)
n    Data representation
n    File input and output




MT 2009 (2)      Introduction to Physics Computing (Tseng)   26

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:7/24/2013
language:English
pages:26