Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Organization & Systems

Similar presentations


Presentation on theme: "Introduction to Computer Organization & Systems"— Presentation transcript:

1 Introduction to Computer Organization & Systems
Spring 2018 Introduction to Computer Organization & Systems UNIX and C Topics: UNIX command line C - everything

2

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

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

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

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

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

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

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

10 More Unix Redirection History
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

11

12 The function of a compiler

13 The compiler as a program

14 The machine independence of a Level HOL6 language

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!

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

17 A C++ program that processes three integer values
Note the & #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); } 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)

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

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

21 scanf #include <stdio.h> int main() { char C, B; int x; printf("What comes after G\n"); scanf("%c", &C); printf("What comes after O\n"); scanf("%c", &B); printf("What is your age?\n"); scanf("%d", &x); return 0; } Run this!

22 scanf What’s the problem? Why does it occur?
\n is a character! Fix: leave a space before the %c that you use in scanf: scanf(” %c”, &myChar); Note the space!

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

24 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 The ASCII code for a “s”

25 Error Checking What if the user enters the wrong type?
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: What if the user enters the wrong type? C will convert characters to int But will (normally) only read a single character Example #include <stdio.h> int main() { int x = 0; while (x != -1){ printf("Enter an integer: "); scanf("%d", &x); } return 0;

26 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 <stdio.h> int main() { int x = 0; while (x != -1){ printf("Enter an integer: "); scanf("%d", &x); __fpurge(stdin); } return 0; 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.

27 Error Checking Note that fflush only works on output streams!
NAME fflush, fpurge -- flush a stream LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdio.h> int fflush(FILE *stream); 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). Note that fflush only works on output streams! Useful to use fpurge before doing input

28 Other IO functions #include <stdio.h> 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);

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

30 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(int *s, int n, FILE *stream) 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. To read from keyboard use stdin for stream 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.

31 Example: factorial #include <stdio.h> 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; else printf("factorial of a negative number is undefined\n");

32 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"); int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; return(ans); A function prototype is required in some versions of C if the function is defined after it is used.

33 Types: floating point Family of float types. float (often 16 bits)
double (often 32 bits) long double (often 64 bits)

34 Floating Point Formatting instructions For floating point output
1 #include <stdio.h> 2 3 /* print Fahrenheit-Celsius table 4 for f = 0, 20, ... , 300 */ 5 main() 6 { int lower, upper, step; float fahr, celsius; 9 lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit */ step = 20; /* step size */ 13 fahr = lower; while (fahr <= upper) { celsius = (5.0/9.0) * (fahr ); printf("%4.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } 20 } Formatting instructions For floating point output

35 Floating point input/output

36 Floating point input/output
“%+5.2hf” 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, %

37 Conversion Size specification changes output type

38 The relational operators

39 The if statement This is how you do constants in C.
#include <stdio.h> #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"); This is how you do constants in C. The const key word also works. Don’t forget the & in scanf. Why?

40 The if statement (Cont’d)

41 The boolean operators

42 The switch statement #include <stdio.h> 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); case 3: printf("%d is way too high \n", guess); default: printf("%d is not between 1 and 3!!\n", guess); }

43 The switch statement (Cont’d)
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$

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

45 The while statement (Cont’d)
#include <stdio.h> char letter; main() { printf("Enter a letter between a and z: \n"); gets(&letter); printf("You entered: %c\n", letter); while (letter != '*') } 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?

46 The do statement <stdio.h> printf(“%d”,cop);

47 The do statement (Cont’d)

48 The for statement with an array
#include <stdio.h> #define SIZE 4 main() { int i; int v[SIZE]; for (i = 0; i < SIZE; i++) printf("Enter an integer: \n"); scanf("%d", &v[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?

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

50 Pointers #include <stdio.h> 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); } Pointer declaration Pointer assignment Accessing value that pointer points at Changing a value in variable that pointer points at

51 Arrays // ex2.c #include <stdio.h> #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); } You don’t have to specify the size of an array that is a parameter

52 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]); } You do have to specify the size of an array that is a variable (unless you want to use dynamic memory)

53 2D Arrays You DO have to specify the size of all dimensions in an array that is a parameter EXCEPT the first. #include <stdio.h> #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");

54 2D Arrays Cannot return an array. Well, you can return a pointer that points to an array, but we won’t go there. Yet. /* 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"); printf("%d ",ans[i]); printf("\n\n"); }

55 Arrays and Pointers An array is a pointer and vice versa
// ex2-2.c #include <stdio.h> #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); An array is a pointer and vice versa

56 Arrays and Pointers Using pointer arithmetic to access an array
// 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++)); } Using pointer arithmetic to access an array

57 Arrays and Pointers dynamic memory
#include <stdlib.h> 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); } An array is a pointer and vice versa

58 Arrays and Pointers dynamic memory
alloc family: man malloc 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 malloc returns a (void *), so it must be cast. Dynamic allocation The function sizeof is defined in the stdlib.h library Using pointer arithmetic to access an array Note that memory that is allocated must be freed!

59 2D arrays and Pointers #include <stdlib.h> #include <stdio.h> 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 (i = 0; i < 4; i++){ printf("%d ", line[n][i]); printf("\n");

60 2D arrays and Pointers #include <stdlib.h> #include <stdio.h> 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 (i = 0; i < 4; i++){ printf("%d ”*ptr++,); printf("\n");

61 Strings #include <stdio.h> 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));

62 Strings as arrays #include <stdio.h>
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);

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

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

65 Strings: readline #include <stdio.h> #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); }

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

67 Strings and dynamic memory
#include <string.h> /* 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);

68 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"); } Strcmp is a library function strequal is a user defined function

69 Strings and pointers Use #define to put in debug statements
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"); } Use #define to put in debug statements If the name DEBUG is #defined, then #ifdef is true and the printf is included.

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

71 Command Line Argc indicates the number of command line arguments (including the program name). 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); Argv is an array of pointers to char (strings) that lists all of the command line arguments.

72 Command Line #include <stdio.h> int factorial (int n) { int ans = 1; while (n > 1) { ans *= n; n = n - 1; } return(ans);

73 File I/O Variable fname is a file pointer Function fopen will open
#include <stdio.h> #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]); 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"); Function 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.

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

75 File I/O: reading part 1 fname is the file descriptor variable
#include <stdlib.h> #include <stdio.h> 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); fname is the file descriptor variable here’s where we open the file See ex3.7.c

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

77 Bitwise operators in C 1 #include <stdio.h> 2 #include <stdlib.h> main() 6 { 7 int x, y; 8 9 printf("Enter two numbers: "); 10 scanf("%d %d", &x, &y); 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 }

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

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

80 Masking #include <stdio.h> #include <stdlib.h> 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;

81 Octal Numbers octal1.c #include <stdio.h> #include <stdlib.h> #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 */ putchar(s[--i]); /* output characters on stdout */ } while ( i > 0 ); putchar ('\n');

82 Octal Numbers octal1.c int main() { int x; octal_print(0); /* result: 00 */ octal_print(-1); /* result: -01 */ octal_print(123456); /* result: */ octal_print( ); /* result: */ octal_print(999); /* result: */ octal_print(-999); /* result: */ octal_print(1978); /* result: */ 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); }

83 Any Base convert.c #include <stdio.h> #include <stdlib.h> #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 */ putchar(s[--i]); /* output characters on stdout */ } while ( i > 0 ); putchar ('\n');

84 Octal Numbers octal2.c #include <stdlib.h> #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 */ putchar(s[--i]); /* output characters on s */ } while ( i > 0 ); putchar ('\n');

85 Octal Numbers octal2.c int main() { int x; octal_print(0); /* result: 00 */ octal_print(-1); /* result: -01 */ octal_print(123456); /* result: */ octal_print( ); /* result: */ octal_print( ); /* result: (0 indicates octal)*/ octal_print( ); /* result: */ octal_print(999); /* result: */ octal_print(-999); /* result: */ octal_print(1978); /* result: */ 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); }


Download ppt "Introduction to Computer Organization & Systems"

Similar presentations


Ads by Google