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

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
Dale Roberts Basic I/O – scanf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
C Formatted Input/Output /* Using Integer Conversion Specifiers */ #include int main ( ) { printf( "%d\n", 455 ); printf( "%i\n", 455 ); printf( "%d\n",
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Introduction to C Language
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Introduction to Computer Organization & Systems Topics: Intro to UNIX COMP John Barr.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C Programming Lecture 10 Instructor: Wen, Chih-Yu Department of Electrical Engineering National Chung Hsing University.
Adv. UNIX:io/91 Advanced UNIX v Objectives of these slides: –look in some detail at standard input and output in C Special Topics in Comp.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Chapter 18 I/O in C.
File IO and command line input CSE 2451 Rong Shi.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
CSE1301 Computer Programming: Lecture 6 Input/Output.
Introduction to Computer Organization & Systems Topics: Types in C: floating point COMP C Part III.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Introduction to Computer Organization & Systems Topics: Command Line Bitwise operators COMP Spring 2014 C Part V.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
CS 1704 Introduction to Data Structures and Software Engineering.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Files A collection of related data treated as a unit. Two types Text
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
Input/output.
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
Programming in C Input / Output.
Input and Output Lecture 4.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Introduction to Computer Organization & Systems
File Input and Output.
Introduction to Computer Organization & Systems
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Programming in C Input / Output.
Introduction to Computer Organization & Systems
Introduction to Computer Organization & Systems
Chapter 11 Programming in C
Module 12 Input and Output
Introduction to C EECS May 2019.
Introduction to Computer Organization & Systems
I/O CS580U - Fall 2018.
Chapter 18 I/O in C.
Presentation transcript:

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

2-2

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

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

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

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

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

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

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

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

2-11

The function of a compiler 2-12

The compiler as a program 2-13

The machine independence of a Level HOL6 language 2-14

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

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

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)

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

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

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

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?

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”

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:

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.

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) Note that fflush only works on output streams! Useful to use fpurge before doing input

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

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

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

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

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.

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

Floating Point #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 */ fahr = lower; 15 while (fahr <= upper) { 16 celsius = (5.0/9.0) * (fahr ); 17 printf("%4.0f %6.1f\n", fahr, celsius); 18 fahr = fahr + step; 19 } 20 } Formatting instructions For floating point output

2-33 Floating point input/output

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”

Conversion 2-35 Size specification changes output type

The relational operators 2-36

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.

The if statement (Cont’d) 2-38

The boolean operators 2-39

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

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$

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?

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?

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

The do statement (Cont’d) 2-45

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?

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$

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

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

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)

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.

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.

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

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

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

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.

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

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

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

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

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

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.

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

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

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

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

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

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

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.

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

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.

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

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

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

Bitwise operators in C 1 #include 2 #include 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 } 2-75

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

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

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

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

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

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

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

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