Lecture 20: Arrays Classwork
Wednesday, April 11, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: 8.1 - 8.3 and 9.1
Homework Due: Homework 09
Homework Assigned: Homework 10
Classwork Assigned: Classwork 11
Topics Covered:
- Quiz 3 Results
- Homework 9 questions?
- Homework 10 overview
- Arrays
- Reminder of array syntax
int x[10]; int i; for(i=0; i<10; i++) { x[i] = 100 + i; } for(i=0; i<10; i++) { printf("x[%d] is %d\n", i, x[i]); }
- Reminder about how arrays are stored in memory
- Arrays are stored in sequential memory locations
- You must be sure you don't access array elements outside of the allocated size
- Use conditionals and loops to ensure index is valid
- Reminder of array syntax
- Strings
- An example of a string in C "hello"
- Strings are just an array of characters
- We can create a string by saying:
char c[] = "hello";
- Strings in C always contain one extra character, a character at the end of the string with the value zero called NULL
- The null character can also be written as '\0'
- We can print strings via printf with:
char c[] = "hello"; printf("%s", c);
- This code will print the output "hello"
- We can also get string input from the user with scanf:
char c[20]; scanf("%19s", &c); printf("%s", c);
- Note the value 19 we passed to scanf between % and s, that says that scanf should put at most 19 characters into the string
- The %s specifier to scanf will read all the characters upto the maximum value specified, or the first whitespace character (space, tab, return)