Presentation is loading. Please wait.

Presentation is loading. Please wait.

Let’s summarize what we have learnt so far

Similar presentations


Presentation on theme: "Let’s summarize what we have learnt so far"— Presentation transcript:

1 Let’s summarize what we have learnt so far
A C program is organized into one or more modules (source files created by a programmer), within which are various functions and variables. As a minimum the ‘main’ function must exist. The compiler A.Honey (Oct 2003) S2-1

2 Let’s summarize what we have learnt so far
A C program is organized into one or more modules (source files created by a programmer), within which are various functions and variables. As a minimum the ‘main’ function must exist. The compiler parses the modules and, if they are syntactically correct, translates them into assembly code -> object code. The linker A.Honey (Oct 2003) S2-2

3 Let’s summarize what we have learnt so far
A C program is organized into one or more modules (source files created by a programmer), within which are various functions and variables. As a minimum the ‘main’ function must exist. The compiler parses the modules and, if they are syntactically correct, translates them into assembly code -> object code. The linker builds an executable program from the various pieces of object code. The preprocessor A.Honey (Oct 2003) S2-3

4 Let’s summarize what we have learnt so far
A C program is organized into one or more modules (source files created by a programmer), within which are various functions and variables. As a minimum the ‘main’ function must exist. The compiler parses the modules and, if they are syntactically correct, translates them into assembly code -> object code. The linker builds an executable program from the various pieces of object code. The preprocessor checks for directives, which begin with ‘#’, to alter or enhance the input to the compiler. This is the means for telling the compiler what the required parameters are for the functions within the various modules. A.Honey (Oct 2003) S2-4

5 Let’s summarize what we have learnt so far
Functions are the C equivalent of subroutines. Functions allow a program to be broken into smaller more manageable and maintainable pieces. Each function has a set of input and output requirements (parameters and declarations) that must be adhered to by any program which uses those functions. A.Honey (Oct 2003) S2-5

6 Let’s summarize what we have learnt so far
Variables are used to pass data values from one place in the program to another. Each variable must be declared, thereby, providing the compiler with the type of the variables so that it knows the representation of the data in physical memory. Different types are represented differently in memory. When a variable is defined the compiler locates a memory location for the associated data value and uses that location throughout the life of the variable. There may be many types of variables but they are all derived from four basic types. We have used integer and floating-point variables in a program. A.Honey (Oct 2003) S2-6

7 Let’s summarize what we have learnt so far
Punctuation is an important component of the syntax. Whenever you use a function (call the function) the parameters to that function must be comma separated and collectively enclosed in parentheses. When a function is created (declared) it’s argument list must also be comma separated and enclosed in parentheses. The beginning of a function is delineated by a brace ‘{‘ as is the ending ‘}’. This is also true for blocks of statements, as we will see for conditional and looping statements. Most if not all statements must be terminated with a semi-colon. Comments must be enclosed in ‘/*’ and ‘*/’. A.Honey (Oct 2003) S2-7

8 Let’s revisit the program from last week at pgm6.
C variables S2_pgm1 Let’s revisit the program from last week at pgm6. This was the first taste that the variables we create truly are variable. Add in printf statements to display the resultant values of the two variables. Why are the two values so drastically different? A.Honey (Oct 2003) S2-8

9 Let’s revisit the program from last week at pgm6.
C variables Let’s revisit the program from last week at pgm6. This was the first taste that the variables we create truly are variable. Add in printf statements to display the resultant values of the two variables. Why are the two values so drastically different? We modified ivar to be (1111 * ) before we modified fvar, which will now be (1111 * ) * Keeping in mind that ivar has only the integer part of the result of the first multiplication. A.Honey (Oct 2003) S2-9

10 C variables S2_pgm2 Let’s modify the program so that both ivar and fvar end up with the value of (1111 * ). We’ll do this by creating a third variable to hold the original value of ivar before the multiplication. A.Honey (Oct 2003) S2-10

11 C variables S2_pgm2 Let’s modify the program so that both ivar and fvar end up with the value of (1111 * ). We’ll do this by creating a third variable to hold the original value of ivar before the multiplication. This technique of using a variable as a temporary holding place becomes useful in algorithms for sorting and searching through lists. A.Honey (Oct 2003) S2-11

12 C variables So far we have defined our variables with initial values that have been constants. So how can we provide initial values that are user supplied? A.Honey (Oct 2003) S2-12

13 Modify your program as shown.
C variables S2_pgm3 So far we have defined our variables with initial values that have been constants. So how can we provide initial values that are user supplied? The first technique is to supply values when the program starts. This is called command line input. In order for this to work we must give our main function some input arguments. For main they are typically always the same, an argument count ‘argc’ and an array of strings ‘argv’. So let’s experiment a little bit. Modify your program as shown. Note we will pursue understanding character and string variables and arguments in a future session. A.Honey (Oct 2003) S2-13

14 C variables By default, there is always at least one command line argument provided to main and that is the name of the program. A.Honey (Oct 2003) S2-14

15 in wedit project->configuration->debugger
C variables s2_pgm4 By default, there is always at least one command line argument provided to main and that is the name of the program. Now let’s provide a couple of more command line arguments. We will do this by using: in wedit project->configuration->debugger Enter your first and last names in the command line argument section. Then modify you program to print out the appropriate arguments (be sure to check that they exist first). A.Honey (Oct 2003) S2-15

16 in wedit project->configuration->debugger
C variables By default, there is always at least one command line argument provided to main and that is the name of the program. Now let’s provide a couple of more command line arguments. We will do this by using: in wedit project->configuration->debugger Enter your first and last names in the command line argument section. Then modify you program to print out the appropriate arguments (be sure to check that they exist first). Note this was our first use of a conditional statement. We will pursue that topic after dealing with user input. Why were those ‘if’ statements needed? A.Honey (Oct 2003) S2-16

17 in wedit help->standard C library
C variables The one caveat to command line arguments is that all arguments are given to main as character strings, which are not the same as integer or floating-point values. If the program requires numeric values then the character strings must be converted using functions in the standard C library. in wedit help->standard C library Check the ASCII conversion functions. These are the functions beginning with ‘ato…’ which stands for ‘ASCII to’. A.Honey (Oct 2003) S2-17

18 in wedit help->standard C library
C variables S2_pgm5 The one caveat to command line arguments is that all arguments are given to main as character strings, which are not the same as integer or floating-point values. If the program requires numeric values then the character strings must be converted using functions in the standard C library. in wedit help->standard C library Check the ASCII conversion functions. These are the functions beginning with ‘ato…’ which stands for ‘ASCII to’. Modify your program so that the command line arguments are and and display the output from atoi and atof. A.Honey (Oct 2003) S2-18

19 C variables S2_pgm6 The second method for getting user values is to query for keyboard input. So modify your program to request values using the scanf function. The scanf function is the complement of the printf function. The scanf function requires that you specify how the incoming data is to be interpreted. The variables, into which the data values will be written, must also be of compatible types. So ‘%d’ tells scanf that an integer value is expected and ‘%f’ or ‘%e’ indicates that the input will be floating-point. In a future session we will deal with the ‘%s’ format for character strings. A.Honey (Oct 2003) S2-19

20 C variables There is a new syntactical item in what we have done. That is, the ampersands in front of the variables that were the arguments to the scanf function. A.Honey (Oct 2003) S2-20

21 C variables There is a new syntactical item in what we have done. That is, the ampersands in front of the variables that were the arguments to the scanf function. The ‘&’ tells the compiler to pass the address of the variable, which is actually the address of the memory location. This is called passing by reference. Why do you think this is necessary? A.Honey (Oct 2003) S2-21

22 You can actually display variables’ addresses.
C variables S2_pgm7 Remember that the variable name indicates to the compiler that a data value must be written or retrieved. If we simply put the variable name in the function call to scanf then the compiler would retrieve the current value and pass that to the function. However, the scanf function needs to write the user entered value into the memory location. Hence, scanf must be given the address of that memory location. You can actually display variables’ addresses. Modify your program as shown and run it. A.Honey (Oct 2003) S2-22

23 Conditional statements and expressions
In order to allow decisions, as to what is to occur next in a program, a programming language must provide some form of conditional statement. In C this is done with the traditional ‘if then else’ construct. The two simplest forms are: if ( <conditional expression>) <true condition statement> and else <false condition statement> If the conditional expression evaluates to a nonzero value then the first statement is executed, otherwise, the second statement is executed. A.Honey (Oct 2003) S2-23

24 Conditional statements and expressions
Alternatively compound statements can be employed. A compound statement is a user defined block of statements enclosed in braces: if ( <conditional expression>) { <block of statements 1> } else <block of statements 2> } Single statements and compound statements can be inter-mixed within a given conditional construct. A.Honey (Oct 2003) S2-24

25 Conditional statements and expressions
Additional conditionals can be nested within the else. if ( <conditional expression 1>) { <block of statements 1> } else if (<conditional expression 2> ) <block of statements 2> } else <block of statements 3> } The depth of nesting is compiler dependent. However, if more than 3 or 4 nests are needed then there is usually a better way to implement the program. A.Honey (Oct 2003) S2-25

26 Conditional statements and expressions
A conditional expression can be as simple as a variable or it can be quite complex. A typical expression would involve a relational expression, however, any numerical expression is also valid as any nonzero result would cause the ‘then’ clause (first statement block) to be executed. The relational operators are: <, <=, >, >= less than or greater than ==, != equal or not equal && logical AND || logical OR The tutorial section provides a table of all valid operators and their precedence (order of evaluation). A.Honey (Oct 2003) S2-26

27 Conditional control S2_pgm8
If you recall, in a previous program we used conditional statements to test the existence of the command line arguments. Those statements were the simplest form of the conditional construct. So let’s modify the program, which requests the user to enter values, so as to check the relative sizes of the values. Run your program several times and try to make each of the printf statements execute. A.Honey (Oct 2003) S2-27

28 Conditional control If you recall, in the previous program we used conditional statements to test the existence of the command line arguments. Those statements were the simplest form of the conditional construct. So let’s modify the program, which requests the user to enter values, so as to check the relative sizes of the values. Run your program several times and try to make each of the printf statements execute. Note that each compound statement (the braces enclosed blocks containing the printf statements) could each have contained multiple statements. A.Honey (Oct 2003) S2-28

29 Lets extend our integer and floating-point variable capabilities.
Variables Revisited Lets extend our integer and floating-point variable capabilities. What do you do if you need a list of values? A.Honey (Oct 2003) S2-29

30 Lets extend our integer and floating-point variable capabilities.
Arrays Lets extend our integer and floating-point variable capabilities. What do you do if you need a list of values? You create a one-dimensional array (vector). The syntax in C is straight forward. You must tell the compiler both the type of the values in the array and the size of the array, which is depicted by an integer value enclosed in brackets. For instance a 20 element array of floating-point values would be declared as such: float my_array[20]; A.Honey (Oct 2003) S2-30

31 Lets extend our integer and floating-point variable capabilities.
Arrays Lets extend our integer and floating-point variable capabilities. What do you do if you need a list of values? You create a one-dimensional array (vector). The syntax in C is straight forward. You must tell the compiler both the type of the values in the array and the size of the array, which is depicted by an integer value enclosed in brackets. For instance a 20 element array of floating-point values would be declared as such: float my_array[20]; What if you need a two dimension array? A.Honey (Oct 2003) S2-31

32 Arrays Multi-dimensional arrays in C are simply an extension of the one-dimensional array. You simply add the sizes of the additional dimensions, where each size is enclosed in brackets. For instance, a 10 by 20 integer array would be declared as: int your_array[10][20]; A.Honey (Oct 2003) S2-32

33 Arrays Multi-dimensional arrays in C are simply an extension of the one-dimensional array. You simply add the sizes of the additional dimensions, where each size is enclosed in brackets. For instance, a 10 by 20 integer array would be declared as: int your_array[10][20]; The number of dimensions allowed is compiler dependent but usually at least 3 dimensions are valid. Assuming int is 4 bytes (32 bits) then how much space must the compiler allocate for the aforementioned array? A.Honey (Oct 2003) S2-33

34 Arrays Multi-dimensional arrays in C are simply an extension of the one-dimensional array. You simply add the sizes of the additional dimensions, where each size is enclosed in brackets. For instance, a 10 by 20 integer array would be declared as: int your_array[10][20]; The number of dimensions allowed is compiler dependent but usually at least 3 dimensions are valid. Assuming int is 4 bytes (32 bits) then how much space must the compiler allocate for the aforementioned array? 800 Before we experiment with arrays let’s learn about looping constructs so that we can use the arrays more effectively. A.Honey (Oct 2003) S2-34

35 Loop D loop C has three control structures which allow a statement or group of statements to be repeated a fixed or variable number of times: while, do-while, and for. I think the do-while loop is not available in Interactive C, which is the C development system will use with the botball controller, however we will use the do-while loop in one program anyways. A.Honey (Oct 2003) S2-35

36 The while loop has syntax of the form:
while ( <termination expression> ) <statement>; and while ( <termination expression> ) { <compound statement block>; } The statements will be executed until the termination expression becomes false. That is, as long as it evaluates to a non-zero value the loop will continue. So how does the loop terminate? A.Honey (Oct 2003) S2-36

37 The while loop has syntax of the form:
while ( <termination expression> ) <statement>; and while ( <termination expression> ) { <compound statement block>; } The statements will be executed until the termination expression becomes false. That is, as long as it evaluates to a non-zero value the loop will continue. So how does the loop terminate? One of the statements in the body of the loop must eventually alter the result of the expression. A.Honey (Oct 2003) S2-37

38 While loop S2_pgm9 Let’s add a while loop to our program that requests the user to enter values. Make the loop continue until the second value (fvar2) is 0. What do you think would happen if we did not set the initial values of the variables to 1? A.Honey (Oct 2003) S2-38

39 While loop Let’s add a while loop to our program that requests the user to enter values. Make the loop continue until the second value (fvar2) is 0. What do you think would happen if we did not set the initial values of the variables to 1? When the compiler allocates the memory locations for the variables then there initial values would be whatever is currently in that memory. Random values! If fvar2 happened to have 0 in its memory location then the while loop would terminate immediately. A.Honey (Oct 2003) S2-39

40 do <statement>; while (<termination expression>); and do {
Do-While loop The do-while loop is similar to the while loop, however the construct commences with the word ‘do’ and terminates with the conditional as follows: do <statement>; while (<termination expression>); and do { <compound statement>; } while (<termination expression>); Analogous to the while loop the loop continues until the termination expression evaluates to zero. A.Honey (Oct 2003) S2-40

41 So modify your program to use the do-while construct.
Do-While loop S2_pgm10 The do-while loop simplifies our previous program as we do not have to assign initial values to the variables. The user entered values will be input before the terminating expression. So modify your program to use the do-while construct. A.Honey (Oct 2003) S2-41

42 So modify your program to use the do-while construct.
Do-While loop The do-while loop simplifies our previous program as we do not have to assign initial values to the variables. The user entered values will be input before the terminating expression. So modify your program to use the do-while construct. What happens with the following? do { printf(“Help me!!!!\n”); } while ( 1 ); A.Honey (Oct 2003) S2-42

43 So modify your program to use the do-while construct.
Do-While loop The do-while loop simplifies our previous program as we do not have to assign initial values to the variables. The user entered values will be input before the terminating expression. So modify your program to use the do-while construct. What happens with the following? do { printf(“Help me!!!!\n”); } while ( 1 ); This is a perfectly valid infinite loop, which actually has utility! And, it is going to eat up a lot of your computer time. A.Honey (Oct 2003) S2-43

44 for (<initial expression>; <termination expression>;
For loop The for loop is the most complex of the looping constructs and is also the most versatile. Consequently, the syntax is also complex. for (<initial expression>; <termination expression>; <iteration expression> ) { <statement block>; } Note that the compound statement may be a single statement instead (i.e. without the braces). A.Honey (Oct 2003) S2-44

45 for (<initial expression>; <termination expression>;
For loop The for loop is the most complex of the looping constructs and is also the most versatile. Consequently, the syntax is also complex. for (<initial expression>; <termination expression>; <iteration expression> ) { <statement block>; } Note that the compound statement may be a single statement instead (i.e. without the braces). Any of the ‘expressions’ may be empty, in which case the separating semi-colon is still required. Also, the initial and iteration expressions may be a list of any statements, where each statement is separated from the next by a comma. A.Honey (Oct 2003) S2-45

46 For loop initial expression
The statements in the initial expression are only execute at the beginning of the loop and not each time through the loop. Typically the statements, in the initial expression list, are used to initialize variables, for instance, a variable to keep track of the number of iterations through the loop may be set to zero ‘idx = 0;’ or ‘idx = 0, idx2 = 0;’. The second variation demonstrates that multiple statements can be used. In fact, the statements, in the initial expression list, can more-or-less be any valid C statements, although I have never tried embedding another looping structure therein. Anybody want to experiment? A.Honey (Oct 2003) S2-46

47 For loop termination expression
The termination expression is similar to the while loop termination expression, as the evaluation of the termination expression determines whether or not the loop terminates. As long as the termination expression evaluates to non-zero the for loop continues. Typically, the termination expression is a relational expression. The termination expression is always evaluated at the ‘top’ of the loop, that is before any of the statements in the body of the loop are executed. A.Honey (Oct 2003) S2-47

48 For loop iteration expression
The iteration expression may also be a comma separated list of statements. Those statements are executed at the ‘bottom’ of the loop, that is, after the statements in the body of the loop have been executed and before the termination expression is evaluated and before the next iteration of the loop commences. The iteration expression is typically where the loop counter variable would be altered (usually incremented by 1) ‘idx = idx+1’ or, more compactly ‘idx++’. But again, the iteration expression list can be whatever statements the programmer deems necessary! A.Honey (Oct 2003) S2-48

49 Okay so let’s create a couple of for loops.
1. A for loop to get user input until 0 is entered. Keeping track of the number of iterations through the loop. Don’t forget to declare your variables! A.Honey (Oct 2003) S2-49

50 Okay so let’s create a couple of for loops.
1. A for loop to get user input until 0 is entered. Keeping track of the number of iterations through the loop. Don’t forget to declare your variables! for (idx = 0; ivar > 0; idx++ ) { <your code to request values here> } printf(“There were %d user values entered\n”, idx); A.Honey (Oct 2003) S2-50

51 Note that C arrays always begin at element 0, NOT 1!
For loop 2. Modify the for loop to store the values in an integer array. At the end of the loop generate the sum of the values and the average of the values. Don’t forget to declare the array. Note that C arrays always begin at element 0, NOT 1! A.Honey (Oct 2003) S2-51

52 Note that C arrays always begin at element 0, NOT 1!
For loop 2. Modify the for loop to store the values in an integer array. At the end of the loop generate the sum of the values and the average of the values. Don’t forget to declare the array. Note that C arrays always begin at element 0, NOT 1! for (idx = 0, sum = 0; ivar < ; idx++ ) { <your code to request values here> myArray[idx] = ivar; sum = sum + ivar; } average = sum / idx; A.Honey (Oct 2003) S2-52

53 for (idx=0; idx<1000; idx++);
For loop What is the result of: for (idx=0; idx<1000; idx++); A.Honey (Oct 2003) S2-53

54 for (idx=0; idx<1000; idx++);
For loop What is the result of: for (idx=0; idx<1000; idx++); for (idx=0;;idx++) printf(“loop iteration %d\n”,idx); A.Honey (Oct 2003) S2-54

55 for (idx=0; idx<1000; idx++);
For loop What is the result of: for (idx=0; idx<1000; idx++); for (idx=0;;idx++) printf(“loop iteration %d\n”,idx); for (;;) printf(“Hello!\n”); A.Honey (Oct 2003) S2-55

56 Slamming on the breaks! There are a couple of C statements that let the behavior of a loop be modified within the body of the loop. One of those is the break statement. A.Honey (Oct 2003) S2-56

57 Break statement There are a couple of C statements that let the behavior of a loop be modified within the body of the loop. One of those is the break statement. When the break statement is executed the loop terminates immediately, without evaluating the termination expression and, in the case of the for loop, without executing the iteration expression! For instance, if we are requesting user input and we want to exit if the user enters 9999 then we could add the following to the loop body: if (ivar == 9999) break; A.Honey (Oct 2003) S2-57

58 Break statement There are a couple of C statements that let the behavior of a loop be modified within the body of the loop. One of those is the break statement. When the break statement is executed the loop terminates immediately, without evaluating the termination expression and, in the case of the for loop, without executing the iteration expression! For instance, if we are requesting user input and we want to exit if the user enters 9999 then we could add the following to the loop body: if (ivar == 9999) break; Typically, a break statement would be used to terminate a loop when an error or some other anomalous condition has occurred. A.Honey (Oct 2003) S2-58

59 Remember the array starts at 0.
Break statement There was a problem with the last two programs we created. There was nothing to prevent the user from entering more values than the size of the array! Modify your last program so that the loop terminates if the user enters more values than can be accommodated in the array. Remember the array starts at 0. A.Honey (Oct 2003) S2-59

60 Do it again daddy! Do it again!
There is also another C statement which allows altering the flow of control from within the body of a loop, namely, continue. A.Honey (Oct 2003) S2-60

61 Continue statement There is also another C statement which allows altering the flow of control from within the body of a loop, namely, continue. When the continue statement is executed the flow of control immediately changes to the end of the loop, thereby, skipping any intervening statements. In the case of a for loop, execution is transferred to the iteration expression statements, followed by the evaluation of the termination expression. For the do-while and while loops, execution is transferred to evaluation of the termination expression. A.Honey (Oct 2003) S2-61

62 Continue statement There is also another C statement which allows altering the flow of control from within the body of a loop, namely, continue. When the continue statement is executed the flow of control immediately changes to the end of the loop, thereby, skipping any intervening statements. In the case of a for loop, execution is transferred to the iteration expression statements, followed by the evaluation of the termination expression. For the do-while and while loops, execution is transferred to evaluation of the termination expression. The continue statement would typically be used when an event occurs which makes the remaining loop body statements undesired or superfluous. Usually this can be handled in a better way! A.Honey (Oct 2003) S2-62


Download ppt "Let’s summarize what we have learnt so far"

Similar presentations


Ads by Google