notes5

H int main int k 10 32 28 12 39 57 63 15

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: m[i] 1 6 11 16 21 26 31 36 41 46 Arrays Example #2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* initializing an array with an initializer list */ #include <stdio.h> int main() { int k[ 10 ] = { 32, 28, 12, 39, 57, 63, 15, }; int i; /* counter */ printf( "\n%3s%11s\n", "i", "k[i]" ); for( i = 0 ; i <= 9 ; i++ ) { printf( "%3d%11d\n", i, k[i] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ Arrays Example #2 - Output % a.out i 0 1 2 3 4 5 6 7 8 9 % k[i] 32 28 12 39 57 63 15 0 0 0 Arrays Example #3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* scanning an array of integers */ #include <stdio.h> int main() { int k[ 5 ]; int i; /* counter */ printf( "\n Enter 5 integers: " ); for( i = 0; i <= 4; i++ ) { scanf( "%d", &k[i] ); } printf( "\n%3s%11s\n", "i", "k[i]" ); for( i = 0 ; i <= 4 ; i++ ) { printf( "%3d%11d\n", i, k[i] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ Arrays Example #3 - Output % a.out Enter 5 integers: 5 6 7 1 2 i 0 1 2 3 4 % k[i] 5 6 7 1 2 Character Arrays • Character arrays – – String “flop” is really an array of characters Character arrays can be initialized using string literals • char string1 = “flop”; • Null character ‘\0’ terminates strings • string1 actually has 5 elements char string1 = { ‘f’, ‘l’, ‘o’, ‘p’, ‘\0’ }; – – Can access individual characters • string1[2] is character ‘o’ When scanning a character array using scanf, & is not needed • scanf( “%s”, string2 ); • Program keeps scanning until whitespace is encountered Character Arrays: Example 1 2 3 4 5 6 7 8 9 10 11 12 13 /* treating character arrays as strings */ #include <stdio.h> int main() { char str1[ 20 ]; /* reserves 20 characters */ char str2 = "Hello there"; /* reserves 12 characters */ int i; /* counter */ /* read str1 in from user */ printf( "\nEnter a string: " ); scanf( "%s&quot...
View Full Document

Ask a homework question - tutors are online