Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP 21000 Spring 2016 C Part IV.

Similar presentations


Presentation on theme: "Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP 21000 Spring 2016 C Part IV."— Presentation transcript:

1 Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP 21000 Spring 2016 C Part IV

2 2-2

3 Unix Passwords – Changing passwd whoami finger and the.plan file Help – about a command man cmdName apropos cmdName which cmdName ;gives path to the application 2-3

4 Unix Directories – Seeing, manuvering, creating cd /path/to/new/directory pwd ls [-a –l] mkdir dirName rmdir dirName rm –r dirName pushd. popd 2-4

5 Unix Files – Moving, deleting cp src dest rm fileName – Viewing more fileName cat fileName1 fileName2 – Permissions ls –l chmod 777 fileName 2-5

6 Unix Processes – What’s running? ps ;only your processes ps –a ;all processes PID TTY TIME CMD 33129 ttys000 0:00.02 -bash 33178 ttys000 0:00.00 man builtin 33186 ttys000 0:00.00 /usr/bin/less -is 33131 ttys001 0:00.01 -bash 33130 ttys002 0:00.02 –bash 2-6

7 Kill kill command is used to stop a running process – A user can kill all his process. – A user can not kill another user’s process. – A user can not kill processes System is using. – A root user* can kill System-level-process and the process of any user. * the root is the administrator 2-7

8 Kill kill -9 pid ;kill process pid other ways to kill – kill by name pkill a.out ;kill all processes named a.out – kill on the command line ^c ;hold down control key and press the c key ;kills currently running process 2-8

9 More Unix Shells – Environmental variables (capitalization counts!) Echo $ENV $PATH –.bashrc and.bash_profile files alias changing $PATH using source to act on changes to the file Pipes – using the | operator to connect programs 2-9

10 More Unix Redirection – using > and >> to redirect stdout to a file > to overwrite >> to append – using &> to redirect stdout and stderr to a file gcc –g -o ex1 ex1.c > err.txt &> err.txt – using < to redirect stdin from file History – the ! operator 2-10

11 2-11

12 The function of a compiler 2-12

13 The compiler as a program 2-13

14 The machine independence of a Level HOL6 language 2-14

15 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! 2-15

16 The three attributes of a C++/C variable A name A type A value 2-16

17 A C++ program that processes three integer values 2-17 #include #define bonus 5 int exam1, exam2, score; main( ){ scanf(“%d %d”, &exam1, &exam2); score = (exam1 + exam2)/2 + bonus; printf(“score = %d\n”, score); } C++ program C program Note the & Note that all declarations must be at the beginning, either before main() or right after main( ). Cannot put them in the body! Cannot declare in a for statement! (except gcc does allow C++ like syntax)

18 A C++ program that processes three integer values (Cont’d) 2-18

19 Output: printf 2-19 printf(“score = %d\n”,score);

20 Input: scanf 2-20 scanf(“%d %d”,&exam1, &exam2);

21 A program to process a character variable 2-21 #include char ch; main (){ scanf(“%c”,&ch); printf(“Original character: %c\n”, ch); ch++; printf(“Following character: %c\n”, ch); } What if you replace %c with %d?

22 A program to process a character variable (Cont’d) 2-22 bash-2.03$ a.out s Original character: 115 Following character: 116 Using %d Using %c The ASCII code for a “s”

23 Error Checking What if the user enters the wrong type? – C will convert characters to int – But will (normally) only read a single character – Example #include int main() { int x = 0; while (x != -1){ printf("Enter an integer: "); scanf("%d", &x); } return 0; } 2-23 Admins-Computer-52:~/Classes/CS210/PractSoln barr$ !g gcc testPurge0.c Admins-Computer-52:~/Classes/CS210/PractSoln barr$ !a a.out Enter an integer: 5 Enter an integer: 6 Enter an integer: a Enter an integer:

24 Error Checking What if the user enters the wrong type? – C will convert characters to int – But will (normally) only read a single character – Example #include int main() { int x = 0; while (x != -1){ printf("Enter an integer: "); scanf("%d", &x); __fpurge(stdin); } return 0; } 2-24 Note: fpurge is only available in BSD 4.4. __fpurge works in Linux. Note the two underscores before the name fpurge On some systems may have to include the lib stdio_ext.h No man page for __fpurge google it.

25 Error Checking NAME fflush, fpurge -- flush a stream LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include int fflush(FILE *stream); int fpurge(FILE *stream); DESCRIPTION The function fflush() forces a write of all buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush() flushes all open output streams. The function fpurge() erases any input or output buffered in the given stream. For output streams this discards any unwritten output. For input streams this discards any input read from the underlying object but not yet obtained via getc(3); this includes any text pushed back via ungetc(3). 2-25 Note that fflush only works on output streams! Useful to use fpurge before doing input

26 Other IO functions #include int fgetc(FILE *stream); char *fgets(char *s, int size, FILE *stream); int getc(FILE *stream); int getchar(void); char *gets(char *s); int ungetc(int c, FILE *stream); 2-26

27 Other IO functions fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once. getchar() is equivalent to getc(stdin). 2-27

28 Other IO functions gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. No check for buffer overrun is performed. fgets() reads in at most one less than n characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer. ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed - back characters will be returned in reverse order; only one pushback is guaranteed. 2-28

29 Example: factorial 2-29 #include int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); } 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"); }

30 Example: using function prototypes 2-30 #include 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"); } int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); } A function prototype is required in some versions of C if the function is defined after it is used.

31 Types: floating point Family of float types. – float (often 16 bits) – double (often 32 bits) – long double (often 64 bits) 2-31

32 Floating Point 2-32 1 #include 2 3 /* print Fahrenheit-Celsius table 4 for f = 0, 20,..., 300 */ 5 main() 6 { 7 int lower, upper, step; 8 float fahr, celsius; 9 10 lower = 0; /* lower limit of temperature table */ 11 upper = 300; /* upper limit */ 12 step = 20; /* step size */ 13 14 fahr = lower; 15 while (fahr <= upper) { 16 celsius = (5.0/9.0) * (fahr - 32.0); 17 printf("%4.0f %6.1f\n", fahr, celsius); 18 fahr = fahr + step; 19 } 20 } Formatting instructions For floating point output

33 2-33 Floating point input/output

34 2-34 A conversion specification begins with a percent sign character, %, and has the following elements in order: 1. Zero or more flag characters: –, +, 0, #, or space, which modify the meaning of the conversion operation. 2. An optional minimum field width expressed as a decimal integer constant. 3. An optional precision specification expressed as a period optionally followed by a decimal integer. This is the min number of digits to be printed in d, I, o, u, x and X conversions. Is the num of digits to right of decimal point in e, E, and f. Is the maximum number of characters in s conversion. 4. An optional size specification expressed as on of the letters ll, l, L, h, hh, j, z or t which tells whether conversion is to a long or a short when necessary. 5. The conversion operation, a single character from the set a, A, c, d, e, E, f, g, G, I, n, o, p, s, u, x, X, % “%+5.2hf”

35 Conversion 2-35 Size specification changes output type

36 The relational operators 2-36

37 The if statement 2-37 #include #define LIMIT 100 int num; main () { printf("Enter an integer: \n"); scanf("%d", &num); if (num > LIMIT) { printf("high \n"); } else if (num < LIMIT) { printf("low \n"); } else { printf("right on! \n"); } Don’t forget the & in scanf. Why? This is how you do constants in C. The const key word also works. This is how you do constants in C. The const key word also works.

38 The if statement (Cont’d) 2-38

39 The boolean operators 2-39

40 The switch statement 2-40 #include int guess; main() { printf("Enter a number between 1 and 3: \n"); scanf("%d", &guess); switch(guess) { case 1: printf("%d is way too low \n", guess); break; case 2: printf("%d is correct!! \n", guess); break; case 3: printf("%d is way too high \n", guess); break; default: printf("%d is not between 1 and 3!!\n", guess); break; }

41 The switch statement (Cont’d) 2-41 users-MacBook-Pro:Spring 11 user$ testSwitch Enter a number between 1 and 3: 1 1 is way too low users-MacBook-Pro:Spring 11 user$

42 The while statement 2-42 #include char letter; main() { printf("Enter a letter between a and z: \n"); scanf("%c", &letter); while (letter != '*') { printf("Enter a letter between a and z: \n"); scanf("%c", &letter); } scanf causes a problem. Why? How do we fix this? We can end input with a ^d. Will this help?

43 The while statement (Cont’d) #include char letter; main() { printf("Enter a letter between a and z: \n"); gets(&letter); printf("You entered: %c\n", letter); while (letter != '*') { printf("Enter a letter between a and z: \n"); gets(&letter); printf("You entered: %c\n", letter); } 2-43 Does this work? Why do you get: warning: this program uses gets(), which is unsafe. What happens if you enter two letters on a line (like ab)? Why? Does this work? Why do you get: warning: this program uses gets(), which is unsafe. What happens if you enter two letters on a line (like ab)? Why?

44 The do statement 2-44 printf(“%d”,cop);

45 The do statement (Cont’d) 2-45

46 The for statement with an array 2-46 #include #define SIZE 4 main() { int i; int v[SIZE]; for (i = 0; i < SIZE; i++) { printf("Enter an integer: \n"); scanf("%d", &v[i]); } for (i = 0; i < SIZE; i++) { printf("v[%d] = %d: \n", i, v[i]); printf("v[%d] = %d: \n", SIZE-i-1, v[SIZE - i - 1]); } Why the “- 1” ?? How would you make the two print statements print side-bye-side?

47 The for statement with an array (Cont’d) 2-47 users-MacBook-Pro:Spring 11 user$ !t testFor Enter an integer: 9 Enter an integer: 8 Enter an integer: 7 Enter an integer: 6 v[0] = 9: v[3] = 6: v[1] = 8: v[2] = 7: v[1] = 8: v[3] = 6: v[0] = 9: users-MacBook-Pro:Spring 11 user$

48 Pointers #include int main() { int n1, n2, *intPtr; intPtr = &n1; printf ( "Enter two numbers\n"); scanf("%d%d",&n1,&n2); printf ( "The numbers you entered are: %d and %d \n", n1, n2); printf ("n1 is %d\n", *intPtr); intPtr = &n2; printf ( "n2 is %d\n",*intPtr); *intPtr = n1 + n2; printf ( "and their sum is: %d\n",n1 + *intPtr); } 2-48 Pointer assignment Accessing value that pointer points at Changing a value in variable that pointer points at Pointer declaration

49 Arrays // ex2.c #include #define SIZE 5 int readints(int s[ ],int max) { int c,i=0; printf("Enter %d numbers: \n",max); while (i < max) scanf("%d",&s[i++]); return(i); } 2-49 You don’t have to specify the size of an array that is a parameter

50 Arrays // ex2.c int main() { int line[SIZE]; int i, n; n = readints(line, SIZE); printf("The numbers you entered are: \n"); for (i = 0; i < n; i++) { printf("%d\n", line[i]); } 2-50 You do have to specify the size of an array that is a variable (unless you want to use dynamic memory)

51 2D Arrays #include #define SIZE 5 /* function prototype */ void vector_add(int a[][SIZE], int n); main() { int i,j; int numRows=3; int arr[3][SIZE]; printf("Enter in the first row (5 values): "); for (i = 0; i < numRows; i++){ for (j = 0; j < SIZE; j ++) scanf("%d", &arr[i][j]); if (i < numRows -1) printf("\nEnter in the next row: "); } fprintf(stderr,"Calling vector_add\n"); vector_add(arr, 3); printf("\n"); printf("Good bye!\n"); } 2-51 You DO have to specify the size of all dimensions in an array that is a parameter EXCEPT the first.

52 2D Arrays /* cannot return an array! */ void vector_add(int a[][SIZE], int n) { int i,j; int ans[n]; /* initialize ans */ for (i = 0; i < n; i++) ans[i] = 0; fprintf(stderr,"in vector_add\n"); /* sum the rows */ for (i = 0; i < n ; i++) for (j = 0; j < SIZE ; j++) ans[i] = ans[i] + a[i][j]; printf("The sum of each row is: \n"); for (i = 0; i < n; i++) printf("%d ",ans[i]); printf("\n\n"); } 2-52 Cannot return an array. Well, you can return a pointer that points to an array, but we won’t go there. Yet.

53 Arrays and Pointers // ex2-2.c #include #define SIZE 5 int readints(int *s,int max) { int c,i=0; printf("Enter %d numbers: \n",max); while (i < max){ scanf("%d",s++); i++; } return(i); } 2-53 An array is a pointer and vice versa

54 Arrays and Pointers // ex2-2.c int main() { int line[SIZE]; int i, n, *intPtr; intPtr = line; n = readints(line, SIZE); printf("The numbers you entered are: \n"); for (i = 0; i < n; i++) { printf("%d\n", *(intPtr++)); } 2-54 Using pointer arithmetic to access an array

55 Arrays and Pointers dynamic memory #include int readints(int *s,int max) { int c,i=0; printf("Enter %d numbers: \n", max); while (i < max) scanf("%d",&s[i++]); return(i); } 2-55 An array is a pointer and vice versa

56 Arrays and Pointers dynamic memory int main() { int *line; int i, n, *intPtr, theSize; printf("Enter the size of the array\n"); scanf("%d", &theSize); line = (int *) malloc(theSize * sizeof(int)); intPtr = line; n = readints(line, theSize); printf( "The numbers you entered are: \n"); for (i = 0; i < n; i++) { printf("%d\n", *intPtr++); } free(line); // always free dynamically allocated storage } 2-56 Dynamic allocation Using pointer arithmetic to access an array Note that memory that is allocated must be freed! malloc returns a (void *), so it must be cast.

57 2D arrays and Pointers #include int main(){ int *line[5], *ptr; int n, i; for (n = 0; n < 5; n++) line[n] = (int *)malloc(4*sizeof(int)); for (n = 0; n < 5; n++){ for (i = 0; i < 4; i++) line[n][i] = n * i; } printf( "The numbers are: \n"); for (n = 0; n < 5; n++){ for (i = 0; i < 4; i++){ printf("%d ", line[n][i]); } printf("\n"); } 2-57

58 2D arrays and Pointers #include int main(){ int *line[5], *ptr; int n, i; for (n = 0; n < 5; n++) line[n] = (int *)malloc(4*sizeof(int)); for (n = 0; n < 5; n++){ ptr = line[n]; for (i = 0; i < 4; i++) //line[n][i] = n * i; *ptr++ = n * i; } printf( "The numbers are: \n"); for (n = 0; n < 5; n++){ ptr = line[n]; for (i = 0; i < 4; i++){ printf("%d ”*ptr++,); } printf("\n"); } 2-58

59 Strings #include int lower(int c) { if (c >= 'A' && c <= 'Z') return(c + 'a' - 'A'); else return(c); } int main() { int c; printf("Enter some characters. To end input hit ^D on a new line\n"); /* read char until end of file */ while ( (c = getchar()) != EOF) putchar(lower(c)); } 2-59

60 Strings as arrays # include int strequal(char x[ ], char y[ ]) { int i=0; if (x == y) return(1); while (x[i] == y [i]) { if (x[i] == '\0') return (1); i++; } return(0); } 2-60

61 Strings as arrays int main() { char str1[10],str2[10]; printf("Enter a string\n"); scanf("%s",str1); printf("\nEnter another string\n"); scanf("%s",str2); if (strequal(str1,str2)) printf("The strings are equal\n"); else printf("The strings are not equal\n"); } 2-61

62 Strings and Pointers #include int main() { char alpha[ ] = "abcdefghijklmnopqrstuvwxyz"; char *str_ptr; str_ptr = alpha; while(*str_ptr != '\0') printf ("%c ",toupper(*str_ptr++) ); printf("\n"); } 2-62 Strings always end with the ‘\0’ character An array name is a pointer “toupper” is a function defined in the ctype.h library.

63 Strings: readline #include #define SIZE 100 int readline(char s[ ],int max) { int c,i=0; max--; while (i < max && (c = getchar()) != EOF && c != '\n') s[i++] =c; if (c == '\n') s[i++] = c; s[i] = '\0'; return(i); } 2-63

64 Strings: readline int main() { char line[SIZE]; int n; while ( (n = readline(line, SIZE) ) > 0) printf("n = %d \t line = %s\n", n, line); } 2-64

65 Strings and dynamic memory #include /* compare two strings character by character using array syntax */ int strequal(char x[ ],char y[ ]) { int i=0; if (x == y) return(1); while (x[i] == y [i]) { if (x[i] == '\0') return (1); i++; } return(0); } 2-65

66 Strings and dynamic memory int main() { char *str1,*str2; str1 = (char *) malloc(20 * sizeof(char)); str2 = (char *) malloc(20 * sizeof(char)); printf("Enter a string or ! to halt \n"); scanf("%s",str1); while (strcmp(str1, "!") != 0){ printf("\nEnter another string\n"); scanf("%s",str2); if (strequal(str1,str2)) printf("The strings are equal\n"); else printf("The strings are not equal\n"); printf("Enter a string or ! to halt \n"); scanf("%s",str1); } 2-66 Strcmp is a library functionstrequal is a user defined function

67 Strings and pointers int strequal(char *x, char *y) ;// function prototype #define DEBUG 1 int main() { char *str1,*str2; str1 = (char *) malloc(10 * sizeof(char)); str2 = (char *) malloc(10 * sizeof(char)); printf("Enter a string or ! to halt \n"); scanf("%s",str1); #ifdef DEBUG printf("This is a debug statement. str1 is %s \n", str1); #endif while (strcmp(str1, "!") != 0){ printf("\nEnter another string\n"); scanf("%s",str2); if (strequal(str1,str2)) printf("The strings are equal\n"); else printf("The strings are not equal\n"); printf("Enter a string or ! to halt \n"); scanf("%s",str1); } 2-67 If the name DEBUG is #defined, then #ifdef is true and the printf is included. Use #define to put in debug statements

68 Strings and pointers #include int strequal(char *x, char *y) { if (x == y) return(1); while (*x++ == *y++) { if (*x == '\0' && *y == '\0') return (1); } return(0); } 2-68 *x is the contents of what x points at Return true if at end of string

69 Command Line int main(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); } 2-69 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.

70 Command Line #include int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans); } 2-70

71 File I/O #include #define SIZE 100 int main(int argc, char *argv[ ]) { char line[SIZE]; int n; FILE *fname; if (argc <2) { fprintf(stderr, "%s : you must include a file name \n",argv[0]); exit(1); } /* verify that we can open the file */ if ( (fname = fopen(argv[1], "w")) == NULL) { fprintf(stderr, "%s: cannot open %s for writing", argv[0], argv[1]); exit(1); } printf("Enter some lines. End your input with ^d: \n"); while ( (n = readline(line, SIZE) ) > 0) fprintf(fname, "n = %d \t line = %s\n", n, line); printf ("Goodbye! \n"); } 2-71 Variable fname is a file pointerFunction fopen will open the file given as the first argument of the command line. Function fprintf writes to the file indicated by its first argument.

72 File I/O /* This function will read an entire line including white space until either a newline character of the EOF character is found */ int readline(char s[ ],int max) { int c,i=0; max--; while (i < max && (c = getchar()) != EOF && c != '\n') s[i++] =c; if (c == '\n') s[i++] = c; s[i] = '\0'; return(i); } 2-72

73 File I/O: reading part 1 #include int main(int argc, char *argv[]) { int *line[5]; int n, i, *ptr; FILE *fname; if (argc <2) { // if there is no command line argument, use a default name fname = fopen("ints.txt", "r"); } else fname = fopen(argv[1], "r"); // error check; did the file open? if (fname == NULL) { fprintf(stderr, "Could not open %s\n", argv[1]); exit(1); } 2-73 here’s where we open the file fname is the file descriptor variable See ex3.7.c

74 File I/O: reading part 2 for (n = 0; n < 5; n++) line[n] = (int *)malloc(4*sizeof(int)); for (n = 0; n < 5; n++) { ptr = line[n]; for (i = 0; i < 4; i++) { fscanf(fname, "%d", ptr++); } printf( "The numbers are: \n"); for (n = 0; n < 5; n++){ for (i = 0; i < 4; i++) { printf("%d ", line[n][i]); } printf("\n"); } 2-74 here’s where we read in from the file Dynamically allocate memory

75 Bitwise operators in C 1 #include 2 #include 3 4 5 main() 6 { 7 int x, y; 8 9 printf("Enter two numbers: "); 10 scanf("%d %d", &x, &y); 11 12 printf ("%d AND %d gives %d\n\n", x, y, x & y); 13 printf ("%d OR %d gives %d\n\n", x, y, x | y); 14 printf ("%d Exclusive OR %d gives %d\n\n", x, y, x ^ y); 15 printf ("%d shifted left 2 places gives %d\n\n", x, x << 2); 16 printf ("%d shifted right 2 places gives %d\n\n", x, x >> 2); 17 printf ("%d complemented gives %d\n\n", x, ~x); 18 } 2-75

76 Masking a = 15215; b = a << 2; printf("Shifting by 2 bits: \n a = %d \n b = %d\n\n", a, b); printf("a in bytes:\n"); show_bytes((pointer) &a, sizeof(int)); printf("b in bytes:\n"); show_bytes((pointer) &b, sizeof(int)); b = a & theMask; printf("Masking out everything but the last byte: \n a = %d \n b = %d\n\n", a, b); printf("a in bytes:\n"); show_bytes((pointer) &a, sizeof(int)); printf("b in bytes:\n"); show_bytes((pointer) &b, sizeof(int)); 2-76

77 Masking b = a & theMask; b = b << 8; printf("Masking out the last byte and then shifting 8 bits: \n a = %d \n b = %d\n\n", a, b); printf("a in bytes:\n"); show_bytes((pointer) &a, sizeof(int)); printf("b in bytes:\n"); show_bytes((pointer) &b, sizeof(int)); } 2-77

78 Masking #include typedef unsigned char *pointer; void show_bytes(pointer start, int len) { int i; for (i = 0; i < len; i++) /* with some compilers you need to put in the first 0x */ //printf("0x%p\t0x%.2x\n", start+i, start[i]); printf("%p\t0x%.2x\n", start+i, start[i]); printf("\n"); } int main(int argc, char* argv[]) { int a, b; int theMask = 0x000000FF; 2-78

79 Octal Numbers octal1.c #include #define DIG 20 void octal_print(int x) { int i = 0, od; char s[DIG]; /* up to DIG octal digits */ if ( x < 0 ) /* treat negative x */ { putchar ('-'); /* output a minus sign */ x = - x; } do { od = x % 8; /* next higher octal digit */ s[i++] = (od + '0'); /* octal digits in char form */ } while ( (x = x/8) > 0); /* quotient by integer division */ putchar('0'); /* octal number prefix */ do { putchar(s[--i]); /* output characters on stdout */ } while ( i > 0 ); putchar ('\n'); } 2-79

80 Octal Numbers octal1.c int main() { int x; octal_print(0); /* result: 00 */ octal_print(-1); /* result: -01 */ octal_print(123456); /* result: 0361100*/ octal_print(-123456); /* result: -0361100*/ octal_print(999); /* result: 01747 */ octal_print(-999); /* result: -01747 */ octal_print(1978); /* result: 03672 */ printf("enter a number or -1 to quit: "); scanf("%d", &x); while (x != -1){ octal_print(x); printf("\n"); printf("enter a number of -1 to quit: "); scanf("%d",&x); } 2-80

81 Any Base convert.c #include #define DIG 20 void octal_print(int x, int base) { int i = 0, od; char s[DIG]; /* up to DIG octal digits */ if ( x < 0 ) /* treat negative x */ { putchar ('-'); /* output a minus sign */ x = - x; } do { od = x % base; /* next higher octal digit */ s[i++] = (od + '0'); /* octal digits in char form */ } while ( (x = x/base) > 0); /* quotient by integer division */ putchar('0'); /* octal number prefix */ do { putchar(s[--i]); /* output characters on stdout */ } while ( i > 0 ); putchar ('\n'); } 2-81

82 Octal Numbers octal2.c #include #define LOWDIGIT 07 #define DIG 20 void octal_print(register int x) { register int i = 0; char s[DIG]; if ( x < 0 ){ /* treat negative x */ putchar ('-'); /* output a minus sign */ x = - x; } do{ s[i++] = ((x & LOWDIGIT) + '0'); /* mod performed with & */ } while ( ( x >>= 3) > 0 ); /* divide x by 8 via shift */ putchar('0'); /* octal number prefix */ do{ putchar(s[--i]); /* output characters on s */ } while ( i > 0 ); putchar ('\n'); } 2-82

83 Octal Numbers octal2.c int main() { int x; octal_print(0); /* result: 00 */ octal_print(-1); /* result: -01 */ octal_print(123456); /* result: 0361100 */ octal_print(-123456); /* result: -0361100 */ octal_print(0123456); /* result: 0123456 (0 indicates octal)*/ octal_print(-0123456); /* result: -0123456 */ octal_print(999); /* result: 01747 */ octal_print(-999); /* result: -01747 */ octal_print(1978); /* result: 03672 */ printf("enter a number or -1 to quit: "); scanf("%d", &x); while (x != -1){ octal_print(x); printf("\n"); printf("enter a number of -1 to quit: "); scanf("%d",&x); } 2-83


Download ppt "Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP 21000 Spring 2016 C Part IV."

Similar presentations


Ads by Google