Computational Methods of Scientific Programming Fall 2007

Similar documents
Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Computational Methods of Scientific Programming Lecture 8. Today s lecture Start C/C++ Basic language features

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Standard File Pointers

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

CSCI 171 Chapter Outlines

C programming basics T3-1 -

Lectures 5-6: Introduction to C

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Contents. A Review of C language. Visual C Visual C++ 6.0

Lecture 03 Bits, Bytes and Data Types

Pointers and File Handling

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Lectures 5-6: Introduction to C

Kurt Schmidt. October 30, 2018

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

File I/O. Preprocessor Macros

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill

211: Computer Architecture Summer 2016

File Access. FILE * fopen(const char *name, const char * mode);

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Binghamton University. CS-220 Spring Includes & Streams

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

File IO and command line input CSE 2451


Organization of a file

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

BİL200 TUTORIAL-EXERCISES Objective:

CAAM 420 Notes Chapter 2: The C Programming Language

Course organization. Course introduction ( Week 1)

Standard C Library Functions

Input/Output and the Operating Systems

EL2310 Scientific Programming

Advanced C Programming Topics

Input / Output Functions

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Computer Programming Unit v

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

2009 S2 COMP File Operations

CSC 270 Survey of Programming Languages. Input and Output

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

CSE 374 Programming Concepts & Tools

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

File Handling. 21 July 2009 Programming and Data Structure 1

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

Model Viva Questions for Programming in C lab

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

25.2 Opening and Closing a File

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Basic and Practice in Programming Lab 10

PROGRAMMAZIONE I A.A. 2017/2018

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

File I/O. Arash Rafiey. November 7, 2017

PRINCIPLES OF OPERATING SYSTEMS

Input/Output: Advanced Concepts

High Performance Programming Programming in C part 1

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

ENG120. Misc. Topics

Come and join us at WebLyceum

C Basics And Concepts Input And Output

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Main Program Revisited. Reading Assignment. K.N. King Chapter 3, 22. K.N. King Sections Example of Argument Processing

SWEN-250 Personal SE. Introduction to C

EE458 - Embedded Systems Lecture 4 Embedded Devel.

CSI 402 Lecture 2 Working with Files (Text and Binary)

CSE 124 Discussion (10/3) C/C++ Basics

Advanced C Programming and Introduction to Data Structures

C Programming. The C Preprocessor and Some Advanced Topics. Learn More about #define. Define a macro name Create function-like macros.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

C PROGRAMMING. Characters and Strings File Processing Exercise

Friday, September 16, Lab Notes. Command line arguments More pre-processor options Programs: Finish Program 1, begin Program 2 due next week

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

DATA STRUCTURES USING C

EL2310 Scientific Programming

Computer Programming: Skills & Concepts (CP) Files in C

211: Computer Architecture Summer 2016

A Crash Course in C. Steven Reeves

Problem Solving and 'C' Programming

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Unit 4 Preprocessor Directives

A Fast Review of C Essentials Part I

Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C

C Programming Language

Friday, February 10, Lab Notes

CSE 12 Spring 2016 Week One, Lecture Two

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Intermediate Programming, Spring 2017*

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Transcription:

MIT OpenCourseWare http://ocw.mit.edu 12.010 Computational Methods of Scientific Programming Fall 2007 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

12.010 Computational Methods of Scientific Programming Lecture 9 Today s lecture C in more detail

Summary LAST LECTURE Basic C Syntax v. Fortran THIS LECTURE Examined C-pointers File Input/Output and the routines for formatted reads and writes Compiling C routines The C preprocessor cpp. Structures in C Memory management 10/5/2006 12.010 Lec 09 2

Call by reference In call by reference, the address of a variable (called a pointer) is passed to the function. The value stored at this address can be changed but not the address itself (arguments to C functions can never be changed). Example: int mymax(*float, *float); /* Prototype. The *float is a pointer to (address of) a floating point number */ main () { float a,b; int ans; a=b=2.; ans= mymax(&a,&b); /* 1 if a > b, 2 if b > a, 0 otherwise */ /* set a and b = to max. value */ } int mymax(float *a, float *b) { if ( *a > *b ) {*b=*a;return 1;} if ( *b > *a ) {*a=*b;return 2;} return 0; } 10/5/2006 12.010 Lec 09 3

Addresses - *, & C allows very explicit addressing of memory locations with the concept of pointers (points to memory location) 0x00 short a; short *ptr_to_a; a = 1; ptr_to_a = &a; Computer Memory 0xFF 0001 &a a (value stored at &a) 10/5/2006 12.010 Lec 09 4

Example of pointer use The following code examines how pointers can be used. main () { char c='a', *p, s[100], *strcpy(); p = &c ; printf("\n%c %c %c", *p, *p+1, *p+2); s[0] = 'A' ; s[1] = 'B'; s[2] = 'C'; s[3] = '\0'; p = s; printf("\n%s %s %c %s",s, p, *(p+1), p+1); strcpy(s,"\nshe sells seas shells by the seashore"); printf("%s",s); p += 17; for ( ; *p!= '\0' ; ++p ){ if ( *p == 'e' ) *p = 'E'; if ( *p == ' ' ) *p = '\n'; } printf("%s\n",s); } Output of Program A B C ABC ABC B BC she sells seas shells by the seashore she sells seas shells by the seashore 10/5/2006 12.010 Lec 09 5

File input/output To use files in C, the stdio.h header needs to be included. This contains a structure called FILE. Code for file use contains FILE *fp, *fopen(); fp = fopen( file name, r ); fp will return NULL if file could not be opened. The options for open are r read; w write; a append The file name is a variable would be declared char file_name[100]; With stdio.h included, stdin stdout and stderr are pointers to the keyboard, screen and error output (direct output to screen with little or no buffering). fclose(fp) will close the file (needed if written in one part of program and read in another). Automatically happens when program stops. 10/5/2006 12.010 Lec 09 6

Reading/writing files To read files: getc(fp) : Gets next character in file fgetc(fp) : Same but function not macro getchar() : Similar but reads from stdin fgets(s,n,fp) : Gets string of n-1 characters or until a newline character is read (\n) gets(s) : Similar but reads from stdin putc(c,fp) : Outputs a character (putchar to stdout) fputs(s, fp) : null terminated string sent to file. (puts goes to stdout). fseek and other functions allow more control of moving through file. 10/5/2006 12.010 Lec 09 7

Reading/writing The main reading/writing routines are: printf, fprintf, sprintf : Output formatted lines to stdout, a file pointer and string scanf, fscanf, sscanf : Input formatted lines stdin, a file pointter or a string. Format used: %nc - prints character in n-width right justified; %-nc is left justified. %n.ms - n character string into m width right justfied, %-n.ms is left justified, %s whole string to \0 %n.md int ouput (%-n.md left justified) %n.mf floating point %n.me exponential format Others include o for octal, x for hexidecimal, g for e/f combination 10/5/2006 12.010 Lec 09 8

Compiling and linking Source code is created in a text editor. To compile and link: cc <options> prog.c funcs.c -llibraries -o prog Where prog.c is main program plus maybe functions funcs.c are more subroutines and functions libraries.a are indexed libraries of subroutines and functions (see ranlib) prog is name of executable program to run. <options> depend on specific machine (see man cc or cc --help) -llibraries refers to precompiled library in file liblibraries.a 10/5/2006 12.010 Lec 09 9

C preprocessor (CPP) precompile macros and options; compiler proper does not see CPP code. Also stand alone cpp; other compilers e.g..f files fortran (not in java!) #include - file inclusion #define - macro definition #undef - undefine macro #line - compiler messages line number (not really for general use) #if, #ifdef, #ifndef, - Conditional compilation #else, #elif, #endif FILE, LINE (ANSI C). 10/5/2006 12.010 Lec 09 10

C preprocessor (CPP) #include fred.h - includes contents of file fred.h in program. I cpp flag sets path to search for fred.h #define PI 3.14159 - substitutes 3.14159 everywhere PI occurs in program source. (except in quotes). #undef PI - stops substitution #ifdef PI printf( pi is set to %f in file %s\n,pi, FILE ); #else printf( pi is not set. Line %d file %s\n, LINE, FILE ); #endif 10/5/2006 12.010 Lec 09 11

C preprocessor (CPP) Macros with args #define _getaddress(a) (&a) /* This macro returns address of a */ main() { double n; double *ptrton; ptrton = _getadress(n); } Compiler actually sees code below main() { double n; double *ptrton; ptrton = &n; } Often used for debuging #ifdef debug #define _D(a) a #else #define _D(a) #endif 10/5/2006 12.010 Lec 09 12

Structures and Types Way to group things that belong together e.g. Representing 3d coord (x,y,z) No structures double cx, cy, cz; cx=3.;cy=3.;cz=2; plot(cx, cy, cz); Structure struct { double cx; double cy; double cz; } point; point.cx = 3.; point.cy=3.;point.cz=2.; 10/5/2006 12.010 Lec 09 13

Structures and Types Struct alone is still unclear - typedef typedef struct { double cx; double cy; double cz; } t_point; main() { t_point point; point.cx = 3.; point.cy=3.; point.cz=2.; plot(point); } 10/5/2006 12.010 Lec 09 14

Structures and Types Derived types just like basic types e.g. can use arrays typedef struct { double cx; double cy; double cz; } t_point; main() { t_point point[10]; int i; for (i=0;i<10;++i) { point[i].cx = 3.; point[i].cy=3.; point[i].cz=(double)i; } for (i=0;i<10;++i) { plot(point[i]); } } 10/5/2006 12.010 Lec 09 15

Memory Management Application code creates variables and arrays at runtime <stdlib.h> - malloc, calloc, free, realloc + sizeof e.g main(int argc, char *argv[]) { double *foo; int nel; int i; /* Create an array of size nel at runtime */ sscanf(argv[1], %d\n,&nel); foo = (double *) calloc(nel,sizeof(*foo)); if ( foo == NULL ) exit(-1); for (i=0;i<nel;++i) { foo[i]=i; } free(foo); } 10/5/2006 12.010 Lec 09 16

short a; short *ptr_to_a; a = 1; ptr_to_a = &a; *ptr_to_a = 1; Remember - *, & a 0001 0001 0002 0003 0x00 0xFF &a Here compiler allocated memory for you foo = (double *) calloc(3,sizeof(*foo)); Here application allocates memory explicitly. Allows more control but requires careful bookkeeping. 10/5/2006 12.010 Lec 09 17

Examined C-pointers Summary File Input/Output and the routines for formatted reads and writes Compiling C routines The C preprocessor cpp. Structures in C Memory management 10/5/2006 12.010 Lec 09 18