Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Similar presentations


Presentation on theme: "C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems."— Presentation transcript:

1 C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems

2 Variable Names Variable names must start with a letter or an underscore No special characters may be used in variable names Letters, digits, or underscores may follow the first character in the variable name

3 Variable Name Examples Valid avg _pi number_of_students inT Invalid int double the end 3rd_entry all$done

4 Escape codes \n new line \r return \t tab \' single quote \" double quote \\ backslash

5 Floating Point vs. Integer Division 19/10 --> 1 Remember to truncate after the decimal point for integer division 19.0 / 10.0 --> 1.9 19.0 / 10 --> 1.9 19 / 10.0 --> 1.9

6 Character Data Type char - denotes the character data type and holds one character char a;

7 Example Code #include int main(int argc, char ** argv) { char c; //Declaration c = 'A'; //Initialization printf("%c\n", c); //print contents of c printf("%d\n", c); //print c as an int printf(”%u\n", &c); //print the address of c //Assume the address is 1000 return 0; }

8 Output A 65 1000 Notice that the ASCII code for 'A' is output ASCII codes can be found on the web http://www.asciitable.com/

9 Reading Data with scanf Pretend a has an address of 205 &a is 205 in C because the ampersand means “address of” int a; printf("Please enter an integer: "); scanf("%d", &a); //Read data into //memory location 205 printf("a is %d\n", a); printf("The address of a is %u\n", &a);

10 Running the program gcc addrEx.c –o addrEx.exe or with the Intel compiler icc addrEx.c –o addrEx.exe Output: Please enter an integer: 5 a is 5 The address of a is 205

11 Multiple inputs with scanf int a, b, c; printf("Enter 3 ints on one line: "); scanf("%d %d %d", &a, &b, &c); printf("%d %d %d", a, b, c); Enter 3 ints on one line: 5 10 15 5 10 15

12 Field Width Specifiers printf("%c%4c%6c\n", ‘C', 'B', ‘A'); //Use 4 spaces for the 2nd character and 6 for the 3rd character C___B_____A printf(”%2d", 3000); 3000 printf("%5.2lf\n", 6.537); __6.54

13 Common number of bytes used on 64- bit machines char --> 1 byte float --> 4 bytes double --> 8 bytes long double --> 16 bytes int --> 4 bytes long --> 8 bytes Try the following: printf("%u\n", sizeof(char)); Note that %u represents an unsigned int

14 Arrays An array is a sequence of data items that are of the same type and are stored contiguously in memory. Elements of an array are accessed using square brackets []. Arrays in C are indexed from zero. type name[size]; //Array declaration //note that the size cannot be changed

15 Example int intarr[1000]; 0 1 2 999 +---+---+---+--------------------+---+ | | | |... | | +---+---+---+--------------------+---+ Attempting to access data beyond the end of an array will often, but not always, result in a segmentation fault.

16 Other Examples char carr[4]; double darr[27]; unsigned char ucarr[78]; long larr[12];

17 More on Arrays An array's size cannot be changed. double darr[27]; We use a subscript or index to access an element of an array. darr[0] darr[19]

18 More on Arrays darr is the name of the array and represents the address of the first element in the array darr == 200 index 0 1 2 26 +---+---+---+--------------------+---+ |2.3|5.4|0.2|... |7.3| +---+---+---+--------------------+---+ 200 208 216 408 address

19 Addressing Arrays Notice the address changes by 8 because double values take up 8 bytes. Example darr[20] darr + index*sizeof(double) darr is the starting point in memory. The rest is the offset from the starting point Notice that darr is actually an unsigned integer

20 Another Example int arr[5] = {7, 25, 13, 2, -3}; 0 1 2 3 4 +---+---+---+---+---+ | 7 | 25| 13| 2 |-13| +---+---+---+---+---+ We can also use the following and get the same effect int arr[] = {7, 25, 13, 2, -3};

21 Yet Another Example double data[5] = { 34.0, 27.0, 45.0, 82.0, 22.0 }; double total, avg; total = data[0] + data[1] + data[2] + data[3] + data[4]; avg = total / 5.0; printf("Total %lf\nAvg %lf\n", total, avg);

22 ASCII Art of the Previous Example 0 1 2 3 4 +-----+-----+-----+-----+-----+ data | 34.0| 27.0| 45.0| 82.0| 22.0| +-----+-----+-----+-----+-----+ +-----+ total |210.0| +-----+ avg | 42.0| +-----+ Total 210.0 Avg 42.0

23 Strings In C, a string is a one-dimensional array of characters (type char ). Strings always end with a special character -- the NULL character The NULL character is all caps in C The character '\0', the integer 0, and NULL all represent the same null value in C.

24 Examples char a = '\0'; //The null character 0 1 2 3 +-----+-----+-----+-----+ "abc" | 'a' | 'b' | 'c' | '\0'| +-----+-----+-----+-----+ The length of this string is 3. The size of this array is 4. When declaring an array that will contain a string, be sure to leave one extra character of space for the null character.

25 String Examples char name[100]; name[0] = 'H'; name[1] = 'e'; name[2] = 'l'; name[3] = 'l'; name[4] = 'o'; name[5] = '\0'; printf("%s\n", name); char name[] = "Hello"; char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};

26 scanf You can use scanf to read in a string. char name[100]; printf("Enter your name: "); scanf("%s", name); //Recall that name is the //address of the beginning //of the array (string).

27 scanf Enter your name: Dave 0 1 2 3 4 +-----+-----+-----+-----+-----+--------- name | 'D' | 'a' | 'v' | 'e' | '\0'|... +-----+-----+-----+-----+-----+---------

28 Math Functions in C #include //to use math functions x^y is pow(x,y) pow(2,2) --> 2^2 = 4 double d; d = pow(2,3); d now contains 8.0

29 Math Functions in C A few other math functions: cos(x)tan(x) sin(x)sqrt(x) d = sqrt(50 + 50); //d will contain 10.0

30 Example #include int main() { double a,b,c; a = 3; b = 4; //compute the square root of a^2 + b^2 c = sqrt(pow(a,2) + pow(b,2)); printf("%lf is a, %lf is b, and %lf is c\n", a, b, c); printf("%lf is a, %lf is b, and %lf is c\n", a, b, sqrt(a*a + b*b) ); return 0; }

31 Problems with strings and scanf char line[100]; scanf("%s", line); //line is the address printf("%s\n", line); Assume an input of: Hello there The output will be: Hello Why? scanf counts white space as a delimiter.

32 fgets fgets reads an entire line. Similar to Scanner.readLine() Be sure to leave lots of space in your arrays when using fgets. Function call: fgets(name of string, size of string in bytes, where the input is coming from);

33 Example of fgets char name[50]; printf("Please enter your name: "); fgets(name, sizeof(name), stdin); //sizeof(name) returns the number // of bytes in the array name. //stdin is standard input. That // means we read from the console

34 Result Please enter your name: Dave Monismith Dave Monismith <-- has 14 characters name 0 1 2 3 4 12 13 14 15 +-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-------- | 'D' | 'a' | 'v' | 'e' | ' ' |...| 't' | 'h' | '\n'| '\0'|... +-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-------- Notice that the '\n' character is stored within our string. We need to remove it.

35 String Functions Use #include strlen(name of string) Provides the length of the string and excludes null character. strlen(name) is 15 We can remove the return character from name as follows: name[strlen(name) - 1] = 0;

36 sscanf sscanf is string scanf sscanf(name of string, control string, variables);

37 Example #include int main(int argc, char ** argv){ int a, b; char line[100]; fgets(line,sizeof(line), stdin); sscanf(line, "%d %d", &a, &b); printf("%d %d\n", a, b); }

38 String Functions To use string functions, #include Sometimes compilers will let you get away without it. strlen - # of characters in a string strcpy - allows you to copy the contents of one string into another strcpy(destination, source); strcat - allows you to concatenate (add to) a string to the end of another string strcat(destination, source); Do NOT use the + operator as you would in Java name1 = name1 + name2; //Don't do this in C

39 Example char first[100]; char last[100]; char full_name[200]; printf("%s%s","Please enter your ", "first name: "); fgets(first, sizeof(first), stdin); fgets(last, sizeof(last), stdin);

40 Example //Remove newline characters first[strlen(first) - 1] = '\0'; last[strlen(first) - 1] = '\0'; strcpy(full_name, first); strcat(full_name, " "); strcat(full_name, last); printf("%s\n", full_name);

41 String Comparison strcmp(str1, str2) result is zero if two strings are lexicographically equivalent A --> 65 a --> 97 Try the following: strcmp("a", "a"); strcmp("A", "a"); strcmp("a", "A");

42 Shorthand Operators a = a + 2; is the same as a += 2 Other operators include +=-=*=/=

43 Pre/Post Operators ++ adds one to a variable/expression (increment) -- subtracts one from a variable or expression (decrement) a++; //Post increment ++a; //Pre increment

44 Pre Increment Example //Try this a = 1; printf("%d\n", ++a); //Result is the same as a = a + 1; printf("%d\n", a);

45 Post Increment Example //Try this a = 1; printf("%d\n", a++); //Result is the same as printf("%d\n", a); a = a +1;

46 Problems with Pre/Post Increment value = 1; //Results from the following assignment //statement are undefined in the //C standard result = (value++ * 5) + (value++ * 3);

47 Example Answer 1 Evaluation could occur as follows: 1 * 5 = 5 value = 2 2 * 3 = 6 value = 3 result = 11

48 Example Answer 2 Or: 1 * 3 = 3 value = 2 2 * 5 = 10 value = 3 result = 13

49 Assignment Operator Don't play around with the assignment operator either a = (b = 2) + (c = 3); //is a valid C statement //Don't do this!

50 Multi-dimensional Arrays type arrayname[dim1][dim2][dim3]... int arr[2][3]; Example arr[1][0] = 23;


Download ppt "C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems."

Similar presentations


Ads by Google