Introduction to Computer Organization & Systems

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 CSE1301 Computer Programming: Lecture 21 File I/O.
CSE1301 Computer Programming: Lecture 19 File I/O
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
C Programming Lecture 10 Instructor: Wen, Chih-Yu Department of Electrical Engineering National Chung Hsing University.
File IO and command line input CSE 2451 Rong Shi.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
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.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
Introduction to Computer Organization & Systems Topics: Command Line Bitwise operators COMP Spring 2014 C Part V.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2016 C Part IV.
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.
Lecture 3: Getting Started & Input / Output (I/O)
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Strings (Continued) Chapter 13
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Quiz 11/15/16 – C functions, arrays and strings
CS 261 – Recitation 7 Fall 2013 Oregon State University
Getting Started with C.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Command-Line Arguments
Module 2 Arrays and strings – example programs.
C Programming:Part 3 Characters and Strings File Processing Exercise.
Strings A string is a sequence of characters treated as a group
Programmazione I a.a. 2017/2018.
Computer Science 210 Computer Organization
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Computer Programming Lecture 15 Text File I/O
Programming in C Input / Output.
Computer Science 210 Computer Organization
Programming in C Input / Output.
CSE1320 Files in C Dr. Sajib Datta
Strings.
CSE1320 Strings Dr. Sajib Datta
Functions, Part 2 of 3 Topics Functions That Return a Value
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.
File Input and Output.
File Handling.
Outline Defining and using Pointers Operations on pointers
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
Strings.
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Programming in C Input / Output.
Introduction to Computer Organization & Systems
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Introduction to Computer Organization & Systems
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Introduction to Computer Organization & Systems
Functions, Part 2 of 3 Topics Functions That Return a Value
I/O CS580U - Fall 2018.
Files Chapter 8.
Week 5 - Wednesday CS222.
Chapter 18 I/O in C.
Presentation transcript:

Introduction to Computer Organization & Systems C Part II Topics: Intro to C Types in C: int and floating point C I/O C file I/O

The function of a compiler

The compiler as a program

The machine independence of a Level HOL6 language

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

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); } Global variables are possible, but not in this class!

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

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

Input: scanf 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!

A program to process a character variable What if you replace %c with %d? #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!

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”

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* put 5 elements on a line for (i = 0; i < realSize; i++) { printf("arr[%d] = %d ", i, arr[i]); if (i % 5 == 0) 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"); } 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"); } 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) { int i; 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

File I/O* version 1 Variable fptr is a file pointer #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"); Variable fptr is a file pointer Function fopen will open the file NULL means nothing as in this pointer is pointing to nothing. exit(1) will cause the program to terminate with an error * This example is on the server at /home/barr/Student/Examples/week2/array1D_file.c

File I/O* version 2 Continued on next slide #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; int rslt; rslt = fscanf(fptr, "%d", &line[count]); while ( rslt != EOF && count + 1 < ROWS) { printf("integer %d = %d\n", count, line[count]); 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]; int i; // 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); } fname is 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 here’s where we read in from the file 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++){ 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”; 1 2 3 4 5 6 7 8 9 j o h n \0 ?

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 . int strcmp(char *string1, char *string2); Compare string1 and string2 to determine alphabetic order. int strncmp(char *string1, char *string2, int n); Compare first n characters of two strings. int strlen(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++; } 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* This example reads in an entire line at a time. #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); } 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); } 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

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.

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