Download presentation
Presentation is loading. Please wait.
Published byJennifer Wright Modified over 8 years ago
1
CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016
2
Scope of a variable Every identifier in a program has a scope, which means the region of the program where it is defined. – The declaration dictates the scope of an identifier. – The enclosing block ( { } ) defines/specifies the scope of all variables except global variables, which are defined at the top-level of a program and are visible everywhere. The snippet of code below demonstrates variable scope: #include char chump = ‘k’; int main ( void ) { int chump = 666 ; … All references to chump in main( ) refer to the int chump All references to chump outside main( ) refer to the char chump
3
Global Variables Global variables and functions are "visible" or "reachable" everywhere in the program, including all functions (more about functions soon). However, use of global variables is usually considered poor programming practice.
4
Jump Statements/Commands C supports four jump statements/commands break continue return goto Jump statements/commands transfer the flow of control to another part of the program
5
break The break statement/command has two uses – First, as you have experienced, it terminates a statement sequence in a switch statement – Second, it can be used to exit a loop
6
break // Using break to exit a for loop 1.c #include int main( void ) { int index = 0 ; for ( index = 0 ; index < 1000 ; index = index + 1) { if( index == 17) break ; // terminate loop if index is 17 printf( "index: %d \n", index ) ; } printf( "\nLoop complete.\n\n" ) ; return 0 ; }
7
break // Using break to exit a while loop 2.c #include int main( void ) { int index = 0 ; while ( index < 1000 ) { if( index == 36 ) break ; // terminate loop if index is 36 printf( "index: %d \n", index ) ; index = index + 3 ; } printf( "\nLoop complete.\n\n" ) ; return 0 ; }
8
continue The continue command/statement accomplishes this: – immediately go to the bottom of the loop block of statements ( aka the closing } ) This means that in while and do-while loops, a continue statement/command essentially causes the flow of control to be transferred to the conditional expression that controls the loop. In a for loop, the flow of control is transferred to the "loop adjustment" portion of the for statement and then to the conditional expression for evaluation
9
continue // Demonstrate continue in a while loop 3.c #include int main( void ) { int index = 0 ; while ( index < 1000 ) { index = index + 1; continue ; printf("\nThe value of index is: ", index ) ; //never executed } printf("\nThe program complete, final value of index: %d\n\n ", index ) ; return 0 ; }
10
continue // Demonstrate continue in a for loop 4.c #include int main( void ) { int index = 0 ; for ( index = 0 ; index < 1000 ; index = index + 1 ) { index = index + 1; continue ; printf("\nThe value of index is: ", index ) ; //never executed } printf("\nThe program complete, final value of index: %d\n\n ", index ) ; return 0 ; }
11
return The return statement/command is used to explicitly exit a function. – This means that return causes the flow of control to be transferred back to the calling/initiating function or program or the operating system
12
return // Using return to exit the main ( ) from within a while loop 5.c #include int main( void ) { int index = 0 ; while ( index < 1000 ) { if( index == 36 ) return 0 ; // exit the main( ) if index is 36 printf( "index: %d \n", index ) ; index = index + 3 ; } printf( "Loop complete." ) ; // never executed return 0 ; // never executed }
13
goto It's possible to jump to any statement within the same function using goto A label is used to mark the destination of the jump
14
goto #include // 6.c int main(void) { int k = 1; again: // label printf( "\n %d ", k ) ; k = k + 1 ; if( k < 15 ) goto again ; printf( "\n Program complete.\n\n\n" ) ; return 0; }
15
Single Variables are Boring!!
16
There are lots of times we’d like to work with a bunch of "like things" – we can refer to this "bunch of like things" as a homogeneous group or collection – In C the concept of being homogeneous or the "homogeneity" of groups/collections means the member of the group have the same data type Here’s an example of a collection of floats: 1.4 7.1 3.14 5.5 17.0 6.1
17
Single Variables are Boring!! Groups or collections of items – Because they are the same type we need a way to distinguish one from the other – "order" to the rescue… intuitively we might use these labels first item second item third item fourth item fifth item sixth item 1.47.1 3.14 5.5 17.0 6.1
18
Single Variables are Boring!! Our intuition is off by 1… in C an ordered list does not begin with "first" item… it begins with zeroth item zeroth item first item second item third item fourth item fifth item 1.47.1 3.14 5.5 17.0 6.1
19
Single Variables are Boring!! zeroth, first, second, etc… are too long – We need a little shorthand… we can barrow from matrix notation – While we’re at it, let’s name the collection (we’ll call this one A) A 0 A 1 A 2 A 3 A 4 A 5 1.47.1 3.14 5.5 17.0 6.1
20
Single Variables are Boring!! This shorthand works, too… we prefer this method A[0] A[1] A[2] A[3] A[4] A[5] 1.4 7.1 3.14 5.5 17.0 6.1
21
An Array A "data structure" in which items of the same data type are stored sequentially (in order): – item 0, item 1, item 2, item 3... These homogenous data items are stored in memory in sequential order (contiguously): index[0] index[1] index[2] index[3] item 0 item 1 item 2 item 3
22
Arrays For now, as we introduce the concept of an array, think of an array as a list Array named "snow": [13.2, 7.3, 4.4, 65.3] Each position is accessed by a "subscript" or "index value": snow[0] snow[1] snow[2] snow[3] 13.2 7.3 4.4 65.3
23
Arrays snow 0 or snow[0] is 13.2 snow 1 or snow[1] is 7.3 etc... Soon we will expand the notion of an array beyond a simple list – We can easily use the array data structure to construct things like matrices and tables
24
Arrays Why do arrays in C start with 0? – The subscript tells how far from the beginning of the array it is to the element we want. This is known as the offset. Offset from what? From the array’s address!!
25
Arrays An array shares traits with single variables: – Name (also known as an identifier) – Data type – Address An array has a "address" and each value (element) in the array is found using the "offset" from this address – Value... instead of a single value, an array has the capability to hold multiple values – One value per array element
28
Array Declaration To declare an array you need: – Data type (what kind of values will the array hold?) – Name/Identifier – Size (how many different values will the array hold?) int golf_score[18]; – As with other variables, the compiler/OS handle assigning an array its address in memory with enough space to hold the array's values
29
Array Declaration Programmers often use a constant to specify the size of an array: const int SIZE = 18 ; int golf_score[SIZE] ; or #define SIZE 18 … int golf_score[SIZE] ;
30
Array Declaration
31
Array Initialization
32
Arrays and Input/Output Loops are commonly used to facilitate efficient input/output and traversing for arrays... const int SIZE = 18 ; int golf_score[SIZE] ;... for ( i = 0; i < SIZE ; i = i + 1 ) { printf("\n\n Enter a golf score: "); scanf("%d", &golf_score[i]); }
33
Arrays and Input/Output Print all the elements of an array, one element per line for ( i = 0 ; i < size ; i++ ) { printf("%d \n ", golf_score[i]); }
34
Arrays and Input/Output Print all the elements of an array with their element subscripts (index)… in this case print each hole number and its corresponding score and put each hole and score on a different line... we often use i to indicate "index" for ( i = 0 ; i < size ; i++ ) { printf("Hole %d score was %d \n ", i + 1, golf_score[i]); } OR for ( i = 1; i <= size ; i++ ) { printf("Hole %d score was %d\n", i, golf_score[ i - 1]); }
35
Array Indices Highest and lowest indices form the bounds of the array In C, the lower bound is always 0 In C, the upper bound is always 1 less than the size of the array (remember: the array begins with 0 not 1) C cannot check array bounds… it must be done manually
36
Array "Bounds" Checking const int size = 18; int golf_score[size]; int hole = 0; printf("For which hole do want the score? "); scanf ("%d", &hole); if ( (hole >= 1) && (hole <= size)) { printf ("\n\nOn hole number %d you carded: %d\n", hole, golf_score[hole-1]); } else
37
#include //My file 7.c #define size 18 int main ( ) { int golf_score[size] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36}; int hole = 0; printf( "\n\nFor which hole do want the score? " ) ; scanf ( "%d", &hole ) ; if ( ( hole >= 1) && (hole <= size) ) { printf ("\n\nOn hole number %d you carded: %d\n", hole, golf_score[hole-1]); } else { printf("\n\nSorry, but your entry of hole %d is not appropriate.\n", hole ) ; } return 0; }
38
Array Practice Let’s write a program that: - prompts the user to enter 5 test scores (the program must store the scores into an array named test_scores); - calculates the average score (the program must use the array test_scores); - displays the results.
39
Array Practice 1. Greet the user 2. Create a place where 5 test scores can be recorded and retained temporarily 3. Create a place where the total of 5 test scores can be recorded and retained temporarily; store 0 there initially 4. Create a place where the average of the 5 test scores can be recorded and retained temporarily, store 0 there initially 5a. Prompt user to enter a test score 5b. Read user's input for a test score 5c. Repeat steps 5a and 5b until 5 scores are obtained 6a. Go to the place where the 5 test scores are recorded 6b. Read one test score 6c. Add the test score to total 6d. Repeat steps 6a to 6c until all 5 test scores and been read and added to total 7. Find average using formula: average = total / number of test scores 8. Display results to the user 9. End
40
#include //My file 8.c #define SIZE 5 int main (void) { int i = 0 ; float test_scores [SIZE], total = 0.0, average = 0.0 ; for ( i = 0 ; i < SIZE ; i = i + 1) { printf("\n Enter a test score: "); scanf("%f", &test_scores [i] ); } for ( i = 0 ; i <= SIZE ; i = i + 1) total = total + test_scores[i] ; average = total / SIZE; printf ("\n\n The average of your test scores is: %f \n\n\n", average); return (0) ; } Does this produce a correct result? Why or why not?
41
Assigning Values to Array Elements Cannot assign values to entire arrays as a whole Values are assigned to individual elements – Examples: golf_score[0] = 3; test_2_grade[3] = 'C'; retail_price[2] = 1234.45;
42
Assigning Values to Array Elements More array element assignment examples: retail_price[0] = 5.75; retail_price[0] = retail_price[0] * 1.03; retail_price[1] = retail_price[2] - 2; retail_price[2] = retail_price[1] * 7; retail_price[x] = retail_price [x + 1]; retail_price[x] = retail_price [x] + 1; Note: index can be any integer expression.
43
Accessing Array Elements Remember: array indices always, always, always start at 0 Access a specific array element by using the array name followed by the index in square brackets: golf_score[0] total = total + golf_score[17]
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.