CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Introduction to C Programming
Intermediate Code Generation
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Kernighan/Ritchie: Kelley/Pohl:
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
CS0007: Introduction to Computer Programming Introduction to Arrays.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Systems Programming Concepts
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Array Lesson 1 CS1313 Spring Array Lesson 1 Outline 1.Array Lesson 1 Outline 2.Mean of a List of Numbers 3.mean: Declarations 4.mean: Greeting,
CS 108 Computing Fundamentals Notes for Thursday, February 12, 2015.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Chapter 8 Arrays and Strings
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1. 1. Introduction to Array 2. Arrays of Data 3. Array Declaration 4. Array Initialization 5. Operations on Array 6. Multidimensional Arrays 7. Index.
ICS103 Programming in C Lecture 11: Arrays I
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Engineering Computing I Chapter 3 Control Flow. Chapter 3 - Control Flow The control-flow of a language specify the order in which computations are performed.
1 CSC103: Introduction to Computer and Programming Lecture No 17.
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Flow Control. Comments u Comments: /* This is a comment */ –Use them! –Comments should explain: v special cases v the use of functions (parameters, return.
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, For loop While loop Do while loop
EKT150 : Computer Programming
Declaration, assignment & accessing
Loops in C.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
ICS103 Programming in C Lecture 12: Arrays I
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016

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

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.

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

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

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 ; }

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 ; }

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

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 ; }

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 ; }

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

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 }

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

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; }

Single Variables are Boring!!

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:

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

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

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

Single Variables are Boring!! This shorthand works, too… we prefer this method A[0] A[1] A[2] A[3] A[4] A[5]

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

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]

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

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

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

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

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] ;

Array Declaration

Array Initialization

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]); }

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]); }

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]); }

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

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

#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; }

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.

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

#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?

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] = ;

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.

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]