470 likes | 488 Views
Introduction to Computer Organization & Systems. COMP 21000. Topics: Intro to C Types in C: int and floating point C I/O C file I/O. C Part II. The function of a compiler. The compiler as a program. The machine independence of a Level HOL6 language. C Programming & Systems Programming.
E N D
Introduction to Computer Organization & Systems COMP 21000 Topics: • Intro to C • Types in C: int and floating point • C I/O • C file I/O C Part II
C Programming & Systems Programming • Specific type of programming • Not used in the development of most applications • Emphasis is on conciseness and efficiency (space and time) • Ignores readability and maintainability • You will get fired if you program like this in most situations!
The three attributes of a C++/C variable • A name • A type • A value
Note the & Global variables are possible, but not in this class! A C++ program that processes three integer values C++ program C program #include <stdio.h> #define bonus 5 int exam1, exam2, score; main( ){ scanf(“%d %d”, &exam1, &exam2); score = (exam1 + exam2)/2 + bonus; printf(“score = %d\n”, score); }
Output: printf printf(“score = %d\n”,score);
Input: scanf scanf(“%d %d”,&exam1, &exam2); scanf(“ %d %d”,&exam1, &exam2); note that you can put a space before a ‘%’ character. This will cause scanf to skip a whitespace character (like a newline or ‘\n’ character) when it reads input. Do not put a space after the last %d. This will insert a newline character into the input stream and will cause problems!
What if you replace %c with %d? A program to process a character variable #include <stdio.h> main (){ char ch; scanf(“%c”,&ch); printf(“Original character: %c\n”, ch); ch++; printf(“Following character: %c\n”, ch); }
ASCII These assignments also work in UNICODE!
The ASCII code for a “s” A program to process a character variable (Cont’d) Using %c Using %d bash-2.03$ a.out s Original character: 115 Following character: 116
Arrays* No magic numbers in your code! Use defined constants. #include <stdio.h> #include <stdlib.h> #define SIZE 10 int main() { int arr[SIZE]; int i; int realSize; // read in number of numbers to use printf("enter the number of numbers \n"); scanf("%d", &realSize); for (i = 0; i < realSize; i++) { printf("enter the %dth value: ", i); scanf("%d", &arr[i]); } You do have to specify the size of an array that is a variable (unless you want to use dynamic memory) Must use the & because we’re reading into a specific array element continued on next slide * This example is on the server at /home/barr/Student/examples/readArr.c
Arrays* for (i = 0; i < realSize; i++) { printf("arr[%d] = %d ", i, arr[i]); if (i % 5 == 0) printf("\n"); } printf("\n"); return 0; } put 5 elements on a line * This example is on the server at /home/barr/Student/Examples/array.c
functions #include <stdio.h> int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); } * This example is on the server at /home/barr/Student/Examples/factorial.c
functions main() { int n, i = 0, x; printf("Please enter value of n = "); /* Note the & before the variable n */ scanf("%d", &n); if (n >= 0) while (n >= 0) { x = factorial(i); printf("factorial( %d) = %d\n", i, x); i = i + 1; n = n - 1; } else printf("factorial of a negative number is undefined\n"); }
Example: using function prototypes #include <stdio.h> int factorial (int n); main() { int n, i = 0, x, y; printf("Please enter value of n = "); /* Note the & before the variable n */ scanf("%d", &n); if (n >= 0) while (n >= 0) { printf("factorial( %d) = %d\n", i, factorial(i)); i = i + 1; n = n - 1; } else printf("factorial of a negative number is undefined\n"); } A function prototype is required in some versions of C if the function is defined after it is used.
Example: using function prototypes int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); } The function definition is defined after main().
Arrays and functions* What happens if you enter a value > SIZE for the number of elements? How would you protect against this? #include <stdio.h> #include <stdlib.h> #define SIZE 10 void readints(int s[], int max); int main() { int arr[SIZE]; int i; int realSize; // read in number of numbers to use printf("enter the number of numbers \n"); scanf("%d", &realSize); while (realSize < 1){ printf("enter the number of numbers (> 0) \n"); scanf("%d", &realSize); } readints(arr, realSize); For a function, must have a prototype if the function body is given after the main( ) function. Always do error checking! To pass an array, just use its name In C arrays are (in effect) pass-by-reference * This example is on the server at /home/barr/Student/Examples/array_readints.c
Arrays* // continued from previous slide for (i = 0; i < realSize; i++) { printf("arr[%d] = %d ", i, arr[i]); if (i % 5 == 0) printf("\n"); } printf("\n"); return 0; } * This example is on the server at /home/barr/Student/examples/array_readints.c
readints* // readints.c #include <stdio.h> #define SIZE 5 void readints(int s[ ],int max) { inti; for (i = 0; i < max; i++) { printf("Enter element %d: ", i); scanf("%d", &s[i]); } return; } You don’t have to specify the size of an array that is a parameter (for 1D arrays) Note the format of the comment in the program on the server * This example is on the server at /home/barr/Student/examples/array_readints.c
I/O* • There are three standard I/O “streams” in C • stdin • stdout • stderr • You can also create other streams • files • pipes • sockets * See K&R chapter 7 or H&S chapter 15
Variable fptr is a file pointer exit(1) will cause the program to terminate with an error Function fopen will open the file File I/O* version 1 #include <stdio.h> // need this library for the exit() system call #include <stdlib.h> #define SIZE 100 int main() { int line[SIZE]; int n, i = 0; FILE *fptr; char textName[30]; printf("Enter the file name: "); scanf("%s", textName); /* verify that we can open the file */ if ( (fptr= fopen(textName, "r")) == NULL) { fprintf(stderr, "Cannot open %s for reading ", textName); exit(1); } while ( (fscanf(fptr, "%d", &line[i]) ) != EOF) { printf("integer %d = %d\n", i, line[i]); i++; } close(fptr); printf ("Goodbye! \n"); } NULL means nothing as in this pointer is pointing to nothing. * This example is on the server at /home/barr/Student/Examples/week2/array1D_file.c
File I/O* version 2 #include <stdio.h> // need this library for the exit() system call #include <stdlib.h> #define SIZE 100 int main() { int line[SIZE]; int n, i = 0; FILE *fptr; char textName[30]; printf("Enter the file name: "); scanf("%s", textName); fptr = fopen(textName, "r”); /* verify that we can open the file */ if (fptr == NULL) { fprintf(stderr, "Cannot open %s for reading ", textName); exit(1); } Continued on next slide
File I/O* version 2 count = 0; intrslt; rslt= fscanf(fptr, "%d", &line[count]); while ( rslt != EOF && count + 1 < ROWS) { printf("integer %d = %d\n", count, line[count]); count++; rslt = fscanf(fptr, "%d", &line[count]); } close(fptr); printf ("Goodbye! \n"); }
File I/O* #include <stdio.h> #include <stdlib.h> #define SIZE 100 void printArray(int line[], int count); int main() { int line[SIZE]; int n, i = 0; FILE *fptr; char textName[30]; printf("Enter the file name: "); scanf("%s", textName); fptr = fopen(textName, "r”); /* verify that we can open the file */ if (fptr == NULL) { fprintf(stderr, "Cannot open %s for reading ", textName); exit(1); } while ( (fscanf(fptr, "%d", &line[i]) ) != EOF) { printf("integer %d = %d\n", i, line[i]); i++; } close(fptr); printArray(line, i); }
File I/O* void printArray(int line[], int count) { FILE *outPtr; char outTextName[30]; inti; // note that count contains the number of numbers that were read printf("Enter the output file name\n"); scanf("%s", outTextName); outPtr= fopen(outTextName, "w"); /* verify that we can open the file */ if (outPtr == NULL) { fprintf(stderr, "Cannot open %s for writing ", outTextName); exit(1); } for (i = 0; i < count; i++) { fprintf(outPtr, "%d ", line[i]); } close(outPtr); }
2D arrays #include <stdlib.h> #include <stdio.h> #define ROWS 2 #define COLS 3 int main( ) { int matrix[ROWS][COLS]; int n, i, j; // can’t print a number directly so store it in a variable n = COLS; for (i = 0; i < ROWS; i++) { printf("Enter %d ints for row %d:\n", n, i); for (j = 0; j < COLS; j++) { scanf("%d", &matrix[i][j]); } } * This example is on the server at /home/barr/Student/Examples/week2/array2D.c
2D arrays (cont) printf( "The numbers are: \n"); for (i = 0; i < ROWS; i++){ for (j = 0; j < COLS; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } }
File I/O: reading 2D arrays*part 1** #include <stdlib.h> #include <stdio.h> #define ROWS 5 #define COLS 10 int main( ) { int matrix[ROWS][COLS]; int n, i, j; FILE *fname; char *textName = “ints.txt”; fname = fopen(textName, "r"); // error check; did the file open? if (fname == NULL) { fprintf(stderr, "Could not open %s\n", textName); exit(1); } fnameis the file descriptor variable here’s where we open the file * see K&R section 5.7 or H&S section 5.4.2 for a discussion of multi-dimensional arrays **See /home/barr/Student/Examples/week1/arrays2D_file.c
File I/O: reading part 2 for (i = 0; i < ROWS; i++) { for (j = 0; j < COLS; j++) { fscanf(fname, "%d", &matrix[i][j]); } } printf( "The numbers are: \n"); for (i = 0; i < ROWS; i++){ for (j = 0; j < COLS; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } here’s where we read in from the file
Strings • A string in C is a char array • This is a string with up to 30 characters: char line[30]; • To be a string a char array must have the character ‘\0’ as its last character • string constants are really arrays: char line[30] = “john”;
Strings • The C string library contains functions #include <string.c> char *strcpy (char *dest, char *src); Copy src string into dest string. char *strncpy(char *string1, char *string2, int n); Copy first n characters of string2 to stringl . intstrcmp(char *string1, char *string2); Compare string1 and string2 to determine alphabetic order. intstrncmp(char *string1, char *string2, int n); Compare first n characters of two strings. intstrlen(char *string); Determine the length of a string.
Strings char *strcat(char *dest, const char *src); Concatenate string src to the string dest. char *strncat(char *dest, const char *src, int n); Concatenate n chracters from string src to the string dest. char *strchr(char *string, int c); Find first occurrence of character c in string. char *strrchr(char *string, int c); Find last occurrence of character c in string. char *strstr(char *string2, char string*1); Find first occurrence of string string1 in string2. char *strtok(char *s, const char *delim) ; Parse the string s into tokens using delim as delimiter.
I/O strings* Variables line and newLine will be a strings #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 100 int main( ) { char line[SIZE], newLine[SIZE]; int n, count; count = 0; printf("Enter a character. End your input with ^d: \n"); n = scanf(" %c", &line[count]); while (n != EOF) { count++; printf("Enter a character. End your input with ^d: \n"); n = scanf(" %c", &line[count]); } line[count] = '\0'; Note: if you’re reading a character at a time it’s better to use the function getchar() Need the ’\0’character to make it a string * This example is on the server at /home/barr/Student/Examples/strings/string1.c
I/O strings* // when I call strncpy need to leave room for the \0 strncpy(newLine, line, count + 1); printf ("count is %d\n", count); printf ("You entered the characters %s \n", line); printf ("You entered the characters %s \n", newLine); } Use a function from the string.h library to copy string from line to newLine * This example is on the server at /home/barr/Student/Examples/strings/string1.c
File I/O strings* Variable line will be a string #include <stdio.h> #include <stdlib.h> #define SIZE 100 int main( ) { char line[SIZE]; int n; FILE *fptr; char textName[15] = "inFile.txt"; /* verify that we can open the file */ if ( (fptr = fopen(textName, "r")) == NULL) { fprintf(stderr, "cannot open %s for reading", textName); exit(1); } * This example is on the server at /home/barr/Student/Examples/strings/string_file.c
I/O strings getchar()* // have to enter ^d twice. In UNIX/LINUX you can enter ^d once at the beginning of a line or // ^d twice at the end of a line to signal EOF. while (c != EOF) { line[count] = c; count++; c = getchar(); } line[count] = '\0'; // when I call strncpy need to leave room for the \0 strncpy(newLine, line, count + 1); printf ("count is %d\n", count); printf ("You entered the characters %s \n", line); printf ("You entered the characters %s \n", newLine); } Same example as previous slide but using getchar() instead * This example is on the server at /home/barr/Student/Examples/strings/string2.c
File I/O strings* #include <stdio.h> #include <stdlib.h> #define SIZE 100 int main( ) { char line[SIZE]; int n; FILE *fptr; char textName[15] = "inFile.txt"; /* verify that we can open the file */ if ( (fptr = fopen(textName, "r")) == NULL) { fprintf(stderr, "cannot open %s for reading", textName); exit(1); } This example reads in an entire line at a time. * This example is on the server at /home/barr/Student/Examples/strings/string_file2.c
File I/O strings* n = fscanf(fptr, "%s", line); while (n != EOF) { printf("n = %d \t line = %s\n", n, line); n = fscanf(fptr, "%s", line); } printf ("Goodbye! \n"); } this will read strings (characters separated by white space) * This example is on the server at /home/barr/Student/Examples/strings/string_file.c
I/O strings getchar()* #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 100 int main( ) { char line[SIZE], newLine[SIZE]; char c; int n, count; count = 0; printf("Enter a bunch of characters. End your input with ^d . Note that a newline is a character!\n"); c = getchar(); Same example as previous slide but using getchar() instead * This example is on the server at /home/barr/Student/Examples/strings/string2.c
File I/O strings* n = readline(line, SIZE, fptr); while (n != 0) { printf("n = %d \t line = %s\n", n, line); n = readline(line, SIZE, fptr); } printf ("Goodbye! \n"); } Call to function readline to read a line. readline will return 0 when there are no more lines to read (see next slide). Note that you can use fscanf to read a line, but it’s not easy. * This example is on the server at /home/barr/Student/Examples/strings/string_file2.c
File I/O strings (cont)* /* This function will read an entire line including white space until either a newline character of the EOF character is found */ #include <stdio.h> int readline(char s[ ],int max, FILE *fptr) { int c,i=0; // must do this so that we have room at the end for the \0 max--; while (i < max && (c = getc(fptr)) != EOF && c != '\n') s[i++] = c; // uncomment the following line if you want the \n included in the string //if (c == '\n') s[i++] = c; s[i] = '\0'; return(i); } To compile the previous slide together with this slide: > gcc –o string_file.c readline.c * This example is on the server at /home/barr/Student/Examples/strings/readline.c
Argc indicates the number of command line arguments (including the program name). Argv is an array of pointers to char (strings) that lists all of the command line arguments. Command Line intmain(int argc, char *argv[ ]) { int j; if (argc != 2) { printf("factorial takes one integer argument\n"); return(1); /* abnormal termination. */ } /* ASCII string to integer conversion */ j = atoi(argv[1]); printf("factorial(%d) = %d\n", j, factorial(j)); return(0); }
Command Line #include <stdio.h> intfactorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); }