Download presentation
Presentation is loading. Please wait.
Published byKathryn Stone Modified over 8 years ago
1
CSCI 130 More on Arrays
2
Multi-dimensional Arrays Multi - Dimensional arrays: –have more than one subscript –can be directly initialized –can be initialized via a for within a for –increase exponentially in complexity with each new dimension –are sometimes called arrays of arrays of...
3
Declaring M-D arrays int x[3][4]; –has 3 rows –has 4 columns –has up to 12 integer elements –first element is x[0][0] –last element is x[2][3]
4
Initializing M-D arrays All values can be directly initialized: –int x[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} –int x[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10,11,12}}; Can be initialized with a for within a for for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) x[i][j] = 0;
5
Order of elements in an array int x[2][3][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} implies the following: x[0][0][0] = 1 x[1][0][0] = 7 x[0][0][1] = 2 x[1][0][1] = 8 x[0][1][0] = 3 x[1][1][0] = 9 x[0][1][1] = 4 x[1][1][1] = 10 x[0][2][0] = 5 x[1][2][0] = 11 x[0][2][1] = 6 x[1][2][1] = 12
6
Strings and Characters Type char can only hold a single character char x = ‘H’; To hold a collection of 5 characters (i.e. a string), we need an array char x[6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’}; String - sequence of characters ending with a null character ( \0 )
7
Initializing Strings char c[6] = {“HELLO”}; char c[] = {“HELLO”}; char c[] = “HELLO”; char x[6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
8
Displaying strings Can use either printf, or puts char x[] = {“HELLO”}; printf(“%s”, x); puts(x);
9
Receiving strings as input Can either use scanf, or gets scanf only scans up to the first occurrence of whitespace (return key or a space) char x[10]; scanf(“%s”, x); // Notice no & is necessary gets retrieves everything up to the return key char x[10]; gets(x);
10
String functions Copying strcpy(dest, source) Concatenation –to append y onto the end of x: strcat(x, y) Comparing –strcmp(x, y) returns a value < 0 if x < y returns a value > 0 if x > y returns a value = 0 if x = y
11
More on string functions Chapter 17 CIS 131 CIS 221
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.