Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 261 C Basics Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variable.

Similar presentations


Presentation on theme: "CS 261 C Basics Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variable."— Presentation transcript:

1

2 CS 261 C Basics

3 Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variable

4 Page 3 1/14/2016 CS 261, WSU Vancouver Primitive Operations

5 Page 4 1/14/2016 CS 261, WSU Vancouver Common Statements Notes: 4 always put in the braces! 4 remember the semicolons! int sum(int a, int b) { return a+b; } abstraction int length(char s[]) { declarations statements } x = x + 3; y = sum(3,5); z = length ("abc"); A[i] = '+'; *p = '+'; assignment & using functions /* a comment */ #include #define MAXSIZE 512 pre-processor stuff this is class standard for formatting if (... ) {... } else if (...) {... } else {... } switch (... ) { case... :... break; case... :... break; default:... } selection * * We don't often use these repetition while (... ) {... } for (i = 0; i < n; ++i) {... } * do {... } while (... )

6 Page 5 1/14/2016 CS 261, WSU Vancouver int isEvenSumSquares(int n) { int sum, i; i = 0; /* i = 0, 1, … */ sum = 0; /* sum = 0*0 + 1*1 + … + (i-1)*(i-1) */ while (i <= n) { sum = sum + i*i; i = i+1; } if (sum % 2 == 0) { return 1; } else { return 0; } Example: Even Sum of Squares Complete the following function declaration so that the code will return the parity of the sum of the squares 1 2 + 2 2 + 3 2 + … + n 2. If the sum is even, return 1; otherwise, return 0. For example, if n = 5, the result is 0 since 1 + 4 + 9 + 16 + 25 = 55 is odd. Notes: clear logic always better clear indentation essential

7 Page 6 1/14/2016 CS 261, WSU Vancouver Example: Sum of Squares For the mathematically inclined, here is a shortcut: int isEvenSumSquares(int n) { if ((n % 4 == 3) || (n % 4 == 0)) { return 1; } else { return 0; } int isEvenSumSquares (int n) { return (n % 4 == 3) || (n % 4 == 0); }

8 Page 7 1/14/2016 CS 261, WSU Vancouver Example: Sum of Squares To use the routine, we could code a main routine: #include int isEvenSumSquares(int n); int main() { int result; result = isEvenSumSquares(20); printf ("result for %d is %d\n", 20, result); return 0; } main.c int isEvenSumSquares(int n) { return (n % 4 == 3) || (n % 4 == 0); } sum.c % gcc -o sum sum.c main.c % sum result for 20 is 1 % what files are created?

9 Page 8 1/14/2016 CS 261, WSU Vancouver Fundamental Principle of Counting In C, we count from zero A is an array with 4 elements: The first element is A[0]: The second element is A[1]: remarks int A[4]; A[0] = 21; A[1] = 6; A[2] = 4; A[3] = 9; example code The last element is A[3]:

10 Page 9 1/14/2016 CS 261, WSU Vancouver int S[4]; int i, n; n = 4; Example: Set to Squares Write a code fragment so that will set each element of the array S[i] to i 2, for i = 0, 1, …, n-1. For example, if n=4, the code would set S[0] to 0, S[1] to 1, S[2] to 4, and S[3] to 9. What goes here?

11 Page 10 1/14/2016 CS 261, WSU Vancouver int S[4]; int i, n; n = 4; i = 0; while (i < n) { S[i] = i*i; ++i; } Example: Set to Squares Write a code fragment so that will set each element of the array S[i] to i 2, for i = 0, 1, …, n-1. For example, if n=4, the code would set S[0] to 0, S[1] to 1, S[2] to 4, and S[3] to 9. Always use the same "while" logic:... create initial state... while (... more work to do... ) {... do some work...... advance the state... }

12 Page 11 1/14/2016 CS 261, WSU Vancouver Fundamental Principle of Arrays Arrays are pointers to the first element A allocates room on the stack and makes A point to first element A stores 21 where A points A+1 stores 6 at next int beyond where A points A+3 A[i] is shorthand for *(A+i) example code remarks int A[4]; *A = 21; *(A+1) = 6; *(A+2) = 4; *(A+3) = 9;

13 Page 12 1/14/2016 CS 261, WSU Vancouver Can Point to Elements More Than Once int A[4]; int B[]; *(A+2) = 4; B = A; *(B+1) = 11; AB ? A B ? A B A B would A = B; be legal?

14 Page 13 1/14/2016 CS 261, WSU Vancouver Strings are arrays of characters where the last character is '\0' Fundamental Principle of Strings core dump! s now has a new value s[0] == example coderemarks char s[]; s = "abc"; s = ""; s = 0; s is an array variable s ? s now has a value "abc" s[0] == 'a' s[2] == 'c' s[3] == '\0' s s now has a new value s s[0] == '\0' ""

15 Page 14 1/14/2016 CS 261, WSU Vancouver int containsSpace(char s[]) { int i = 0; while (s[i] != '\0') { if (s[i] == ' ') return 1; ++i; } return 0; } Example: Contains Space Write a function that tests if a string contains a space (' '). Return 1 if a space appears, 0 otherwise. Correctly handle the case of a null string. Don't use any library routines. Notes: usually prefer only one "return" but, this shortcut logic is an OK idiom

16 Page 15 1/14/2016 CS 261, WSU Vancouver Whiteboard Exercise Write a function that tests if a string contains exactly one '/' int hasOneSlash (char s[]) { }

17 Page 16 1/14/2016 CS 261, WSU Vancouver Whiteboard Exercise Write a function that tests if two strings are exactly the same length int areSameLength(char s[], char t[]) { }

18 Page 17 1/14/2016 CS 261, WSU Vancouver Whiteboard Exercise Write a function that trims all spaces from the beginning of a string char[] leftTrim(char s[]) { }

19 Page 18 1/14/2016 CS 261, WSU Vancouver Example: Length core dump! length("abc") length("012345") length("") length(0) example coderemarks Let's write a function, "length", that returns the length of a string... Note: Library routine "strlen" does this Value is 3 Value is 6 Value is 0 Value is...

20 Page 19 1/14/2016 CS 261, WSU Vancouver First Implementation of Length... Using arrays and subscripts... function definition i == _____ length ("abc") s s[0] == 'a' s[1] == 'b' s[2] == 'c' s[3] == '\0' "abc" int length(char s[]){ int i; i = 0; while (s[i] != '\0') { i = i+1; } return i; }

21 Page 20 1/14/2016 CS 261, WSU Vancouver char a[4]; int n; a[0] = 'e'; n = 4; doIt(a, n); a[0] == ____ n == ______ invocation: Fundamental Principle of Invocation Function parameters are initialized by assignment from invocation arguments parameter1 = argument1, parameter2 = argument2,... Arguments are passed by value void doIt(char b[], int m) { b[0] = 'f'; m = m + 1; b = 0; } example code "call-by-value" b = a; m = n; behind scenes

22 Page 21 1/14/2016 CS 261, WSU Vancouver Fundamental Principle of Arrays, Again Arrays are just pointers to the first element At this point: s[0] == 'a' == *(s+0) s[1] == 'b' == *(s+1) s[2] == 'c' == *(s+2) s[3] == '\0' == *(s+3) At this point:: i == _____ int length(char *s){ int i; i = 0; while (s[i] != '\0') { i = i+1; } return i; } n = length("abc"); example function usage example function definition remarks was: char s[]

23 Page 22 1/14/2016 CS 261, WSU Vancouver Some Versions of Length Using Pointers … int length(char *s) { int i; i = 0; while (s[i] != '\0') { i = i+1; } return i; } v1 int length(char *s) { int i = 0; while (*(s+i) != '\0') { ++i; } return i; } v2 int length(char *s) { int i = 0; while (*s != '\0') { ++s; ++i; } return i; } v3 int length(char *s) { int i = 0; while (*s++ != '\0') { ++i; } return i; } v4

24 Page 23 1/14/2016 CS 261, WSU Vancouver int length(char *s) { int i=0; while (*s++ != '\0') ++i; return i; } final implementation Experienced C programmers can combine C facilities to write compact but still clear code... String Length Again, Tersely... You are getting to right level if this code is clear 4 'char *s' same as 'char s[ ]' 4 initializing declarations 4 ++ operator, both prefix & postfix 4 call-by-value, so changes to parameters don't change arguments 4 testing against '\0' (or 0) can be elided (but, I prefer to leave it explicit) simulate on an example!

25 Page 24 1/14/2016 CS 261, WSU Vancouver Array Declarations in Detail char A[4]; 4 Allocates room for 4 characters and makes A a pointer to the first such character. 4 A is a constant pointer that cannot be modified. 4 A[i] is identical to *(A+i). char *B; or char B[ ]; 4 Allocates no storage; B has no defined value. 4 B is a variable; its values point to a character. 4 B[i] is identical to *(B+i). B = A; 4 Makes B point the same place as A. 4 Thus B[i] are the same storage as A[i] for all i. A = B; 4 illegal; A is a constant (such as 253) A B ? Note: there some subtle differences between char *B and char B[] involving initializing declarations

26 Page 25 1/14/2016 CS 261, WSU Vancouver Let's write a routine, "copy", that copies one string over another Note: Library routine "strcpy" does this Whiteboard Exercise char a[10]; copy(a, "1234"); copy(a+3, "xyz"); example usageremarks Space set aside, but contents not predictable Contents now: a[0] == '1'a[1] == '2'a[2] == '3' a[3] == '4'a[4] == '\0' Contents now: a[0] == '1'a[1] == '2'a[2] == '3' a[3] == 'x'a[4] == 'y'a[5] == 'z' a[6] == '\0'

27 Page 26 1/14/2016 CS 261, WSU Vancouver Solution void copy(char s[], char t[]) { } Want to copy all of t into s, like this: s[0] = t[0]; s[1] = t[1]; s[2] = t[2]; … Copying includes the '\0' at the end of t. We need to examine each char of t in turn. Let i be an index to do this. It will also be the index of next char in s. The logic will be: Set i to 0 (the index of the first char) Repeat: –Set s[i] to t[i]. –If t[i] was '\0', quit this loop. –Otherwise, increment i and continue. Now we know t[i] is the '\0'. So, all of t has been copied. Return. function logicfunction code

28 Page 27 1/14/2016 CS 261, WSU Vancouver Solution void copy (char s[], char t[]) { int i; i = 0; while ( s[i] = t[i], t[i] != '\0' ) { ++i; } return; } Want to copy all of t into s, like this: s[0] = t[0]; s[1] = t[1]; s[2] = t[2]; … Copying includes the '\0' at the end of t. We need to examine each char of t in turn. Let i be an index to do this. It will also be the index of next char in s. The logic will be: Set i to 0 (the index of the first char) Repeat: –Set s[i] to t[i]. –If t[i] was '\0', quit this loop. –Otherwise, increment i and continue. Now we know t[i] is the '\0'. So, all of t has been copied. Return. function logicfunction code Hide this slide

29 Page 28 1/14/2016 CS 261, WSU Vancouver Terse Solution Notes: 4 goal is not to write clever code that may puzzle maintainers 4 but, such pointer manipulation is a common C idiom that must be mastered 4 especially, for system programmers that work with data structures at a relatively low level 4 study up to ensure your comfort with this stuff 4 stylistically, I prefer to make the termination test explicit 4 and, ditto missing statements void copy (char *s, char *t) { while ((*s++ = *t++) != '\0') {} } Hide this slide

30 Page 29 1/14/2016 CS 261, WSU Vancouver Some Useful Names & Functions

31 Page 30 1/14/2016 CS 261, WSU Vancouver Let's write a function, "getline", that reads one line from stdin Note: Library routine "fgets" does this Another Example #define MAXLINE 1000 char buffer[MAXLINE]; while (getline(buffer)) {... do something... } example usageremarks Define a constant Set aside space Process each line

32 Page 31 1/14/2016 CS 261, WSU Vancouver 1. Understand the Problem... State the problem: 4 Read one line from stdin into s 4 A line is terminated by '\n' or EOF (end of file) 4 Fill s with all characters plus '\0'; exclude the '\n' (if any) 4 Don't check if s is big enough 4 Return 1 if a line was read, 0 if EOF detected right away List representative test cases: int getline(char s[]);

33 Page 32 1/14/2016 CS 261, WSU Vancouver 2. Code into C... Write a description or draw a diagram that explains your approach: 4 read chars from stdin using getchar 4 use c to remember the character just read 4 use i to index next place in s to put a character Outline the overall logic: 4 set i to 0 4 repeat: –read one char from stdin into c –if c is EOF, then quit this loop –if c is newline, then quit this loop –store c in s[i] –increment i 4 terminate s properly and return a value: –if c is EOF and i is 0, return 0 –otherwise, set s[i] to '\0' and return 1 Convert the logic into code:

34 Page 33 1/14/2016 CS 261, WSU Vancouver 2. Code into C... Convert the logic into code: int getline(char s[]) { char c; int i = 0; while ( c = getchar (), (c != EOF) && (c != '\n') ) { s[i] = c; ++i; } if ((c == EOF) && (i == 0)) { return 0; } else { s[i] = '\0'; return 1; } Notes: what is EOF? note = vs == note comma operation note parens

35 Page 34 1/14/2016 CS 261, WSU Vancouver 3. Verify the solution... Desk check the code by mentally simulating operation against test cases: 4 file with lines of varying length (0 chars, 1 char, 2 chars, …, 1000 chars) 4 file with varying number of lines (0 lines, 1 line, …) 4 file with last char as '\n' or not Write a test routine, then compile and test: #include extern int getline (char s[]); int main() { char t[500]; while (getline(t)) {... write t plus '\n' to stdout... } return 0; }... body of getline... When is output different from input?


Download ppt "CS 261 C Basics Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variable."

Similar presentations


Ads by Google