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

C Programming Ch1

Embed Size (px)

Citation preview

Page 1: C Programming Ch1

CC ProgrammingChapter 1p

An Overview of C

C Programming Lecture Notes. Reference Textbook : A Book on C by Al Kelley and Ira Pohl1

Page 2: C Programming Ch1

Chapter 1: An Overview of C

ObjectiveObjectiveThis chapter gives an overview of the C programming language.

A series of programs are presented and the elements of each program is l dexplained.

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 Notes2

Page 3: C Programming Ch1

Chapter 1: An Overview of C

Programming and PreperationProgramming and PreperationIt is assumed that the user is able to use some text editor to create files containing C codes.

S h f l ll d dSuch files are called source code.

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 Notes3

Page 4: C Programming Ch1

Chapter 1: An Overview of C

Program OutputProgram OutputPrograms 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 cUsing the text editor we type this into a file whose name ends with .c

The choice of the file name must be mnemonic.

C Programming Lecture Notes4

Page 5: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection 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 Notes5

Page 6: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection of the sea programint 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 wordsy

C Programming Lecture Notes6

Page 7: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection of the sea programint 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.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 Notes7

Page 8: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection 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() functionstdio.h header file provides information about printf() function

C Programming Lecture Notes8

Page 9: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection 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 Notes9

Page 10: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection of the sea programPrintf(“from sea to shining C\n”)This is a call to printf() function. In a program the name of the function followed b h h f b ll d k dby parantheses causes the function to be called or invoked.

It may contain arguments

It prints its argument, the string constant, on screen.

C Programming Lecture Notes10

Page 11: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the sea programDissection of the sea programPrintf(“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()main()

C Programming Lecture Notes11

Page 12: C Programming Ch1

Chapter 1: An Overview of C

Alternative CodesAlternative Codes#include <stdio.h>int main(void){

i f(“f ”)printf(“from sea to”)printf(“shining C”);printf(“/n”);return 0;

}}

C Programming Lecture Notes12

Page 13: C Programming Ch1

Chapter 1: An Overview of C

Alternative CodesAlternative Codes#include <stdio.h>int main(void){

i f(“f ”)printf(“from sea\n”);printf(“to shining\nC\n”);return 0;

}

C Programming Lecture Notes13

Page 14: C Programming Ch1

Chapter 1: An Overview of C

Alternative CodesAlternative Codes#include <stdio.h>int main(void){

i f(“ ”)printf(“\n\n\n\n\n\n\n”);printf(“

*********************************** *\n ”);printf(“ * from sea *\n”);

i f(“ * hi i C *\ ”)printf(“ * to shining C *\n”);printf(“ ************************************ *\n”);printf(“\n\n\n\n\n\n\n”);return 0;

}}

C Programming Lecture Notes14

Page 15: C Programming Ch1

Chapter 1: An Overview of C

Variables Expressions and AssignmentVariables, Expressions, and AssignmentWrite 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 programIn 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

C Programming Lecture Notes15

Page 16: C Programming Ch1

Chapter 1: An Overview of C

Variables Expressions and AssignmentVariables, Expressions, and Assignment/* The distance of a marathon in kilometers */

#include <stdio.h>int main(void)int main(void){

int miles, yards;float kilometers;miles=26;miles=26;yards=385;kilometers=1.609*(miles+yards/1760.0);printf(“\nA marathon is %f kilometers \n\n”, kilometers);return 0;return 0;

}

C Programming Lecture Notes16

Page 17: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the marathon ProgramDissection of the marathon Program/* The distance of a marathon in kilometers */Anything between the characters/* and */ is a comment and is ignored by the

lcompiler.

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 keywordFloat is a keyword

C Programming Lecture Notes17

Page 18: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the marathon ProgramDissection of the marathon Programmiles=26;Yards=385;These are assignment statementsThe equal sign is an assignment operatorThe numbers 26 and 385 are integer constants

kil t 1 609*( il + d /1760 0)kilometers=1.609*(miles+yards/1760.0);This is an assignment statementsThe 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.

C Programming Lecture Notes18

Page 19: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the marathon ProgramDissection of the marathon Programprintf(“\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 stringInside 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

d i t it i t th i t t h th f t %f and insert it into the print stream where the format %f occurs.

Certain words, called keywords are reserved and cannot be used by the programmer as names of variablesp g

int, float, and double are keywordsOther names are known to the C system and would not be redefined by the programmer

Th i tf i lThe name printf is an example

C Programming Lecture Notes19

Page 20: C Programming Ch1

Chapter 1: An Overview of C

Dissection of the marathon ProgramDissection of the marathon ProgramA 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

FloatDoubleLong double

Fl ti t t t ti ll d fi d d blFloating constants are automatically defined as doubleThe 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 rulespThe division of two integers results in an integer value and the remainder is discarded.7/2=37 0/2=7 0/2 0=3 57.0/2=7.0/2.0=3.5kilometers=1.609*(miles+yards/1760.0); TRUEkilometers=1.609*(miles+yards/1760 ); FALSE

yards/1760=0;

C Programming Lecture Notes20

yards/1760 0;

Page 21: C Programming Ch1

Chapter 1: An Overview of C

The use of #define and #includeThe use of #define and #includeThe C compiler has a preprocessor built into itThe lines that begin with # are called preprocessor directives#define LIMIT 100#define PI 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 th t ft itthat come after it.Normally, all #define lines are placed at the beginning of programSymbolic 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 this point in the file when compilation occurs.p pBy convention the names of the header file end with .h

C Programming Lecture Notes21

Page 22: C Programming Ch1

Chapter 1: An Overview of C

The use of #define and #includeThe use of #define and #includeThe 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.

C Programming Lecture Notes22

Page 23: C Programming Ch1

Chapter 1: An Overview of C

The use of #define and #includeThe use of #define and #includein file pacific_sea.h#include <stdio.h>#define AREA 2337#define SQ_MILES_PER_SQ_KILOMETER 0.386102#define SQ_FEET_SQ_MILE (5280*5280)#define SQ_INCHES_PERSQ_FOOT 144#define ACRES PERSQ MILE 640#define ACRES_PERSQ_MILE 640

in file pacific_sea.c#include “pacific sea h”#include pacific_sea.hint main(void){

}

C Programming Lecture Notes23

Page 24: C Programming Ch1

Chapter 1: An Overview of C

The use of printf() and scanf()The use of printf() and scanf()Both printf() and scanf() are passed alist of arguments that can be thought of as

Control_stringOther argumentsOther_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 hcharacter.

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 constantsThus ‘a’ is the character constants corresponding to the lowercase letter a

C Programming Lecture Notes24

Page 25: C Programming Ch1

Chapter 1: An Overview of C

The use of printf() and scanf()The use of printf() and scanf()Printf() Conversion character

C :character

D :decimal integer

E :floating-point number in scientific notation

F :floating-point numberF :floating point number

G :in the e-format or f-format, whichever is shorter

S :string

C Programming Lecture Notes25

Page 26: C Programming Ch1

Chapter 1: An Overview of C

The use of printf() and scanf()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

i f(“% %3 %5 \ ” ‘A’ ‘B’ ‘C’)printf(“%c%3c%5c \n”, ‘A’, ‘B’, ‘C’);Function scanf() is used for inputIts first argument is a control string having formats that correspond to the various

h h i h i b i d O h ways the characters in the input stream are to be interpreted. Other arguments are adresses.scanf(“%d”,&x);Th f %d i h d i h h i & i f() iThe format %d is matched with the expression &x, causing scanf() to interpretcharacters in input stream as a decimal integer and store the result at the adress of x.&x :the adress of x

C Programming Lecture Notes26

Page 27: C Programming Ch1

Chapter 1: An Overview of C

The use of printf() and scanf()The use of printf() and scanf()Scanf() Conversion character

C :character

D :decimal integer

F :floating-point number

LF :floating-point number (double)LF :floating point number (double)

S :string

C Programming Lecture Notes27

Page 28: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlStatements in a program are normally executed in sequenceHowever most programs require alteration of the normal sequential flow of controlThe if and if-else statements provide alternative actionspWhile and for statements provide looping mechanismThese constructs require the evaluation of logical expressions

True : any nonzero valuel lFalse : zero value

The general form of an if statementif(expr)

statementstatement

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

C Programming Lecture Notes28

Page 29: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlA group statement surrounded by braces constitute a compund statementif(a==3){{

b=5;c=7;

}

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

if(expr)

statement1;

lelse

statement2;

C Programming Lecture Notes29

Page 30: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlLooping 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;

}}

C Programming Lecture Notes30

Page 31: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlC code Commentswhile(i<=5) 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{

sum+=i; It causes the stored value of sum to be incremented by the value of isum=sum+i;

i++; C uses ++ and – to increment and decrement the stored value of variables respectively

}

C Programming Lecture Notes31

Page 32: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlWhile(expr)

statement;

Where statement is a simple statement or compound statementWhere 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 toexpr1;

hil ( 2)while(expr2)

{

statement;

expr3;p ;

}

C Programming Lecture Notes32

Page 33: C Programming Ch1

Chapter 1: An Overview of C

Flow of ControlFlow of ControlTypically, 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 exampleq p p p

C Programming Lecture Notes33

Page 34: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsThe heart and soul of C programming is functions

A function represents a piece of code that is a building block in peoblem-solving proessesproesses.

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 beginsbegins.

Other functions are called from within main() and from within each other.

Functions should be declared before thay are useddouble pow(double x double y)double pow(double x, double y)

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 prototypes are not used by the y p p yp ycompiler

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

T f i ( li )

C Programming Lecture Notes34

Type function_name(parameter type lists);

Page 35: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsThe 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 ProgramPrint information about the program (this list)

Read an ineteger value for n

Read in n real numbers

Find minimum and maximum values

C Programming Lecture Notes35

Page 36: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsIn file maxmin.c

C Code Comments#i l d < tdi h> f i f #i l d d # d fi#include <stdio.h> function protoype appera after any #iclude and # definefloat maximum(float x, float y); function prototype: take two arguments of type float

and return a value of type floatfloat minimum(float x, float y); function prototype

id i f ( id) f i k lvoid prn_info(void); function prototype: take no argument return no value

int main(void) main() function{ main function body

i t i i bl d l d t th b i i f i () f tiint i,n; variables are declared at the begining of main() fucntionfloat max, min, x; variables are declared at the begining of main() fucntionprn_info(); function call that takes no argumentprintf(“Input n: ”); prints on screen

f(“%d” & ) t t t i f ti i k b dscanf(“%d”,&n); prompts user to enter information using keyboardplace the value at the adress of n

C Programming Lecture Notes36

Page 37: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsIn file maxmin.c

C Code Commentsprintf(“\n Input %d real numbers: ”, n); equivalent to max=(min=x);scanf(“%f ” &x);scanf( %f ,&x);max=min=x;for(i=2;i<=n,i++) { for loop

scanf(“%f ”,&x); reads a new value for xmax=maximum(max,x); arguments are passed on to func. maximum()

returns the larger of tworeturns the larger of twomin=minimum(min,x); arguments are passed on to func. minimum()

returns the smaller of twoIn C arguments to functions are always passed by value a copy of each argument is made and these copies are processed by functions these copies are processed by functions. Variables passed as arguments to functions are not changed in the calling environment.

}printf(“\n%s%11.3f\n%s%11.3f\n\n”,

“Maximum value: “ maxMaximum value: , max,“Minimum value: “, min);

return 0;}

C Programming Lecture Notes37

Page 38: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsIn file maxmin.c

Code CommentsFl t i (fl t fl t ) h dFloat maximum(float x, float y) header{ function body. Function definition=header+function body

if(x>y) This function returns a value of type floatreturn x; parameter list: comma seperated identifier declaretation

l i hi h h i h h d h f i else within parantheses that occur in the header to the function return y; definition. Parameters in a function defiinition can be

thought of as placeholders}

Float minimum(float x, float y){

if(x<y)t return x;

elsereturn y;

}

C Programming Lecture Notes38

Page 39: C Programming Ch1

Chapter 1: An Overview of C

FunctionsFunctionsIn 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”);

}}

C Programming Lecture Notes39

Page 40: C Programming Ch1

Chapter 1: An Overview of C

Call by valueCall by valueIn 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 provice all-by-referencep y

In C, to get the effect of call-by-reference, ointers must be used.

C Programming Lecture Notes40

Page 41: C Programming Ch1

Chapter 1: An Overview of C

Call by valueCall by valueIn file no_change.cC Code Comments#include <stdio.h>void try to change it(int);void try_to_change_it(int);int main(void){

int a=1;printf(“%d\n”,a); prints on screen value 1void try to change it(a);void try_to_change_it(a);printf(“%d\n”,a); prints on screen value 1return 0;

}

void try to change it(int a) void try_to_change_it(int a) {

a=777;}

C Programming Lecture Notes41

Page 42: C Programming Ch1

Chapter 1: An Overview of C

Arrays, Strings, and PointersArrays, Strings, and PointersIn C, a string is an array of characters.An array name by itself is a pointerA pointer is just an adress of an object in memoryA pointer is just an adress of an object in memoryArrays are used when many variables, all of the same type, are desired.

int a[3];Allocates space for the three-element array a.p yThe 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 arrayThe program reads in five scores, sort them, and prints them out in order.

C Programming Lecture Notes42

Page 43: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn 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

}

.

.

}

C Programming Lecture Notes43

Page 44: C Programming Ch1

Chapter 1: An Overview of C

Arrays, Strings, and PointersArrays, Strings, and PointersIn C, a straing is an array of characters.An array name by itself is a pointerA pointer is just an adress of an object in memoryA pointer is just an adress of an object in memoryArrays are used when many variables, all of the same type, are desired.

int a[3];Allocates space for the three-element array a.p yThe 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 arrayThe program reads in five scores, sort them, and prints them out in order.

C Programming Lecture Notes44

Page 45: C Programming Ch1

Chapter 1: An Overview of CArrays, Strings, and Pointers

In file scores.c

Code Comments#include <ctype.h> standard header file#include <stdio.h> standard header file#define MAXSTRING 100 symbolic constant#define MAXSTRING 100 symbolic constantint main(void) main() function{

char c, name[MAXSTRING]; variable cname: array type of char and its size is MAXSTRINGall array subsscripts starts at 0: Name[0], Name[1] ....

int i, sum=0;printf(“\n Hi ! What is your name ? ”); This is a prompt to userfor(i=0;(c=getchar() != ‘\n’;i++) { getchar() gets a character from the keyboard

assign it to c and tests to see if it is a newline characterassign it to c and tests to see if it is a newline charactername[i]=c;if(isalpha(c)) used to determine whether c is a lower-case or

uppercase lettersum+=c;

}Name[i]=‘\0’; null character \0 is assigned to the element name[i]

By convention, all strings end with a null characteruse the null character \0 as an end-of-string sentinel.

C Programming Lecture Notes45

Page 46: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn file scores.c

Code Commentsprintf(“\n%s%s%s”, %s is used to print character array name:

printed until the end-of-string sentinel \0

“Nice to meet you “, name, “.”,

“Your name spelled backwards is ”);Your name spelled backwards is );

for (--i;i>=0;i++) 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 0 not 1. Thus the effect of these lines is to print 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;

}

C Programming Lecture Notes46

}

Page 47: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersA 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 relatedintimately related.The following program is designed to illustrate some of these relationships:

C Programming Lecture Notes47

Page 48: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn file abc.c

Code Comments#include <stdio.h>#include <string.h> standard header file string.h contains many string-

handling functions i.e. strcpy()#define MAXSTRING 100int main(void)int main(void){

char c=‘a’, *p, s[MAXSTRING]; Variable p is of type pointer to charp=&c; The symbol & is the adress operator. The value of the

i & i d i f th i bl expression &c is adress in memory of the variable cThe adress of c is assigned to p.

printf(“%c%c%c”, *p, *p+1, *p+2); The symbol * is the dereferencing, or indirection, operator. The expression *p has the value of

h t i i ti t B i i ti t ‘ ’whatever p is pointing to. Because p is pointing 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.

C Programming Lecture Notes48

Page 49: C Programming Ch1

Chapter 1: An Overview of C

Arrays, Strings, and PointersArrays, Strings, and PointersIn file abc.c

Code Commentsstrcpy(s, ”ABC”); A string constant is stored in the memory as an

array of characters It is size is 4 not 3 The last array of characters. It is size is 4 not 3. The last 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 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 characters being copied.g p

printf(“%s %c%c%s\n”, s, *s+6, *s+7, s+1); 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 expression *s has the value of what s is pointing p p gto, 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].

C Programming Lecture Notes49

Page 50: C Programming Ch1

Chapter 1: An Overview of C

Arrays, Strings, and PointersArrays, Strings, and PointersIn file abc.c

Code Commentsstrcpy(s, “she sells sea shells by the seashore”); copies a new string into s

+14 Th i l +14 i i d p=s+14; The pointer value s+14 is assigned to pAn equivalent statement isp=&s[14];Note carefully that even though s is a pointer,it is not a pointer variable, but rather a constant.is not a pointer variable, but rather a constant.p=s; CORRECTs=p; FALSEAlthough the value of what s points to may be changed, the value of s itself may not be changed

f ( * != ‘\0’ ++ ) { A l th l f h t i i ti t i t for( ; *p != ‘\0’, ++p) { As long as the value of what p is pointing to is not equal to null character, the body of the for loop is executed.

if (*p==‘e’) If the value of what p is pointing to is equal to ‘e’, *p=‘E’; then the value in memory is changed to ‘E’g

if(*p==‘ ‘) If the value of what p is pointing to is equal to ‘ ’, *p=‘\n’; then the value in memory is changed to ‘\n’

}

C Programming Lecture Notes50

Page 51: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn file abc.c

Code Commentsprintf(“%s\n”, s); The variable s is printed int the format of string

return 0;

}

C Programming Lecture Notes51

Page 52: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn file abc.c

Output Commentsabc ABC GHBC

she sells sea shElls

by

thEt

sEashorE

C Programming Lecture Notes52

Page 53: C Programming Ch1

Chapter 1: An Overview of C

Arrays, Strings, and PointersArrays, Strings, and PointersIn 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 p yelements 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 because is a constant pointer, the expression s++ is wrong. The value of s cannot be p , p gchanged. The are eqivalents[i]=*(s+i)

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

C Programming Lecture Notes53

Page 54: C Programming Ch1

Chapter 1: An Overview of C

FilesFilesTo open the file named my_file, the following code may be used:In file read_it.c#include <stdio h>#include <stdio.h>

int main(void){

int c;FILE *ifFILE *ifp;ifp=fopen(“my_file”,”r”);.....

}

*ifp: infile pointer to be a pointer to FILEThe function fopen() is in the standard library, and its function prototype is in stdio.hThe first argument is the name of fileSecond argument is the mode in which the file is to be opened

r: for read

C Programming Lecture Notes54

Page 55: C Programming Ch1

Chapter 1: An Overview of C

FilesFilesSecond argument is the mode in which the file is to be opened

r: for readw: for writea: for append

#include <stdio.h>

int main(argc, char argv[])

argc: argument countargv: argument vectorIt is an array of pointers to char. Such an array can be thought of as an array of t i Th i l t f i t t i d i th d strings. The successive elements of array points to successive words in the command

line that was used to execute the prograThus, 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 Suppose we have written our program and have put the executable code in file cnt_letters

cnt_letters chapter1 data1cnt_letters chapter2 data2

C Programming Lecture Notes55

Page 56: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn 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);

}

C Programming Lecture Notes56

Page 57: C Programming Ch1

Chapter 1: An Overview of C

Arrays Strings and PointersArrays, Strings, and PointersIn file abc.c

Code Commentsifp=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;

}

C Programming Lecture Notes57

Page 58: C Programming Ch1

Chapter 1: An Overview of C

END OF CHAPTER 1END OF CHAPTER 1

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

C Programming Lecture Notes58