8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.

Slides:



Advertisements
Similar presentations
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Advertisements

Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Multiple-Subscripted Array
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.
 Pearson Education, Inc. All rights reserved Arrays.
C programming---Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.
Array.
A First Book of ANSI C Fourth Edition
Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Computer Science 210 Computer Organization Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
CSE 251 Dr. Charles B. Owen Programming in C1 Pointers, Arrays, Multidimensional Arrays Pointers versus arrays – Lots of similarities How to deal with.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 3.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
COP 3275: Chapter 08 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Sorting –Bubble sort –Merge sort –Quick sort –Selection.
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.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Arrays.
Computer Programming for Engineers
ONE DIMENSIONAL ARRAYS AND RANDOM NUMBERS. Introduction In addition to arrays and structures, C supports creation and manipulation of the following data.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers… –You need 7 variables (6 for winning numbers and 1 for the special number)
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Dr. Sajib Datta Feb 11,  Example of declaring and initializing an array. ◦ double someData[3]; /* declare the array someData that will.
Arrays. Arrays are objects that help us organize large amounts of information.
 2005 Pearson Education, Inc. All rights reserved Arrays.
CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Dr. Sajib Datta Sep 10,  #include  void main()  {  int a = 25;  int b = 0;  int c = -35;  if( a || b ) ◦ printf("Test1\n");  else.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
CSE 220 – C Programming Loops.
C programming---Arrays
Arrays Declarations CSCI N305
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
9. FUNCTIONS.
Module 2 Arrays and strings – example programs.
CNG 140 C Programming (Lecture set 8)
Lecture 10 Arrays.
EKT150 : Computer Programming
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Outline Defining and using Pointers Operations on pointers
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Lecture 14: Problems with Lots of Similar Data
Presentation transcript:

8. ARRAYS

Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type

One-Dimensional Arrays A one-dimensional array is declared in the following way: int a[10]; The number 10 declares that a will have ten elements. Array bounds always start at 0, so a has the following appearance: Notice that 10 is the length of the array, not the array’s upper bound.

Array size #define N 10 … int a[N];

Array Subscripting To select an element of an array, use the [] operator: a[0] a[i] a[i*2+1] This operation is called array subscripting. Expressions of the form a[i] are lvalues a[0] = 1; printf("%d\n", a[5]); ++a[i];

Array idioms for (i = 0; i < N; i++) a[i] = 0; /* clears a */ for (i = 0; i < N; i++) scanf("%d", &a[i]); /* reads data into a */ for (i = 0; i < N; i++) sum += a[i]; /* sums the elements of a */

Array index out of bounds int a[10], i; for (i = 1; i <= 10; i++) a[i] = 0;

Array subscripts An array subscript may be any integer expression: a[i+j*10] = 0; The expression can even have side effects: i = 0; while (i < N) a[i++] = 0; Wrong i = 0; while (i < N) a[i] = b[i++]; Correct for (i = 0; i < N; i++) a[i] = b[i];

Reversing a series of numbers Enter 10 numbers: In reverse order:

/* Reverses a series of numbers */ #include #define N 100 int main(void) { int a[N], n, i; printf(“Enter number of elements: "); scanf("%d",&n); printf("Enter %d numbers: ", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); printf("In reverse order:"); for (i = n - 1; i >= 0; i--) printf(" %d", a[i]); printf("\n"); return 0; }

Computing the average #include #define N 100 int main(void){ int a[N], n, i, sum; printf("Enter number of elements"); scanf("%d", &n); printf("Enter %d numbers: ", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); sum = 0; for (i = 0; i < n; i++) sum += a[i]; printf("Sum is %d\n", sum); printf("Average is %d\n", sum/n); return 0; }

Array Subscripting Warning: Array bounds are not checked; when a subscript goes out of bounds, the result is unpredictable. One common cause of a subscript out of bounds: forgetting that an array with n elements is indexed from 0 to n–1, not 1 to n. On some systems, the following innocent-looking for statement causes an infinite loop: int a[10], i; for (i = 1; i <= 10; i++) a[i] = 0;

Initializing an Array An array may be initialized at the point of definition. An array initializer is a list of expressions enclosed in braces: int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; If an initializer is too short, the remaining elements of the array are given the value 0: int a[10] = {0}; /* initial value of a is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */ An initializer cannot be empty nor can it be longer than the array it initializes. If an initializer is present, the length of the array may be omitted: int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Program: repeated digits Enter a number: Repeated digit

/* Checks numbers for repeated digits */ #include #define TRUE 1 #define FALSE 0 typedef int Bool; int main(void) { Bool digit_seen[10] = {FALSE}; int digit; long n; printf("Enter a number: "); scanf("%ld", &n); while (n > 0) { digit = n % 10; if (digit_seen[digit]) break; digit_seen[digit] = TRUE; n /= 10; } if (n > 0) printf("Repeated digit\n"); else printf("No repeated digit\n"); return 0; }

The sizeof operator sizeof(a) / sizeof(a[0]) #define SIZE ((int) (sizeof(a) / sizeof(a[0]))) for (i = 0; i < SIZE; i++) a[i] = 0;

Program: computing interest Enter interest rate: 6 Enter number of years: 5 Years 6% 7% 8% 9% 10%

/* Prints a table of compound interest */ #include #define NUM_RATES ((int) (sizeof(value) / sizeof(value[0]))) #define INITIAL_BALANCE int main(void) { int i, low_rate, num_years, year; double value[5]; printf("Enter interest rate: "); scanf("%d", &low_rate); printf("Enter number of years: "); scanf("%d", &num_years);

printf("\nYears"); for (i = 0; i < NUM_RATES; i++) { printf("%6d%", low_rate + i); value[i] = INITIAL_BALANCE; } printf("\n"); for (year = 1; year <= num_years; year++) { printf("%3d ", year); for (i = 0; i < NUM_RATES; i++) { value[i] += (low_rate + i) / * value[i]; printf("%7.2f", value[i]); } printf("\n"); } return 0; }

Multidimensional Arrays Arrays may have more than one dimension: int m[5][9]; m has the following appearance:

Multidimensional arrays C stores arrays in row-major order, with row 0 first, then row 1, and so forth.

Multidimensional Arrays An element of m is accessed by writing m[i][j]. Example of multidimensional array use: #define NUM_ROWS 10 #define NUM_COLS 10 int m[NUM_ROWS][NUM_COLS], row, col; for (row = 0; row < NUM_ROWS; row++) for (col = 0; col < NUM_COLS; col++) if (row == col) m[row][col] = 1; else m[row][col] = 0;

Initializing Multidimensional arrays can be initialized: float matrix[5][3] = {{1.0, 1.0, 1.0}, {2.0, 2.0, 2.0}, {3.0, 3.0, 3.0}, {4.0, 4.0, 4.0}, {5.0, 5.0, 5.0}}; int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 1, 0, 0, 1, 0}}; int m2[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {0, 1, 0, 1, 1, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 1, 1, 1}};

Initializing int m3[5][9] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1};

Program: dealing a hand of cards Enter number of cards in hand: 5 Your hand: 7c 2s 5d as 2h

/* Deals a random hand of cards */ #include /* C99 only */ #include #define NUM_SUITS 4 #define NUM_RANKS 13 int main(void) { bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; int num_cards, rank, suit; const char rank_code[] = {'2','3','4','5','6','7','8', '9','t','j','q','k','a'}; const char suit_code[] = {'c','d','h','s'};

srand((unsigned) time(NULL)); printf("Enter number of cards in hand: "); scanf("%d", &num_cards); printf("Your hand:"); while (num_cards > 0) { suit = rand() % NUM_SUITS; /* picks a random suit */ rank = rand() % NUM_RANKS; /* picks a random rank */ if (!in_hand[suit][rank]) { in_hand[suit][rank] = true; num_cards--; printf(" %c%c", rank_code[rank], suit_code[suit]); } printf("\n"); return 0; }

Constant arrays An array can be made “constant” by starting its declaration with the word const : const char hex_chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F'}; Documents that the program won’t change the array. Helps the compiler catch errors.

Variable-Length Arrays (C99 Only) In C99, the length of an array can be specified by a variable or other expression: int a[2*n+1]; An array declared in this way is said to be a variable-length array. Variable-length arrays are only allowed in functions (including main).

/* Reverses a series of numbers using a variable-length array - C99 only */ #include int main(void) { int i, n; printf("How many numbers do you want to reverse? "); scanf("%d", &n); int a[n]; /* C99 only - length of array depends on n */ printf("Enter %d numbers: ", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); printf("In reverse order:"); for (i = n - 1; i >= 0; i--) printf(" %d", a[i]); printf("\n"); return 0; }