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
Variable Name Examples Valid avg _pi number_of_students inT Invalid int double the end 3rd_entry all$done
Escape codes \n new line \r return \t tab \' single quote \" double quote \\ backslash
Floating Point vs. Integer Division 19/10 --> 1 Remember to truncate after the decimal point for integer division 19.0 / > / 10 --> / > 1.9
Character Data Type char - denotes the character data type and holds one character char a;
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; }
Output A Notice that the ASCII code for 'A' is output ASCII codes can be found on the web
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);
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
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:
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
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
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
Example int intarr[1000]; | | | |... | | Attempting to access data beyond the end of an array will often, but not always, result in a segmentation fault.
Other Examples char carr[4]; double darr[27]; unsigned char ucarr[78]; long larr[12];
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]
More on Arrays darr is the name of the array and represents the address of the first element in the array darr == 200 index |2.3|5.4|0.2|... |7.3| address
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
Another Example int arr[5] = {7, 25, 13, 2, -3}; | 7 | 25| 13| 2 |-13| We can also use the following and get the same effect int arr[] = {7, 25, 13, 2, -3};
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);
ASCII Art of the Previous Example data | 34.0| 27.0| 45.0| 82.0| 22.0| total |210.0| avg | 42.0| Total Avg 42.0
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.
Examples char a = '\0'; //The null character "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.
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'};
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).
scanf Enter your name: Dave name | 'D' | 'a' | 'v' | 'e' | '\0'|
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
Math Functions in C A few other math functions: cos(x)tan(x) sin(x)sqrt(x) d = sqrt( ); //d will contain 10.0
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; }
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.
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);
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
Result Please enter your name: Dave Monismith Dave Monismith <-- has 14 characters name | 'D' | 'a' | 'v' | 'e' | ' ' |...| 't' | 'h' | '\n'| '\0'| Notice that the '\n' character is stored within our string. We need to remove it.
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;
sscanf sscanf is string scanf sscanf(name of string, control string, variables);
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); }
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
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);
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);
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");
Shorthand Operators a = a + 2; is the same as a += 2 Other operators include +=-=*=/=
Pre/Post Operators ++ adds one to a variable/expression (increment) -- subtracts one from a variable or expression (decrement) a++; //Post increment ++a; //Pre increment
Pre Increment Example //Try this a = 1; printf("%d\n", ++a); //Result is the same as a = a + 1; printf("%d\n", a);
Post Increment Example //Try this a = 1; printf("%d\n", a++); //Result is the same as printf("%d\n", a); a = a +1;
Problems with Pre/Post Increment value = 1; //Results from the following assignment //statement are undefined in the //C standard result = (value++ * 5) + (value++ * 3);
Example Answer 1 Evaluation could occur as follows: 1 * 5 = 5 value = 2 2 * 3 = 6 value = 3 result = 11
Example Answer 2 Or: 1 * 3 = 3 value = 2 2 * 5 = 10 value = 3 result = 13
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!
Multi-dimensional Arrays type arrayname[dim1][dim2][dim3]... int arr[2][3]; Example arr[1][0] = 23;