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

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

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

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

C Programming Day 2based upon Practical C Programming by Steve

Oualline

CS550Operating Systems

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

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

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

Variable Name Examples

Valid

avg_pinumber_of_studentsinT

Invalid

intdoublethe end3rd_entryall$done

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

Escape codes

• \n new line• \r return• \t tab• \' single quote• \" double quote• \\ backslash

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

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

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

Character Data Type

• char - denotes the character data type and holds one character

char a;

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

Example Code#include <stdio.h>

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

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

Output

A651000

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

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

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 205printf("a is %d\n", a);printf("The address of a is %u\n", &a);

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

Running the program

gcc addrEx.c –o addrEx.exeor with the Intel compilericc addrEx.c –o addrEx.exe

Output:• Please enter an integer: 5• a is 5• The address of a is 205

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

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 155 10 15

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

Field Width Specifiersprintf("%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

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

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

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

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

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

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.

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

Other Examples

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

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

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]

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

More on Arrays

• darr is the name of the array and represents the address of the first element in the array

darr == 200index 0 1 2 26 +---+---+---+--------------------+---+ |2.3|5.4|0.2| . . . |7.3| +---+---+---+--------------------+---+ 200 208 216 408address

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

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

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

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

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

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

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

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.0Avg 42.0

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

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.

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

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

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

String Exampleschar 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'};

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

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

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

scanf

Enter your name: Dave

0 1 2 3 4 +-----+-----+-----+-----+-----+---------name | 'D' | 'a' | 'v' | 'e' | '\0'| . . . +-----+-----+-----+-----+-----+---------

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

Math Functions in C

#include <math.h> //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

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

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

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

Example#include <stdio.h>#include <math.h>

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

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

Problems with strings and scanf

char line[100];scanf("%s", line); //line is the addressprintf("%s\n", line);

• Assume an input of:Hello there

• The output will be:Hello

• Why? scanf counts white space as a delimiter.

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

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

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

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

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

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.

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

String Functions• Use #include <string.h>

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;

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

sscanf

• sscanf is string scanf

• sscanf(name of string, control string, variables);

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

Example#include <stdio.h>#include <string.h>

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

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

String Functions• To use string functions, #include <string.h>• 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

anotherstrcpy(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 Javaname1 = name1 + name2; //Don't do this in C

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

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

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

Example

//Remove newline charactersfirst[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);

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

String Comparison

strcmp(str1, str2)

• result is zero if two strings are lexicographically equivalentA --> 65a --> 97

• Try the following:strcmp("a", "a");strcmp("A", "a");strcmp("a", "A");

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

Shorthand Operators

a = a + 2;

• is the same as

a += 2

• Other operators include

+= -= *= /=

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

Pre/Post Operators

• ++ adds one to a variable/expression (increment)

• -- subtracts one from a variable or expression (decrement)

a++; //Post increment++a; //Pre increment

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

Pre Increment Example

//Try thisa = 1;printf("%d\n", ++a);

//Result is the same asa = a + 1;printf("%d\n", a);

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

Post Increment Example

//Try thisa = 1;printf("%d\n", a++);

//Result is the same asprintf("%d\n", a);a = a +1;

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

Problems with Pre/Post Increment

value = 1;

//Results from the following assignment//statement are undefined in the//C standard

result = (value++ * 5) + (value++ * 3);

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

Example Answer 1

• Evaluation could occur as follows:

1 * 5 = 5

value = 2

2 * 3 = 6

value = 3

result = 11

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

Example Answer 2

• Or:

1 * 3 = 3

value = 2

2 * 5 = 10

value = 3

result = 13

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

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!

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

Multi-dimensional Arrays

type arrayname[dim1][dim2][dim3]...

int arr[2][3];

• Example

arr[1][0] = 23;