Академический Документы
Профессиональный Документы
Культура Документы
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.
Chapter 1: An Overview of C
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.
Chapter 1: An Overview of C
Chapter 1: An Overview of C
Chapter 1: An Overview of C
Chapter 1: An Overview of C
Chapter 1: An Overview of C
Chapter 1: An Overview of C
10
Chapter 1: An Overview of C
11
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
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
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
Chapter 1: An Overview of C
15
Chapter 1: An Overview of C
16
Chapter 1: An Overview of C
17
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
Chapter 1: An Overview of C
19
Chapter 1: An Overview of C
Chapter 1: An Overview of C
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
Chapter 1: An Overview of C
22
Chapter 1: An Overview of C
in file pacific_sea.c
#include pacific sea h pacific_sea.h int main(void) {
23
Chapter 1: An Overview of C
Single quotes are used to designate character constants Thus a is the character constants corresponding to the lowercase letter a
24
Chapter 1: An Overview of C
25
Chapter 1: An Overview of C
26
Chapter 1: An Overview of C
27
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
28
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; }
29
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
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
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;
32
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;
33
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
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
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
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
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
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
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
41
Chapter 1: An Overview of C
42
Chapter 1: An Overview of C
#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
Chapter 1: An Overview of C
44
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
Chapter 1: An Overview of C
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
47
Chapter 1: An Overview of C
Comments
standard header file string.h contains many stringhandling functions i.e. strcpy()
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
Chapter 1: An Overview of C
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].
49
Chapter 1: An Overview of C
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
50
Chapter 1: An Overview of C
Comments
The variable s is printed int the format of string
51
Chapter 1: An Overview of C
Comments
52
Chapter 1: An Overview of C
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
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
Chapter 1: An Overview of C
#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
Chapter 1: An Overview of C
Comments
Chapter 1: An Overview of C
END OF CHAPTER 1
58