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

Similar documents
C Overview Fall 2015 Jinkyu Jeong

C Overview Fall 2014 Jinkyu Jeong

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental of Programming (C)

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Fundamentals of Programming Session 4

C: How to Program. Week /Mar/05

Programming for Engineers Introduction to C

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Chapter 2 - Introduction to C Programming

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

Programming and Data Structures

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Computer System and programming in C

File IO and command line input CSE 2451

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming

LESSON 4. The DATA TYPE char

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Multiple Choice Questions ( 1 mark)

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Approximately a Test II CPSC 206

8. Characters, Strings and Files

BİL200 TUTORIAL-EXERCISES Objective:

UNIT- 3 Introduction to C++

Work relative to other classes

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CSE 230 Intermediate Programming in C and C++ Input/Output and Operating System

ANSI C Programming Simple Programs

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

Arrays, Strings, & Pointers

Basic Elements of C. Staff Incharge: S.Sasirekha

Fundamentals of Programming

Fundamental of Programming (C)

Input/Output: Advanced Concepts

Data types, variables, constants

THE FUNDAMENTAL DATA TYPES

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

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

CS102: Variables and Expressions

Chapter 1 & 2 Introduction to C Language

Course organization. Course introduction ( Week 1)

Course Outline Introduction to C-Programming

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

ET156 Introduction to C Programming

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Simple Java Reference

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

today cs3157-fall2002-sklar-lect05 1

printf( Please enter another number: ); scanf( %d, &num2);

Programming and Data Structure

A Fast Review of C Essentials Part I

Fundamentals of Programming. Lecture 11: C Characters and Strings

Chapter 8 - Characters and Strings

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

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

10/6/2015. C Input/Output. stdin, stdout, stderr. C Language II. CMSC 313 Sections 01, 02. C opens three input/output devices automatically:

2. Numbers In, Numbers Out

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Approximately a Final Exam CPSC 206

Chapter 2: Basic Elements of C++

C programming basics T3-1 -

Input/Output and the Operating Systems

BSM540 Basics of C Language

C Programming Multiple. Choice

Computers Programming Course 5. Iulian Năstac

Lecture 3. More About C

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Fundamentals of C. Structure of a C Program

Computational Methods of Scientific Programming Fall 2007

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

UNIT-I Input/ Output functions and other library functions

Chapter 2, Part I Introduction to C Programming

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

BITG 1233: Introduction to C++

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

Objectives. In this chapter, you will:

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

C - Basic Introduction

Programming & Data Structure

H192 Midterm 1 Review. Tom Zajdel

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 11 Introduction to Programming in C

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

C mini reference. 5 Binary numbers 12

Chapter 2: Overview of C. Problem Solving & Program Design in C

Data Type Fall 2014 Jinkyu Jeong

Standard I/O in C and C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

Transcription:

Chapter 1. An Overview 1.1 Programming and Preparation Operating systems : A collection of special programs Management of machine resources Text editor and C compiler C codes in text file. Source code to object code. (Source file: *.c) (Executable file: *.exe) ABC; 9/1/2004; 1-1 1.2 Program Output An example of source sea.c printf( from sea to shining C\n ) ; Compile sea.c sea.c is preprocessed and then compiled The detail of sea.c [1] The preprocessor inserts the header file stdio.h at the point. Information about printf( ) function. The angle brackets < > The header file is in the usual place [2] : Definition of the function main( ) main( ) takes no arguments and returns an integer value. void int ( ) means main is a function void, int are keywords (32 keywords in C) [3] The braces indicate the start and the end of the function [4] printf( ) One of functions in the standard library It prints on the screen [5] from sea to shining C\n string (characters in double quotes) \n (backslash n) means newline Cursor to the beginning of the next line backslash n is treated as a single character

[6] printf( from sea to shining C\n ) The function is called or invoked and its argument is printed on the screen [7] printf( from sea to shining C\n ) ; A statement ends with a semicolon [8] return 0 ; : return statement It returns 0 to the operating system, which may be used later. ABC; 9/1/2004; 1-2 Three examples with printf( ) printf("from sea to shining C\n") ; return 0 ; /* printf("from sea to ") ; printf("shining C") ; printf("\n") ; printf("from sea\n") ; printf("to shining\nc\n") ; */ printf("\n\n\n\n\n\n\n\n\n\n"); printf(" ***********************\n"); printf(" * from sea *\n"); printf(" * to shining C *\n"); printf(" ***********************\n"); printf("\n\n\n\n\n\n\n\n\n\n"); 1.3 Variables, Expressions, and Assignment Numbers in mathematics : natural numbers, integers, real numbers, imaginary numbers Numbers without imaginary parts Natural numbers, negatives of these and zero Two types of numbers in C integers, floating-point numbers 37 37.0 decimal point Three floating types : float : 6 significant digits after the decimal point double : 15 digits long double : At leat as many digits as a double. In C floating numbers are automatically of type double. Variables can store integers and floating numbers. Variables must be declared at the beginning of the program. A variable name is called an identifier. Letters, digits, and underscore (But no digits at the beginning)

ABC; 9/1/2004; 1-3 Assignment statement x = 7.0 ; y = x + 3 ; assignment operator Expression The right side of the assignment operator, or the arguemnt to a function. THE EVALUATION OF EXPRESSIONS INVOLVES CONVERSIONS. y = 7 / 2 ; y = 3 division of two integers y = 7.0 / 2 ; y = 3.5 2 is converted to a double division of a double by an integer Example: Convert the marathon distance (26 miles and 385 yards) to kilometers. Km/Mi = 1.609, Yd/Mi = 1760.0 /* The distance of a marathon in kilometers. */ A comment int miles, yards ; /* Declaration */ float kilometers ; /* kilometers is of type float */ miles = 26 ; /* Assignment statement */ yards = 385 ; kilometers = 1.609 * (miles + yards / 1760.0 ) ; /* Assignment statement */ /* multiplication, addition, division */ /* ( ) is calculated first. * and / precede + and - */ printf( \na marathon is %f kilometers. \n\n, kilometers) ; Control string Format Variable (It prints the variable kilometers as a floating-point number) return 0 ;

1.4 The Use of #define and #include A line beginning with # : preprocessing directive. Normally, they are at the beginning of the program. ABC; 9/1/2004; 1-4 #define PI 3.14159 All the PI s after the line are converted to 3.14159, except in strings, printf( PI = %f\n, PI) ; Advantage of using #define The program becomes more readable. It is easy to change its value later. #include my_file.h my_file.h is inserted at this point of the program. The difference between #include... and #include <...> Example: pacific_sea.c in page 15 [1] These are exactly the same. #define SQ_FEET_PER_SQ_MILE (5280*5280) #define SQ_FEET_PER_SQ_MILE 5280*5280 #define SQ_FEET_PER_SQ_MILE 27878400 [2] #define AREA 2337 const int pacific_sea = AREA ; type qualifier (pacific-sea can be initialized but not changed thereafter) 2337 AREA pacific_sea preprocessor compiler [3] printf( %22.7e acres\n, acres) ; 5.7748528e+05 acres e-format scientific notation, 5.7748528X10 5 22 : total spaces 7 : number of digits after the decimal point

1.5 The Use of printf( ) and scanf( ) printf( ) is used for output scanf( ) is used for input : f stands for formatted ABC; 9/1/2004; 1-5 printf(control string, arguments) variable, string, character, etc. Examples: printf( abc ) ; It contains conversion specifications (% + field width + conversion character) number of spaces for printing printf( %s, abc ) ; printf( %c%c%c, a, b, c ) ; : s = string : c = character printf( %c%3c%5c, A, B, C ) ; A B C 1--4----9 Conversion characters : scanf(control string, addresses) scanf( %d, &x) ; : & = address operator Read characters as an integer and store it at x. scanf() returns the number of conversions Example: Type 1337 on the keyboard A decimal integer %d Not an integer but a string

scanf() skips spaces in reading numbers but not in reading a character. ABC; 9/1/2004; 1-6 char c1, c2, c3; int i; float x; double y; printf("\n%s\n%s", "Input three characters", "an int, a float, and a double: "); scanf("%c%c%c%d%f%lf", &c1, &c2, &c3, &i, &x, &y); printf("\nhere is the data that you typed in:\n"); printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, i, x, y); Try to type 19 30.8 45.6 Conversion characters : 1.6 Flow of Control Statements are normally executed in sequence, from top to bottom. if and if-else statements : Used for alternative actions while and for statements : Used for looping These require the evaluation of logical expressions (true or false) zero value non-zero value if (expr) If expr is true, then statement is executed. Statement If expr is false, then statement is skipped. a = 1 ; if (b == 3) a = 5 ; /* single statement */ is-equal-to operator printf( %d, a) ;

A compound statement is surrounded by braces if ( b == 3 ) b = 5 ; c = 7 ; ABC; 9/1/2004; 1-7 if (expr) If expr is true (nonzero), statement1 is executed. statement1 Otherwise, statement2 is executed. else statement2 if(cnt == 0) a = 2; b = 3; c = 5; else a = -1; b = -2; c = -3; while (expr) If expr is true, the statement is executed. statement The while loop is executed again until expr is false. int i = 1, sum = 0 ; while (i <= 5) /* <= is less-than-or-equal-to operator */ sum += i ; /* sum = sum + i */ ++ i ; /* i = i + 1 */ printf( sum = %d\n, sum) ; return 0 ; for (expr1; expr2; expr3) expr1 : An initial assignment statement expr2 : A test expr3 : An increment at the end of the statement It is the same as the following: expr1 while (expr2) statement expr3 for ( i = 1; i <= 5; ++i) sum += i ;

Example : running_sum.c /* Compute the minimum, maximum, sum, and average. */ ABC; 9/1/2004; 1-8 #include <stdlib.h> int i; double x, min, max, sum, avg; if (scanf("%lf", &x)!= 1) // scanf() returns no. of conversions. // not-equal-to operator printf("no data found - bye!\n"); exit(1); // 0 for normal exit, 1 for otherwise min = max = sum = avg = x; printf("%5s%9s%9s%9s%12s%12s\n%5s%9s%9s%9s%12s%12s\n\n", // print headings "Count", "Item", "Min", "Max", "Sum", "Average",,,,,, ) ; printf("%5d%9.1f%9.1f%9.1f%12.3f%12.3f\n", 1, x, min, max, sum, avg); // print the first line for (i = 2; scanf("%lf", &x) == 1; ++i) // repeat until the test is false if (x < min) // i is incremented at the end min = x; else if (x > max) max = x; sum += x; avg = sum / i; printf("%5d%9.1f%9.1f%9.1f%12.3f%12.3f\n", i, x, min, max, sum, avg); 1.7 Functions A function is a piece of code. A function should be declared before used function declaration or function prototype. They are in the header files. The general form of function prototype type function_name( pararmeter type list ) ; void if no value is returned. void if no argument is taken. Example: The power function pow(2.0, 3.0) 2.0 3.0 The function prototype: double pow(double x, double y) ; // x, y are not used by the compiler. // They are optional.

ABC; 9/1/2004; 1-9 Example: maxmin.c // Function prototypes at the top after #include and #define float maximum(float x, float y); float minimum(float x, float y); void prn_info(void); // prn_info takes no arguments and returns no values int i, n; float max, min, x; // Variable declaration prn_info(); // Function call printf("input n: "); scanf("%d", &n); printf("\ninput %d real numbers: ", n); scanf("%f", &x); max = min = x; // max = (min = x) ; for (i = 2; i <= n; ++i) scanf("%f", &x); max = maximum(max, x); // Arguments are always passed by value. min = minimum(min, x); // The copy of the value of max is passed. // No change in max by the function call printf("\n%s%11.3f\n%s%11.3f\n\n, "Maximum value:", max, Minimum value:", min); float maximum(float x, float y) if (x > y) return x; else return y; // Function definition // Identifier x is unrelated to x in the main float minimum(float x, float y) // Header // Body if (x < y) return x; else return y; void prn_info(void) printf("\n%s\n%s\n\n", "This program reads an integer value for n, and then", "processes n real numbers to find max and min values.");

Call-by-value Arguments to a function are always passed by value. The variables in the argument are not changed by calling the function. ABC; 9/1/2004; 1-10 Example int a = 1; void try_to_change_it(int); /* function prototype */ printf("%d\n", a); /* 1 is printed */ try_to_change_it(a); /* function call */ printf("%d\n", a); /* 1 is printed again! */ void try_to_change_it(int a) a = 777; Call-by-reference The variables in the argument can be changed by calling the function. (Pointers should be used) 1.8 Arrays, Strings, and Pointers A string is an array of characters. abc123 a A pointer is an address in C An array name is treated as a pointer Arrays An array contains many variables of the same type int a[3] ; Three integer constants a[0], a[1], a[2]. The index starts from zero.

Example : scores.c #define CLASS_SIZE 5 ABC; 9/1/2004; 1-11 int i, j, score[class_size], sum = 0, tmp; printf("input %d scores: ", CLASS_SIZE); for (i = 0; i < CLASS_SIZE; ++i) scanf("%d", &score[i]); sum += score[i]; for (i = 0; i < CLASS_SIZE - 1; ++i) /* bubble sort */ for (j = CLASS_SIZE - 1; j > i; --j) if (score[j-1] < score[j]) /* check the order */ tmp = score[j-1]; score[j-1] = score[j]; score[j] = tmp; printf("\nordered scores:\n\n"); for (i = 0; i < CLASS_SIZE; ++i) printf(" score[%d] =%5d\n", i, score[i]); printf("\n%18d%s\n%18.1f%s\n\n", sum, " is the sum of all the scores", (double) sum / CLASS_SIZE, " is the class average"); /* cast operator. Interger value of sum is converted to a double. sum / CLASS_SIZE The fraction is ignored. */ Strings A string is an array of characters. a b_3 The end of a string should be \0 null character A character has an interger value of ASCII coding ( a = 97, b = 98,...)

Example: /* Have a nice day! */ ABC; 9/1/2004; 1-12 #include <ctype.h> // For isalpha(), is a character alphabetic? /* For getchar(), putchar(), printf() Write characters on the screen Read characters from the keyborad */ #define MAXSTRING 100 char c, name[maxstring]; // 99 characters + \0 in name. int i, sum = 0; // sum is initialized to zero printf("\nhi! What is your name? "); for (i = 0; (c = getchar())!= '\n'; ++i) read a character from the keyboard and assign it to c name[i] = c; if (isalpha(c)) // Is c one of alphabets? sum += c; // A character as a ASCII value name[i] = '\0'; /* Strings should end with a null character printf("\n%s%s%s\n%s","nice to meet you ", name, ".", "Your name spelled backwards is "); To print the array name // i = 15 at this point. Print the name backwards on the screen for (--i; i >= 0; --i) putchar(name[i]); printf("\n%s%d%s\n\n%s\n", "and the letters in your name sum to ", sum, ".", "Have a nice day!"); */ Pointers A pointer is an address of an object in memory. char c = a, *p ; p is of type pointer to char. c is of type char and initialized to a. p = &c ; address operator The address of c is stored in p (p is pointing to c) printf( %c%c%c, c, *p, *P + 1) ; indirection operator. *p+1 is one more than the value of *p. The value of what p is pointing to

Example: abc.c #include <string.h> #define MAXSTRING 100 char c = a, *p, s[maxstring] ; p = &c ; // For strcpy() to copy a string ABC; 9/1/2004; 1-13 // The string s has size MAXSTRING. printf( %c%c%c, *p, *p + 1, *p + 2) ; strcpy(s, ABC ) ; // ABC is copied to s printf( %s %c%c%s\n, s, *s + 6, *s + 7, s +1) ; // s is a pointer pointing to s[0]. *s = s[0] = A. *s + 6 = G // s+1 = address of s[1]. *(s+1 )= s[1] = B strcpy(s, she sells sea shells by the seashore ) ; p = s + 14 ; // p is a pointer variable, s is a pointer constant. s = p ; ERROR // p = &s[14]. for ( ; *p!= \0 ; ++p) if (*p == e ) *p = E ; if (*p == ) *p = \n ; printf( %s\n, s) ; return 0 ; 1.9 Files To open a file my_file // Need for fopen()... FILE *ifp ; // pointer to FILE ifp = fopen( my_file, r ) ; file name mode, r for read... w for write. Create the file or start writing from the beginning of the file. a for append. Write just after the last writing. Simultaneous opening of files = 20 or 64. fopen() returns NULL if not successful. fclose() closes the opened files. The C system closes all opened files at the end. Argument to main() int main(int argc, char *argv[]) Argument vector. Argument count. (The array points to successive words in the command line) (Number of arguments in the command line) Command line: cnt_letters chapter1 data1 argv[0] points to cnt_letters, argv[1] points to chapter1, argv[2] points to data1

Example: cnt_letters.c /* Count uppercase letters in a file */ ABC; 9/1/2004; 1-14 #include <stdlib. h> int main(int argc, char *argv[]) int c, i, letter[26]; FILE *ifp, *ofp; /* infile pointer, outfile pointer. */ if(argc!= 3) /* An error if not three arguments. */ printf( \n%s%s%s\n\n%s\n%s\n\n, Usage:, argv[0], infile outfile, The uppercase letters in infile will be counted., The results will be written in outfile. ) exit(1); ifp = fopen(argv[1], r ); ofp = fopen(argv[2], w ); for (i =0; i < 26; ++i) /* The array is automatically initialized */ letter[i] = 0; /* Manual initialization to be sure. */ while ((c = getc(ifp))!= EOF) /* EOF = end-of-file. #define EOF (-1) */ Read a character from the file. It returns EOF at the end of the file. if (c >= A && c <= Z ) /* Find uppercase letters */ Logical AND operator ++letter[c - A ]; /* If c = D, letter[3] is incremented */ for (i = 0; i < 26; ++i) if(i % 6 == 0) /* Remainder of i/6 */ MODULUS operator putc( \n, ofp); /* Write a character in the file. fprintf(ofp, %c:%5d putc( \n, ofp); Print \n for every sixth time */, A + i, letter[i]); /* Formatted print in a file */ fclose(ifp) ; /* Close file explicitly, optional */ fclose(ofp) ; Command line: cnt_letters chapter1 data1