Вы находитесь на странице: 1из 58

C Programming

Chapter 1 p An Overview of C
1 C Programming Lecture Notes. Reference Textbook : A Book on C by Al Kelley and Ira Pohl

Chapter 1: An Overview of C

Objective
This chapter gives an overview of the C programming language. A series of programs are presented and the elements of each program is explained. l d In this chapter we emphasize how to use input/output functions of C. Note carefully that all our C code also serves as C++code.

C Programming Lecture Notes

Chapter 1: An Overview of C

Programming and Preperation


It is assumed that the user is able to use some text editor to create files containing C codes. Such f l S h files are called source code. ll d d A compiler translates source code to object code that is executable. On MS-DOS systems, this compiled code is automatically created in a file with the same name as the xxx.c file, but with the .exe extension (xxx is a generic file name). An example SOURCE FILE :MyFirstProgram.c OBJECT CODE :MyFirstProgram.exe .c and .exe are file extensions. They describe the type of preceeding file name. y yp p g

C Programming Lecture Notes

Chapter 1: An Overview of C

Program Output
Programs must communicate to be useful. Our first examle is a program that prints on screen the phrase: from sea to shining C
#include <stdio.h> int main(void) { printf(from sea to shining C/n); return 0; }

Using the text editor we type this into a file whose name ends with .c c The choice of the file name must be mnemonic.

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


#include <stdio.h> A preprocesor is built into the C compiler Lines that begin with # communicate with preprocessor This #include command causes the preprocessor to include a copy of the header file stdio.h at this point in code The angle brackets around <stdio.h> indicate that the file is be found in the usual place, which is system dependent. We have included this file because it contains information about printf() function

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


int main(void) This is the first line for function definition of main() We write parantheses after name main to remind the reader that main () is a function The two words int void are Keywords / Reserved words y

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


int main(void) Every program has a function named main() Program execution always starts with this function. The top line should be read as main() is a function that takes no argument and returns an integer value g g int:=Integer ( ) following main indicate to the compiler that main is a function The keyword void indicates to the compiler that this function takes no arguments. Keep in mind that some functions may take arguments

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


{} Braces surround the body of a function definition. They are also used to group statements together. printf() The C system contains a standard library of functions This a function from library that prints on the screen stdio.h header file provides information about printf() function

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


from sea to shining C\n A string constant in C is a series of characters surrounded by double quotes This string constant is an argument to the function printf() The characters at the end of string \n is called a newline. It is a nonprinting character. It advances the cursor on the screen to the begining of the next line

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


Printf(from sea to shining C\n) This is a call to printf() function. In a program the name of the function followed by b parantheses causes the f h h function to b called or invoked. be ll d kd It may contain arguments It prints its argument, the string constant, on screen.

10

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the sea program


Printf(from sea to shining C\n); This is a statement. Many statements in C ends with semicolon. Return 0; This is a return statement. It causes the value zero to be returned to the operating system, which in turn may sue the value in some way. } The rigth brace match the left brace above ending the function definition for main()

11

C Programming Lecture Notes

Chapter 1: An Overview of C

Alternative Codes
#include <stdio.h> int main(void) { printf(from sea to) i f(f ) printf(shining C); printf(/n); return 0; }

12

C Programming Lecture Notes

Chapter 1: An Overview of C

Alternative Codes
#include <stdio.h> int main(void) { printf(from sea\n); i f(f ) printf(to shining\nC\n); return 0; }

13

C Programming Lecture Notes

Chapter 1: An Overview of C

Alternative Codes
#include <stdio.h> int main(void) { printf(\n\n\n\n\n\n\n); i f( ) printf( *********************************** *\n ); printf( * from sea *\n); printf( i f( * to shining C hi i *\n); *\ ) printf( ************************************ *\n); printf(\n\n\n\n\n\n\n); return 0; }

14

C Programming Lecture Notes

Chapter 1: An Overview of C

Variables, Expressions Variables Expressions, and Assignment


Write a program that converts marathon in miles and yards to kilometers In English units marathon is defined to be 26 miles and 385 yards 1 miles = 1.609 kilometers 1 miles = 1760.0 yards Variables Integer Real In C, all variables must be declared, or named at the beginning of program A variable name, also called identifier consists of A sequence of letters, digits, and underscore but may not start with a digit

15

C Programming Lecture Notes

Chapter 1: An Overview of C

Variables, Expressions Variables Expressions, and Assignment


/* The distance of a marathon in kilometers */ #include <stdio.h> int main(void) { int miles, yards; float kilometers; miles=26; yards=385; kilometers=1.609*(miles+yards/1760.0); printf(\nA marathon is %f kilometers \n\n, kilometers); return 0; }

16

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the marathon Program


/* The distance of a marathon in kilometers */ Anything between the characters/* and */ is a comment and is ignored by the compiler. l int miles, yards; This is a declaration statement and statements end with a semicolon. nt is a keyword float kilometers; This is a declaration statement and statements end with a semicolon. Float is a keyword

17

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the marathon Program miles=26; Yards=385; These are assignment statements The equal sign is an assignment operator The numbers 26 and 385 are integer constants
kilometers=1.609*(miles+yards/1760.0); kil t 1 609*( il + d /1760 0) This is an assignment statements The value of the expression on the rigth side of the expression is assigned to the variable kilometers * :multiplication + : addition / :division () : operation inside the parantheses is performed first / : has a higher precedence.

18

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the marathon Program


printf(\nA marathon is %f kilometers \n\n, kilometers); This is a statement that invokes or calls printf() function \nA marathon is %f kilometers \n\n, Called control string Inside the string is the specification or conversion format, %f. Its effect is to print the value of the variable kilometers as a floating-point number and i d insert it into the print stream where the f t i t th i t t h th format %f occurs. t Certain words, called keywords are reserved and cannot be used by the p g programmer as names of variables int, float, and double are keywords Other names are known to the C system and would not be redefined by the programmer The Th name printf is an example i tf i l

19

C Programming Lecture Notes

Chapter 1: An Overview of C

Dissection of the marathon Program


A decimal point in a number indicates that it is a floating-point constant than an integer constant. Thus the numbers 37 and 37.0 would be treated differently. There are three floating types Float Double Long double Floating Fl ti constants are automatically d fi d as d bl t t t ti ll defined double The name of a variable itself can be considered an expression, and meaningful combination of operators with variables and constants are also expressions. The evaluation of expressions can involve conversion rules p The division of two integers results in an integer value and the remainder is discarded. 7/2=3 7.0/2=7.0/2.0=3.5 7 0/2=7 0/2 0=3 5 kilometers=1.609*(miles+yards/1760.0); TRUE kilometers=1.609*(miles+yards/1760 ); FALSE yards/1760 0; yards/1760=0;
20 C Programming Lecture Notes

Chapter 1: An Overview of C

The use of #define and #include


The C compiler has a preprocessor built into it The lines that begin with # are called preprocessor directives
#define LIMIT #define PI 100 3.14159

The identifiers LIMIT and PI are called symbolic constants. A #define line can occur anywhere in a program. It affects only the lines in the file that th t come after it ft it. Normally, all #define lines are placed at the beginning of program Symbolic constants are general written in capital letters
#include my_file.h

is preprocessing directive that causes a copy of the file my_file.h to be included at p p this point in the file when compilation occurs. By convention the names of the header file end with .h

21

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of #define and #include


The C system provides a number of standard header files. Stdio.h String.h Math.h These files contain the declarations of functions in the standard library, macros, y, , structure templates.

22

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of #define and #include


in file pacific_sea.h
#include <stdio.h> #define AREA #define SQ_MILES_PER_SQ_KILOMETER #define SQ_FEET_SQ_MILE #define SQ_INCHES_PERSQ_FOOT #define ACRES_PERSQ_MILE ACRES PERSQ MILE 2337 0.386102 (5280*5280) 144 640

in file pacific_sea.c
#include pacific sea h pacific_sea.h int main(void) {

23

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of printf() and scanf()


Both printf() and scanf() are passed alist of arguments that can be thought of as Control_string Other_arguments Other arguments Where control string is a string and may contain conversion specifications or formats. A conversion specification starts with % character and ends with a conversion character. h
printf(abc); printf(%s,abc); printf( %c%c%c a b c ); printf(%c%c%c,a, b, c);

Single quotes are used to designate character constants Thus a is the character constants corresponding to the lowercase letter a

24

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of printf() and scanf()


Printf() Conversion character C :character D :decimal integer E :floating-point number in scientific notation F :floating-point number :floating point G :in the e-format or f-format, whichever is shorter S :string

25

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of printf() and scanf()


When an argument is printed, the place where it is printed is called its field and the number of characters in its field is called field width printf(%c%3c%5c \ A, B C) i f(% %3 %5 \n, A B, C); Function scanf() is used for input Its first argument is a control string having formats that correspond to the various ways the characters i the i h h in h input stream are to b interpreted. O h arguments are be i d Other adresses. scanf(%d,&x); The format %d is matched with the expression & causing scanf() to i Th f i h d ih h i &x, i f() interpret characters in input stream as a decimal integer and store the result at the adress of x. &x :the adress of x

26

C Programming Lecture Notes

Chapter 1: An Overview of C

The use of printf() and scanf()


Scanf() Conversion character C :character D :decimal integer F :floating-point number LF :floating-point number (double) :floating point S :string

27

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
Statements in a program are normally executed in sequence However most programs require alteration of the normal sequential flow of control The if and if-else statements provide alternative actions p While and for statements provide looping mechanism These constructs require the evaluation of logical expressions True : any nonzero value False l : zero value l The general form of an if statement
if(expr) statement

If expr is nonzero (true) then statement is executed; otherwise it is skipped.


a=1; if(b==3) a=5; printf(%d,a);

== is logical equal to operator

28

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
A group statement surrounded by braces constitute a compund statement
if(a==3) { b=5; c=7; }

An f l A if-else statement is of the form f h f


if(expr) statement1; else l statement2;

29

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
Looping mechanism is very important in programming because it allows repetetive actions
#include <stdio.h> int main(void) { int i=1, sum=0; while(i<=5) { sum+=i; i++; } printf(sum = %d\n, sum); return 0; }

30

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
C code
while(i<=5) { sum+=i; i++; } It causes the stored value of sum to be incremented by the value of i sum=sum+i; C uses ++ and to increment and decrement the stored value of variables respectively

Comments
A test is made to see if i is less than or equal to 5 If it is, then the group of statement enclosed by braces are executed

31

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
While(expr) statement;

Where statement is a simple statement or compound statement Another looping construct is the for statement. It has the form
for (expr1;expr2;expr3) statement;

If all three expressions are present this is equivalent to


expr1; while(expr2) hil ( 2) { statement; expr3; p ; }

32

C Programming Lecture Notes

Chapter 1: An Overview of C

Flow of Control
Typically, expr1 peforms an intial assignment Expr2 peforms a tests Expr3 increments a stored value Note that expr3 is the last thing done in body of loop The for loop is repeatedly executed, as long as expr2 is nonzero (true) y g
for(i=1;i<=5;i++) sum+=i;

This is equivalent to the while loop used in previous example q p p p

33

C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
The heart and soul of C programming is functions A function represents a piece of code that is a building block in peoblem-solving proesses. proesses A C program consists of one or more function sin one or more files Precisely one of the functions is a main() function, where execution of program begins. begins Other functions are called from within main() and from within each other. Functions should be declared before thay are used
double pow(double x, double y) x double pow(double, double)
Function declaration of this type are called function prototypes Identifiers such as x and y that occur in the parameter lists of function p p prototypes are not used by the yp y compiler

A function prototype tells the compiler the number and types of arguments to be passed to the function and the type of the value that is tobe returned by the function
Type function_name(parameter type li ) T f i ( lists);
34 C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
The parameter list is typically a list of types seperated by commas. Identifiers are optional; they do not affect the function prototypes The keyword void is sued if a function does not take any arguments Also the keyword void is sued if no value is returned by a function. Creating maxmin Program
Print information about the program (this list) Read an ineteger value for n Read in n real numbers Find minimum and maximum values

35

C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
In file maxmin.c C Code
#include < tdi h> #i l d <stdio.h> float maximum(float x, float y); float minimum(float x, float y); void prn_info(void); id i f ( id) int main(void) { int i,n; i ti float max, min, x; prn_info(); printf(Input n: ); scanf(%d,&n); f(%d & )

Comments
function protoype appera after any #iclude and # define f i f #i l d d d fi function prototype: take two arguments of type float and return a value of type float function prototype function prototype: take no argument return no value f i k l main() function main function body variables are d l d at th b i i of main() fucntion i bl declared t the begining f i () f ti variables are declared at the begining of main() fucntion function call that takes no argument prints on screen prompts user t enter i f t to t information using k b d ti i keyboard place the value at the adress of n

36

C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
In file maxmin.c C Code
printf(\n Input %d real numbers: , n); scanf( %f &x); scanf(%f ,&x); max=min=x; for(i=2;i<=n,i++) { scanf(%f ,&x); max=maximum(max,x); min=minimum(min,x);

Comments

equivalent to max=(min=x);

} printf(\n%s%11.3f\n%s%11.3f\n\n, Maximum value: , max Maximum max, Minimum value: , min); return 0;

for loop reads a new value for x arguments are passed on to func. maximum() returns the larger of two arguments are passed on to func. minimum() returns the smaller of two In C arguments to functions are always passed by value a copy of each argument is made and these copies are processed by functions functions. Variables passed as arguments to functions are not changed in the calling environment.

37

C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
In file maxmin.c Code
Float Fl t maximum(float x, float y) i (fl t fl t ) { if(x>y) return x; else l return y; } Float minimum(float x, float y) { if(x<y) return x; t else return y; }

Comments
header h d function body. Function definition=header+function body This function returns a value of type float parameter list: comma seperated identifier declaretation within parantheses that occur in the header to the f i hi h h i h h d h function i definition. Parameters in a function defiinition can be thought of as placeholders

38

C Programming Lecture Notes

Chapter 1: An Overview of C

Functions
In file maxmin.c
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); }

39

C Programming Lecture Notes

Chapter 1: An Overview of C

Call by value
In C, arguments to functions are always passed by value. This means that when an expression is passed as an argument to a function, th expression is evaluated, and it is this value that is passed to the function. The variables passed as arguments to functiosn a re not changed in the callin environment This argument passing convention is called passed by value To change the value of the variable in the calling environment, other languages p provice all-by-reference y In C, to get the effect of call-by-reference, ointers must be used.

40

C Programming Lecture Notes

Chapter 1: An Overview of C

Call by value
In file no_change.c C Code
#include <stdio.h> void try_to_change_it(int); try to change it(int); int main(void) { int a=1; printf(%d\n,a); void try_to_change_it(a); try to change it(a); printf(%d\n,a); return 0; } void try to change it(int a) try_to_change_it(int { a=777; }

Comments

prints on screen value 1 prints on screen value 1

41

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, and Pointers


In C, a string is an array of characters. An array name by itself is a pointer A pointer is just an adress of an object in memory Arrays are used when many variables, all of the same type, are desired. int a[3]; Allocates space for the three-element array a. p y The elements of the array are of type int and are accessed as a[0], a[1], and a[2]. The index, or subscript, of an array always start from 0. The following program illustrates the use of an array The program reads in five scores, sort them, and prints them out in order.

42

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file scores.c Code Comments

#include <stdio.h> #define CS 5 int main(void) { int i, j, score[CS], sum=0 declaration of int type array score printf(Input %d scores:, CS); for(i=0;i<CS,i++) { ( ) scanf(%d,&score[i]); use of array elements in scanf sum+=score[i]; use of array elements in an expression } . . }

43

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, and Pointers


In C, a straing is an array of characters. An array name by itself is a pointer A pointer is just an adress of an object in memory Arrays are used when many variables, all of the same type, are desired. int a[3]; Allocates space for the three-element array a. p y The elements of the array are of type int and are accessed as a[0], a[1], and a[2]. The index, or subscript, of an array always start from 0. The following program illustrates the use of an array The program reads in five scores, sort them, and prints them out in order.

44

C Programming Lecture Notes

Chapter 1: An Overview of C
Arrays, Strings, and Pointers
In file scores.c

Code
#include <ctype.h> #include <stdio.h> #define MAXSTRING 100 int main(void) { char c, name[MAXSTRING];

Comments
standard header file standard header file symbolic constant main() function variable c name: array type of char and its size is MAXSTRING all array subsscripts starts at 0: Name[0], Name[1] .... This is a prompt to user getchar() gets a character from the keyboard assign it to c and tests to see if it is a newline character used to determine whether c is a lower-case or uppercase letter

int i, sum=0; printf(\n Hi ! What is your name ? ); for(i=0;(c=getchar() != \n;i++) { name[i]=c; if(isalpha(c)) sum+=c; } Name[i]=\0;

null character \0 is assigned to the element name[i] By convention, all strings end with a null character use the null character \0 as an end-of-string sentinel.

45

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file scores.c Code
printf(\n%s%s%s, Nice to meet you , name, ., Your name spelled backwards is ); Your ); for (--i;i>=0;i++)

Comments
%s is used to print character array name: printed until the end-of-string sentinel \0

After i has been decremented , the subscript corresponds to the last characetr of the name that was typed in. Do not forget to count from 0 not 1 Thus the effect of these lines is to print 1. the name backwards

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 !; return 0; }
46 C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


A pointer is an adress of an object in memory. Because an array name is itself a pointer, the uses of arrays and pointers are intimately related related. The following program is designed to illustrate some of these relationships:

47

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, Arrays Strings and Pointers


In file abc.c Code
#include <stdio.h> #include <string.h> #define MAXSTRING 100 int main(void) { char c=a, *p, s[MAXSTRING]; p=&c;

Comments
standard header file string.h contains many stringhandling functions i.e. strcpy()

printf(%c%c%c, *p, *p+1, *p+2);

Variable p is of type pointer to char The symbol & is the adress operator. The value of the expression & i adress i memory of th variable c i &c is d in f the i bl The adress of c is assigned to p. The symbol * is the dereferencing, or indirection, operator. The expression *p has the value of whatever p i pointing t Because p i pointing t ht is i ti to. B is i ti to a This is the value of expression *p and an a is printed. The value of *p+1 is one more than the value of *p and this causes a b to be printed.

48

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, and Pointers


In file abc.c Code
strcpy(s, ABC);

Comments
A string constant is stored in the memory as an array of characters. It is size is 4 not 3 The last characters 3. character is null character \0. The function strcpy() takes two argument, both of type pointer to char, which we can think of strings. The string pointed to by its second argument is copied into memory beginning at the location pointed to by its first argument. All characters upto and including null character are copied. The first arguments must points to enough space to hold all the g p characters being copied. The array name s by itself is a pointer. We can think of s as being the base adress of the array, which is the adress of s[0]. Printing s in the format of a string causes ABC to be printed. Th p p g expression *s has the value of what s is pointing to, which is s[0]. This is the character A. The expressions *s+6 and *s+7, printed in the format of a character, cause G and H to be printed. The expression s+1 is a pointer arithmetic. The value of the expressio n is a pointer that points to s[1].

printf(%s %c%c%s\n, s, *s+6, *s+7, s+1);

49

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, and Pointers


In file abc.c Code
strcpy(s, she sells sea shells by the seashore); p=s+14; +14

Comments
copies a new string into s The i Th pointer value s+14 i assigned to p l +14 is i d An equivalent statement is p=&s[14]; Note carefully that even though s is a pointer,it is not a pointer variable, but rather a constant. p=s; CORRECT s=p; FALSE Although the value of what s points to may be changed, the value of s itself may not be changed As l A long as the value of what p i pointing t i not th l f h t is i ti to is t equal to null character, the body of the for loop is executed. If the value of what p is pointing to is equal to e, then the value in memory is changed to E g If the value of what p is pointing to is equal to , then the value in memory is changed to \n

for( *p \0, ++p) f ( ; * != \0 ++ ) { if (*p==e) *p=E; if(*p== ) *p=\n; }

50

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file abc.c Code
printf(%s\n, s); return 0; }

Comments
The variable s is printed int the format of string

51

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file abc.c Output
abc ABC GHBC she sells sea shElls by t thE sEashorE

Comments

52

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings, and Pointers


In C, arrays, and pointers are closely related.
char *p, s[100];

This creates an identifier p as apointer to char and the identifier s a an array of 100 p y elements of type char. Because an array name by itself is a pointer, both p and s are pointers to char. However p is a variable pointer, whereas s is a constant pointer that points to s[0]. Note that the expression p++ can be used to increment p. But p , p g because is a constant pointer, the expression s++ is wrong. The value of s cannot be changed. The are eqivalent
s[i]=*(s+i)

The Th epression s[i] has the value of the ith element of the array, whereas *( +i) is the i [i] h h l f h ih l f h h *(s+i) i h dereferencing of the expression s+i, a pointer expression that points to i character positions past s. Two expressions are equivalent p q
p[i]=*(p+i);

53

C Programming Lecture Notes

Chapter 1: An Overview of C

Files
To open the file named my_file, the following code may be used: In file read_it.c
#include <stdio.h> <stdio h> int main(void) { int c; FILE *if *ifp; ifp=fopen(my_file,r); ..... }

*ifp: infile pointer to be a pointer to FILE The function fopen() is in the standard library, and its function prototype is in stdio.h The first argument is the name of file Second argument is the mode in which the file is to be opened r: for read
54 C Programming Lecture Notes

Chapter 1: An Overview of C

Files
Second argument is the mode in which the file is to be opened r: for read w: for write a: for append
#include <stdio.h> int main(argc, char argv[])

argc: argument count argv: argument vector It is an array of pointers to char. Such an array can be thought of as an array of strings. Th successive elements of array points to successive words in th command ti The i l t f i t t i d i the d line that was used to execute the progra Thus, argv[0] is a pointer to the name of the command itself. Suppose we have written our program and have put the executable code in file cnt_letters
cnt_letters chapter1 data1 cnt_letters chapter2 data2

55

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file abc.c Code Comments

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int c,i, letter[26]; FILE *ifp, *ofp; if(argc!=3) { printf(\%s%s%s\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); }

56

C Programming Lecture Notes

Chapter 1: An Overview of C

Arrays, Strings Arrays Strings, and Pointers


In file abc.c Code
ifp fopen(argv[1], r ); ifp=fopen(argv[1] r); ofp=fopen(argv[2],w); for(i=0;i<26;i++) letter[i]=0; while((c=getc(ifp) != EOF) if(c>=A && c<=Z) ++letter[c-A]; for(i=0;i<26;i++) { ( ; ; ) if(i%6==0) putc(\n,ofp); fprintf(ofp, %c: %5d , A+i, letter[i]); } putc(\n, ofp); return 0; }
57 C Programming Lecture Notes

Comments

Chapter 1: An Overview of C

END OF CHAPTER 1

REFERENCE TEXTBOOK: A BOOK ON C by AL KELLEY &IRA POHL

58

C Programming Lecture Notes

Вам также может понравиться