Sei sulla pagina 1di 12

Programming-1 Tutorial

Arrays
1. What is Arrays? - Individual variables are classified as scalars. - A scalar can assume exactly one value at a time. - A scalar cannot represent a collection of data elements. Arrays are data structures consisting of related data items of the same type. Arrays and structures are static entities in that they remain the same size throughout program execution. An array is a group of memory locations related by the fact that they all have the same name and the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. An array is a non-scalar reference variable

Like any other variable, an array can be local, static, or instance variable. must be declared before it is used. Given Array c, any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([]). The first element in every array is the zeroth element (c[0]). ith element is c[i-1]. Position number is called subscript or index. Subscript should be integer. In the following figure: c[0] = -45, c[11] (last element) = 78. printf( "%d", c[ 0 ] + c[ 1 ] + c[ 2 ] ); will print -39 We can consider each element in an integer array as a normal integer that can be added to another value, subtracted, multiplied or divided. e.g. x = c[7]/2

2. How to define an array? - You specify the type of each element and the number of elements required by each array so that the computer may reserve the appropriate amount of memory. int c[12] OR int b[100], x[150]; - Arrays can be from any data type (char, float,..).

You can declare an array as follows:


<data_type> array_name[size of the array];

int c[12];
int c[ 12 ]; reserve 12 elements for integer array c

3. Examples: 3.1. Defining an Array and Using a Loop to Initialize the Arrays Elements: #include <stdio.h> #include <stdlib.h> int main() { int n[10] ; int i; for (i = 0; i < 10; i++){ n[i] = 0 ;

} printf ("%s%13s\n", "Element", "Value"); for (i = 0; i < 10; i++){ printf("%7d%13d\n", i, n[i]) ; } return 0; }

3.2.

Initializing an Array in a Definition with an Initializer List:

#include <stdio.h> #include <stdlib.h> int main() { int i ; int n[10] = {32, 27, 15, 10, 0, 2, 4, 5, 6, 16} ; printf ("%s%13s\n", "Element", "Value"); for (i = 0; i < 10; i++){ printf("%7d%13d\n", i, n[i]) ; } return 0; }

Notes about initialization:


Example:if you have array n of size 10 and you want to initialize the first three elements to 1s and the other elements to 0s int n[ 10 ]={1, 1, 1, 0, 0, 0, 0, 0, 0, 0 } also you can make it int n[ 10 ]={1, 1, 1 } Example:the elements of the array n could have been initialized to zero as follows: int n[ 10 ] = { 0 }; The array definition int n[ 5 ] = { 32, 27, 64, 18, 95, 14 }; causes a syntax error because there are six initializers and only five array elements.
3.3. Specifying an Arrays Size with a Symbolic Constant and Initializing Array Elements with Calculations: #include <stdio.h> #include <stdlib.h> #define SIZE 10 int main() { int s[SIZE]; int j ; for ( j = 0; j < SIZE; j++ ) { s[ j ] = 2 + 2 * j; } printf ("%s%13s\n", "Element", "Value"); for ( j = 0; j < SIZE; j++ ) { printf( "%7d%13d\n", j, s[ j ] ); } return 0; }

The #define preprocessor directive is introduced in this program. we could have the first for loop fill a 1000-element array by simply changing the value of SIZE in the #define directive from 10 to 1000. If the symbolic constant SIZE had not been used, wed have to change the program in three separate places to scale the program to handle 1000 array elements. If the #define preprocessor directive in line 4 is terminated with a semicolon, all occurrences of the symbolic constant SIZE in the program are replaced with the text 10; by the preprocessor.
3.4. Summing the Elements of an Array:

#include <stdio.h> #include <stdlib.h> #define SIZE 10 int main() { int a[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int i, total = 0; for (i = 0; i < SIZE; i++){ total += a[i] ; } printf ("Total is %d\n", total); return 0; }

3.5.

Using Arrays to Summarize Survey Results:

#include <stdio.h> #include <stdlib.h> #define RESPONSE_SIZE 40 #define FREQUENCY_SIZE 11 int main() { int answer, rating,i ; int frequency[FREQUENCY_SIZE]; for (i = 0; i < FREQUENCY_SIZE; i++) frequency[i] = 0 ; int responses[RESPONSE_SIZE] = {1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10};

for (answer = 0; answer < RESPONSE_SIZE; answer++){ ++frequency[responses[answer]]; } printf ("%s%17s\n", "Rating", "Frequency"); for (rating = 1; rating < FREQUENCY_SIZE; rating++){ printf("%6d%17d\n", rating, frequency[rating]); } return 0; }

3.6.

Graphing Array Element Values with Histograms:

#include <stdio.h> #include <stdlib.h> #define SIZE 10 int main() { int n[SIZE] = {1, 2, 3, 4, 5, 4, 3, 2, 1, 0}; int i, j ; printf ("%s%13s%17s\n", "Element", "Value", "Histogram"); for (i = 0; i < SIZE; i++){ printf("%7d%13d ", i, n[i]); for (j = 1; j <= n[i]; j++){ printf("%c", '*'); } printf("\n"); } return 0; }

3.7.

Rolling a Die 6000 Times and Summarizing the Results in an Array:

#include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 7 int main() { int face, roll ; int frequency[SIZE] = {0}; srand(time(NULL)); for (roll = 1; roll <= 6000; roll++){ face = 1 + rand()%6 ; ++frequency[face] ; } printf("%s%17s\n", "Face", "Frequency"); for (face = 1; face < SIZE; face++){ printf("%4d%17d\n", face, frequency[face]); } return 0; }

3.8.

Static Local Arrays and Automatic Local Arrays:

#include <stdio.h> #include <stdlib.h> void staticArrayInit( void ); void automaticArrayInit( void ); int main() { printf ("First call to each function \n"); staticArrayInit(); automaticArrayInit(); printf ("Second call to each function \n"); staticArrayInit(); automaticArrayInit(); return 0; } staticArrayInit(){ static int array1[3]; int i; printf( "\nValues on entering staticArrayInit:\n" ); for ( i = 0; i <= 2; i++ ) { printf( "array1[ %d ] = %d ", i, array1[ i ] ); } printf( "\nValues on exiting staticArrayInit:\n" ); for ( i = 0; i <= 2; i++ ) { printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 ); } } void automaticArrayInit( void ) { int array2[ 3 ] = { 1, 2, 3 }; int i; printf( "\n\nValues on entering automaticArrayInit:\n" ); for ( i = 0; i <= 2; i++ ) { printf("array2[ %d ] = %d ", i, array2[ i ] ); } printf( "\nValues on exiting automaticArrayInit:\n" ); for ( i = 0; i <= 2; i++ ) { printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 ); } }

4. Character Arrays as strings: Arrays are capable of holding data of any type. The only string-processing capability we have is outputting a string with printf. A string such as "hello" is really a static array of individual characters in C. Character arrays have several unique features. A character array can be initialized using a string literal. E.g.: char string1[] = first; The size of array string1 is determined by the compiler based on the length of the string. The string "first" contains five characters plus a special string-termination character called the null character. Thus, array string1 actually contains six elements. The character constant representing the null character is '\0'. All strings in C end with this character. Character arrays also can be initialized with individual character constants in an initialize list. The preceding definition is equivalent to char string1[] = {f, i, r, s, t, \0}; Because a string is really an array of characters, we can access individual characters in a string directly using array subscript notation. For example, string1[0] is the character 'f' and string1[3] is the character 's'. We also can input a string directly into a character array from the keyboard using scanf and the conversion specifier %s. For example, char string2[20]; scanf (%s, string2); The above statements create a character array capable of storing a string of at most 19 characters and a terminating null character. scanf reads a string from the keyboard into string2. The name of the array is passed to scanf without the preceding & used with nonstring variables. The & is normally used to provide scanf with a variables location in memory so that a value can be stored there. The

value of an array name is the address of the start of the array; therefore, the & is not necessary. Function scanf will read characters until a space, tab, newline or end-of-file indicator is encountered. The string should be no longer than 19 characters to leave room for the terminating null character. If the user types 20 or more characters, your program may crash! For this reason, use the conversion specifier %19s so that scanf does not write characters into memory beyond the end of the array s. A character array representing a string can be output with printf and the %s conversion specifier. The characters of the string are printed until a terminating null character is encountered. #include <stdio.h> #include <stdlib.h> int main() { char string1[20]; char string2[] = "string literal"; int i; printf("Enter string:"); scanf("%s", string1); printf ("String1 is %s\nString2 is %s\nString1 with spaces between characters is:\n", string1, string2); for (i = 0; string1[i] != '\0'; i++){ printf("%c ", string1[i]); } printf("\n"); return 0; }

We have a problem that scanf (%s, string) splits the input the string according to space, new line. So in the above example it takes only the first word hello and ignores the second one world. You can avoid this problem by reading the string character by character until a special character is detected.

Example: Read the characters until getting New Line (pressing enter). Using getchar() #include <stdio.h> #include <stdlib.h> #define SIZE 100 int main() { char string[SIZE]; int i=0; char c; printf("Enter String:\n"); while ( ( c = getchar() ) != '\n' && i < SIZE ) { string[ i++ ] = c; } string[ i ] = '\0'; /* terminate string */ printf ("%s", string); return 0; }

Using scanf: #include <stdio.h> #include <stdlib.h> #define SIZE 100 int main() { char string[SIZE]; int i=0; char c; printf("Enter String:\n");

scanf("%c", &c); while ( c != '\n' && i < SIZE ) { string[ i++ ] = c; scanf("%c", &c); } string[ i ] = '\0'; /* terminate string */ printf ("%s", string); return 0; }

Potrebbero piacerti anche