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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Lectures 10 & 11.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10 Introduction to Arrays
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Engineering Computing I Chapter 1 – Part B A Tutorial Introduction continued.
Chapter 10.
1 Homework Assignments Turn in HW1 (If not done yet, catch up!) Questions about HW1? Anyone still stuck on apply / UNIX account? Everyone have the books?
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Guide To UNIX Using Linux Third Edition
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
C-strings Array with base type char One character per indexed variable
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
Array with base type char One character per indexed variable One extra character: '\0' Called ‘null character’ Delimiter of the string To declare a string,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
A First Book of ANSI C Fourth Edition Chapter 9 Character Strings.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Chapter Nine Strings. Char vs String Literals Size of data types: Size of data types: –sizeof(“hello\n”)7 bytes –sizeof(“hello”)6 bytes –sizeof(“X”)2.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
User-Written Functions
UMBC CMSC 104 – Section 01, Fall 2016
Quiz 11/15/16 – C functions, arrays and strings
Your questions from last session
COP 3330 Object-oriented Programming in C++
Suggested self-checks: Section 7.11 #1-11
Presentation transcript:

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

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

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 (... )

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 … + n 2. If the sum is even, return 1; otherwise, return 0. For example, if n = 5, the result is 0 since = 55 is odd. Notes: clear logic always better clear indentation essential

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); }

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?

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]:

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?

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... }

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;

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?

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' ""

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

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[]) { }

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[]) { }

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[]) { }

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...

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; }

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

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[]

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

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!

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

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'

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

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

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

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

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

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[]);

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:

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

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?