cs 261 c basics page 2 1/14/2016 cs 261, wsu vancouver primitive types notes: 4 a is a constant; b...
DESCRIPTION
Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variableTRANSCRIPT
Page 4 05/03/23 CS 261, WSU Vancouver
Common Statements
Notes: always put in the braces! remember the semicolons!
int sum(int a, int b) {return a+b;
}
abstraction
int length(char s[]) {declarationsstatements
}
x = x + 3;y = sum(3,5);z = length ("abc");A[i] = '+';*p = '+';
assignment & using functions
/* a comment */#include <stdio.h>#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 ( ... )
Page 5 05/03/23 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 12 + 22 + 32 + … + n2. 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
Page 6 05/03/23 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);
}
Page 7 05/03/23 CS 261, WSU Vancouver
Example: Sum of Squares To use the routine, we could code a main routine:
#include <stdio.h>
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% sumresult for 20 is 1%
what files are created?
Page 8 05/03/23 CS 261, WSU Vancouver
Fundamental Principle of Counting
In C, we count from zero
A is an array with4 elements:
The first elementis A[0]:
The second elementis A[1]:
remarks
int A[4];
A[0] = 21;
A[1] = 6;
A[2] = 4;
A[3] = 9;
example code
The last elementis A[3]:
Page 9 05/03/23 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 i2, 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?
Page 11 05/03/23 CS 261, WSU Vancouver
Fundamental Principle of Arrays
Arrays are pointers to the first element
Aallocates room onthe stack and makesA point to first element
Astores 21 where Apoints
A+1stores 6 at next intbeyond where A points
A+3A[i] is shorthand for*(A+i)
example code remarks
int A[4];
*A = 21;
*(A+1) = 6;
*(A+2) = 4;
*(A+3) = 9;
Page 12 05/03/23 CS 261, WSU Vancouver
Can Point to Elements More Than Once
int A[4];int B[];
*(A+2) = 4;
B = A;
*(B+1) = 11;
A B
?
A B
?
A B
A B
wouldA = B;be legal?
Page 13 05/03/23 CS 261, WSU Vancouver
Strings are arrays of characters where the last character is '\0'
Fundamental Principle of Strings
core dump!s now has anew value s[0] ==
example code remarks
char s[];
s = "abc";
s = "";
s = 0;
s is an arrayvariable s
?
s now has avalue "abc" s[0] == 'a'
s[2] == 'c's[3] == '\0's
s now has anew value s
s[0] == '\0'""
Page 14 05/03/23 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
Page 15 05/03/23 CS 261, WSU Vancouver
Whiteboard Exercise Write a function that tests if a string contains
exactly one '/'
int hasOneSlash (char s[]) {
}
Page 16 05/03/23 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[]) {
}
Page 17 05/03/23 CS 261, WSU Vancouver
Whiteboard Exercise Write a function that trims all spaces from the
beginning of a string
char[] leftTrim(char s[]) {
}
Page 18 05/03/23 CS 261, WSU Vancouver
Example: Length
core dump!
length("abc")
length("012345")
length("")
length(0)
example code remarks
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 ...
Page 19 05/03/23 CS 261, WSU Vancouver
First Implementation of Length ...Using arrays and subscripts ...
function definition
i == _____
length ("abc")
ss[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;}
Page 20 05/03/23 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 argumentsparameter1 = 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
Page 21 05/03/23 CS 261, WSU Vancouver
Fundamental Principle of Arrays, AgainArrays 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 usageexample function definition
remarkswas:
char s[]
Page 22 05/03/23 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;
}
v1int 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
Page 23 05/03/23 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 writecompact but still clear code ...
String Length Again, Tersely ...
You are getting to right level if this code is clear 'char *s' same as 'char s[ ]' initializing declarations ++ operator, both prefix &
postfix call-by-value, so changes to
parameters don't change arguments
testing against '\0' (or 0) can be elided (but, I prefer to leave it explicit)
simulate on an example!
Page 24 05/03/23 CS 261, WSU Vancouver
Array Declarations in Detail char A[4];
Allocates room for 4 characters and makes A a pointer to the first such character. A is a constant pointer that cannot be modified. A[i] is identical to *(A+i).
char *B; or char B[ ]; Allocates no storage; B has no defined value. B is a variable; its values point to a character. B[i] is identical to *(B+i).
B = A; Makes B point the same place as A. Thus B[i] are the same storage as A[i] for all i.
A = B; illegal; A is a constant (such as 253)
A
B ?
Note: there some subtle differences between char *B and char B[] involving initializing declarations
Page 25 05/03/23 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 usage remarks
Space set aside, but contents notpredictable
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'
Page 26 05/03/23 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 logic function code
Page 30 05/03/23 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 usage remarks
Define a constant
Set aside space
Process each line
Page 31 05/03/23 CS 261, WSU Vancouver
1. Understand the Problem ... State the problem:
Read one line from stdin into s A line is terminated by '\n' or EOF (end of file) Fill s with all characters plus '\0'; exclude the '\n' (if any) Don't check if s is big enough Return 1 if a line was read, 0 if EOF detected right away
List representative test cases:
int getline(char s[]);
Page 32 05/03/23 CS 261, WSU Vancouver
2. Code into C ... Write a description or draw a diagram that explains your approach:
read chars from stdin using getchar use c to remember the character just read use i to index next place in s to put a character
Outline the overall logic: set i to 0 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
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:
Page 33 05/03/23 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
Page 34 05/03/23 CS 261, WSU Vancouver
3. Verify the solution ... Desk check the code by mentally simulating operation against test cases:
file with lines of varying length (0 chars, 1 char, 2 chars, …, 1000 chars)
file with varying number of lines (0 lines, 1 line, …)
file with last char as '\n' or not
Write a test routine, then compile and test:
#include <stdio.h>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 outputdifferent from input?