An Introduction to C Programming How to Write

  • Slides: 57
Download presentation
An Introduction to C Programming

An Introduction to C Programming

How to Write and Compile C Programs n n n C, C++ and Java

How to Write and Compile C Programs n n n C, C++ and Java Compilers: Microsoft Visual C++, GCC, Borland C Since we will be working on PCs: n Microsoft Visual C++ n n Open new Win 32 Console Application Name it (in “project name”) Click “a hello world application” Go to file view, source files, then the name of your project. cpp

Some Things About C n n Case matters, white space does not Comments go

Some Things About C n n Case matters, white space does not Comments go between /* and */ Each statement is followed by a semicolon Execution begins in the main function: int main(int argc, char* argv[]) { /* ignore this */ /* start here */ return 0; /*end here */ }

What are C libraries? n n C is a lightweight language. Most of its

What are C libraries? n n C is a lightweight language. Most of its intelligence is compartmentalized in libraries. Almost all c programs use the “stdio” or standard input/output library. Many also use the “math” library. To use a library, include the header file (I. e. , “stdio. h”) at the top of the file. For most special purpose libraries (I. e. , math) you need to include the library on the link line. In Visual C++, go to project->settings>object/module libraries.

C Variable Types n n n The most common types are: char, int, float,

C Variable Types n n n The most common types are: char, int, float, and double. Strings are arrays of characters (we’ll cover arrays later). Declare a variable before you use it: int x; /* declares an integer called x. Its value is not assigned. */ float y, z = 3. 14159; /* declares two floating point numbers. z is set equal to pi */ z = 4; /* now z is equal to 4 */ my. Val = 2; /* This would be an error, because my. Val was not yet declared */

Logical Operators n n C defines these logical operators: <, >, <=, >= and

Logical Operators n n C defines these logical operators: <, >, <=, >= and == (the equivalence operator) You can compare any variable. Characters are compared based on their ASCII values. All answers will be true (not zero) or false (0) You can extend the logic with && (and), ~ (not) and || (or).

The If Statement n n n Syntax: if (expression) statement; If the expression is

The If Statement n n n Syntax: if (expression) statement; If the expression is true (not zero), the statement is executed. If the expression is false, it is not executed. You can group multiple expressions together with braces: if (expression) { statement 1; statement 2; statement 3; }

The If/Else Statement n n Syntax: if (expression) statement_1; else statement_2; If the expression

The If/Else Statement n n Syntax: if (expression) statement_1; else statement_2; If the expression is true, statement_1 will be executed, otherwise, statement_2 will be. if (my. Val < 3) printf(“my. Val is less than 3. n”); else printf(“my. Val is greater than or equal to 3. n”);

The For Loop n n Syntax: for (initialization; test; increment) {statements; } The for

The For Loop n n Syntax: for (initialization; test; increment) {statements; } The for loop will first perform the initialization. Then, as long is test is TRUE, it will execute statements. After each execution, it will increment. for (cntr = 0; cntr < 3; cntr = cntr + 1) { printf(“ Counter = %dn”, cntr); } Counter = 0; Counter = 1; Counter = 2;

Functions n n n Any non-trivial program will have multiple functions C functions look

Functions n n n Any non-trivial program will have multiple functions C functions look like methods in Java Functions have return types n n int, float, void, etc. Functions have unique names Functions have parameters passed into them Before a function can be used, it must be declared and/or defined n n a function declaration alone is called a prototypes can be in a separate header file or included in the file their definition appears in

Function Example #include <stdio. h> #define PI 3. 14 float calc. Area(float); // prototype

Function Example #include <stdio. h> #define PI 3. 14 float calc. Area(float); // prototype for function to be defined later int main() { float radius, area; printf(“Enter radius of a circle: “); scanf(“%f”, &radius); area = calc. Area(radius); // call function printf(“Area of circle with radius %f is: %fn”, radius, area); return 0; } float calc. Area(float radius) { return PI * radius; }

Arrays n Like Java, C has arrays n n n they are declared slightly

Arrays n Like Java, C has arrays n n n they are declared slightly different indexes still go from 0 to size-1 C arrays have some major differences from Java n n if you try to access an index outside of the array, C will probably let you C arrays are kept on the stack n n this limits the maximum size of an array size of a C array must be statically declared n no using variables for the size

Declaring Arrays n Legal array declarations int scores[20]; #define MAX_LINE 80 char line[MAX_LINE]; //

Declaring Arrays n Legal array declarations int scores[20]; #define MAX_LINE 80 char line[MAX_LINE]; // place 80 inside [ ] at compile time n Illegal array declaration int x = 10; float nums[x]; // using variable for array size

Initializing Arrays n Legal initializations int scores[5] = { 2, -3, 10, 0, 4

Initializing Arrays n Legal initializations int scores[5] = { 2, -3, 10, 0, 4 }; char name[20] = { “Jane Doe” }; int totals[5]; int i; for(i=0; i<5; i++) totals[i] = 0; char line[MAX_LINE]; scanf(“%s”, line); n Illegal initialization int scores[5]; scores = { 2, -3, 10, 0, 4 };

More on Arrays n Accessing arrays n no . length parameter in array n

More on Arrays n Accessing arrays n no . length parameter in array n remember, no bounds checking n Using arrays in functions n n arrays can be passed as parameters to functions arrays are always passed-by-reference n the address of the first element is passed n any changes made to array in the called function are seen in the calling function n this is the difference from pass-by-value

Array Example #include <stdio. h> #define NUM_STUDENTS 70 void set. Nums(int nums[], int size)

Array Example #include <stdio. h> #define NUM_STUDENTS 70 void set. Nums(int nums[], int size) { int i; for(i=0; i<size; i++) { printf(“Enter grade for student %d: “, i); scanf(“%d”, &nums[i]); } } int main() { int grades[NUM_STUDENTS]; set. Nums(grades, NUM_STUDENTS); return 0; }

Strings n n In C, strings are just an array of characters Because strings

Strings n n In C, strings are just an array of characters Because strings are so common, C provides a standard library for dealing with them n to use this library, include the following: n n n #include <string. h> This library provides means of copying strings, counting characters in string, concatenate strings, compare strings, etc. By convention, all strings are terminated by the null character ( ) n regardless of the size of the character array holding the string

Common String Mistakes n C does not allow standard operators to be used on

Common String Mistakes n C does not allow standard operators to be used on strings n str 1 < str 2 does not compare the two strings n it n does compare the starting address of each string str 1 == str 2 does not return true if the two strings are equal n it only returns true if the starting address of each string is the same n str 3 = str 1 + str 2 does not combine the two strings and store them in the third n it adds the starting addresses of each string

Common String Functions n int strlen(char str[]); n n int strcpy(char str. To[], char

Common String Functions n int strlen(char str[]); n n int strcpy(char str. To[], char str. From[]); n n n copies the string in str. From to the string in str. To make sure str. To is at least as big as str. From int strcat(char str. To[], char str. From); n n n counts the number of characters up to (but not counting) the null character and returns this number copies the string in str. From to the end of str. To again, make sure str. To is large enough to hold additional chars int strcmp(char str 1[], char str 2[]); n n compares string 1 to string 2 return values are as follows n n n less than 0 if str 1 is lexicographically less than str 2 0 if str 1 is identical to str 2 greater than 0 if str 1 is lexicographically greater than str 2

Structures n n C does not have classes However, C programmers can create their

Structures n n C does not have classes However, C programmers can create their own data types n n called structures Structures allow a programmer to place a group of related variables into one place

Creating a Structure n n Use the keyword struct to create a structure Example

Creating a Structure n n Use the keyword struct to create a structure Example of creating a structure struct foo { char student[30]; int grades[7]; float ending. Grade; }; n n Variables can now be created of the type struct foo Example of creating a structure variable int main() { struct foo my. Struct; … n Notice that the struct keyword is part of the new data type name

Using Structures n To access any of the member variables inside the structure: n

Using Structures n To access any of the member variables inside the structure: n n use the structure variable name, a period, and the member variable name When passed to a function, a structure is passed by value n just like any other data type

Example Using Structures int main() { struct foo my. Struct; strcpy(my. Struct. student, “John

Example Using Structures int main() { struct foo my. Struct; strcpy(my. Struct. student, “John Doe”); for(i=0; i<7; i++) my. Struct. grades[i] = 0; my. Struct. end. Grade = 0; }

Pointers n n n 24 Powerful, but difficult to master Simulate call-by-reference Close relationship

Pointers n n n 24 Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings

Pointer Variable Definitions and Initialization n Pointer variables n n 25 Contain memory addresses

Pointer Variable Definitions and Initialization n Pointer variables n n 25 Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain address of a variable that has a specific value (indirect reference) Indirection – referencing a pointer value

Simple Pointers n n Pointer is a value that points to a location in

Simple Pointers n n Pointer is a value that points to a location in the memory Pointer is associated with a type n n n 26 int number ; int * ptr_to_num ; 23 number = 23; ptr_to_num = & number; printf("Value is %d n", (*ptr_to_num) ); 003 F 45 A 8 ptr_to_num

More Pointers n n int number ; int * p 1, * p 2;

More Pointers n n int number ; int * p 1, * p 2; number n p 1 = & number ; number = 23; p 2 = & number ; printf(" *p 1 = %d *p 2 = %d ", *p 1, *p 2); n /* Output ? ? */ n n n 27 p 2

Pointers and Arrays n char str[32]; char *ptr; n ptr = str ; n

Pointers and Arrays n char str[32]; char *ptr; n ptr = str ; n strcpy( str, "test" ); strcpy( ptr, "test" ); n n 28 /* does the same as above */

Pointers and Arrays n int table [8]; int *ptr ; n ptr = table

Pointers and Arrays n int table [8]; int *ptr ; n ptr = table ; n table [ 4 ] = 94; *( ptr + 4 ) = 94; n n n How about 29 94 table ptr ( ptr + 4 )

Pointer operations n n n n Can add and subtract numbers (like array indices)

Pointer operations n n n n Can add and subtract numbers (like array indices) Can increment and decrement! char str[] = "Test"; char * p ; int i; for( p = str, i=0; *p != ''; p++, i++); printf(" The length of the string is %d ", i); 30

n A way to tell that pointer points to nothing NULL pointer n n

n A way to tell that pointer points to nothing NULL pointer n n void main() { char *msg = NULL; My. Print( msg ); n n n } n void My. Print( char * txt ) { if ( txt == NULL ) printf( "Invalid parameters: NULL pointer receivedn"); else printf( "%sn", txt ); } n n n 31

n Command Line Arguments /* My. Prog. c */ n int main ( int

n Command Line Arguments /* My. Prog. c */ n int main ( int argc , char *argv[] ) {. . . n > my. Prog one two three n argc = 4 argv[0] = "my. Prog" argv[1] = "one" argv[2] = "two" argv[3] = "three“ argv[4] = NULL n n n 32

7. 3 Pointer Operators n & (address operator) n Returns address of operand int

7. 3 Pointer Operators n & (address operator) n Returns address of operand int y = 5; int *y. Ptr; y. Ptr = &y; /* y. Ptr gets address of y */ y. Ptr “points to” y 33

Fig. 7. 2 | Graphical representation of a pointer pointing to an integer variable

Fig. 7. 2 | Graphical representation of a pointer pointing to an integer variable in memory. 34

Fig. 7. 3 | Representation of y and y. Ptr in memory. 35

Fig. 7. 3 | Representation of y and y. Ptr in memory. 35

File Handling in C

File Handling in C

Introduction n Files are places where data can be stored permanently. Some programs expect

Introduction n Files are places where data can be stored permanently. Some programs expect the same set of data to be fed as input every time it is run. n Cumbersome. n Better if the data are kept in a file, and the program reads from the file. Programs generating large volumes of output. n Difficult to view on the screen. n Better to store them in a file for later viewing/ processing Jaypee Institute of Information Technology University, Noida

Introduction n Data files n n n When you use a file to store

Introduction n Data files n n n When you use a file to store data for use by a program, that file usually consists of text (alphanumeric data) and is therefore called a text file. Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data n Storage of data in variables and arrays is only temporary Jaypee Institute of Information Technology University, Noida

Files and Streams n C views each file as a sequence of bytes n

Files and Streams n C views each file as a sequence of bytes n n File ends with the end-of-file marker Stream created when a file is opened n n Provide communication channel between files and programs Opening a file returns a pointer to a FILE structure Jaypee Institute of Information Technology University, Noida

Basic File Operations n n Opening a file Reading data from a file Writing

Basic File Operations n n Opening a file Reading data from a file Writing data to a file Closing a file Jaypee Institute of Information Technology University, Noida

Opening a File n A file must be “opened” before it can be used.

Opening a File n A file must be “opened” before it can be used. FILE *fp; n n : fp = fopen (filename, mode); fp is declared as a pointer to the data type FILE. filename is a string - specifies the name of the file. fopen returns a pointer to the file which is used in all subsequent file operations. mode is a string which specifies the purpose of opening the file: “r” : : open the file for reading only “w” : : open the file for writing only “a” : : open the file for appending data to it Jaypee Institute of Information Technology University, Noida

MODES n r - open a file in read-mode, set the pointer to the

MODES n r - open a file in read-mode, set the pointer to the beginning of the file. n w - open a file in write-mode, set the pointer to the beginning of the file. n a - open a file in write-mode, set the pointer to the end of the file. n rb - open a binary-file in read-mode, set the pointer to the beginning of the file. n wb - open a binary-file in write-mode, set the pointer to the beginning of the file. n ab - open a binary-file in write-mode, set the pointer to the end of the file. n r+ - open a file in read/write-mode, if the file does not exist, it will not be created. n w+ - open a file in read/write-mode, set the pointer to the beginning of the file. n a+ - open a file in read/append mode. n r+b - open a binary-file in read/write-mode, if the file does not exist, it will not be created. n w+b - open a binary-file in read/write-mode, set the pointer to the beginning of the file. n a+b - open a binary-file in read/append mode. Jaypee Institute of Information Technology University, Noida

Contd. n Points to note: n n n Several files may be opened at

Contd. n Points to note: n n n Several files may be opened at the same time. For the “w” and “a” modes, if the named file does not exist, it is automatically created. For the “w” mode, if the named file exists, its contents will be overwritten. Jaypee Institute of Information Technology University, Noida

Examples FILE *in, *out ; in = fopen (“mydata. dat”, “r”) ; out =

Examples FILE *in, *out ; in = fopen (“mydata. dat”, “r”) ; out = fopen (“result. dat”, “w”); FILE *empl ; char filename[25]; scanf (“%s”, filename); empl = fopen (filename, “r”) ; Jaypee Institute of Information Technology University, Noida

Closing a File n After all operations on a file have been completed, it

Closing a File n After all operations on a file have been completed, it must be closed. n n Ensures that all file data stored in memory buffers are properly written to the file. General format: fclose (file_pointer) ; FILE *xyz ; xyz = fopen (“test. txt”, “w”) ; ……. fclose (xyz) ; Jaypee Institute of Information Technology University, Noida

Contd n fclose( FILE pointer ) n Closes specified file n Performed automatically when

Contd n fclose( FILE pointer ) n Closes specified file n Performed automatically when program ends n Good practice to close files explicitly n system resources are freed. n Also, you might not find that all the information that you've written to the file has actually been written to disk until the file is closed. n feof( FILE pointer ) n Returns true if end-of-file indicator (no more data to process) is set for the specified file Jaypee Institute of Information Technology University, Noida

Files and Streams n Read/Write functions in standard library n getc n Reads one

Files and Streams n Read/Write functions in standard library n getc n Reads one character from a file n Takes a FILE pointer as an argument n fgetc( stdin ) equivalent to getchar() n putc n Writes one character to a file n Takes a FILE pointer and a character to write as an argument n fputc( 'a', stdout ) equivalent to putchar( 'a' ) n scanf / fprintf n File processing equivalents of scanf and printf Jaypee Institute of Information Technology University, Noida

Read/Write Operations on Files n n n The simplest file input-output (I/O) function are

Read/Write Operations on Files n n n The simplest file input-output (I/O) function are getc and putc. getc is used to read a character from a file and return it. char ch; FILE *fp; …. . ch = getc (fp) ; n getc will return an end-of-file marker EOF, when the end of the file has been reached. putc is used to write a character to a file. char ch; FILE *fp; …… putc (ch, fp) ; Jaypee Institute of Information Technology University, Noida

Example : : convert a text file to all UPPERCASE main() { FILE *in,

Example : : convert a text file to all UPPERCASE main() { FILE *in, *out ; char c ; in = fopen (“infile. dat”, “r”) ; out = fopen (“outfile. dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ; } Jaypee Institute of Information Technology University, Noida

Contd. n n We can also use the file versions of scanf and printf,

Contd. n n We can also use the file versions of scanf and printf, called fscanf and fprintf. General format: fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ; n Examples: fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ; fprintf (out, “n. The result is: %d”, xyz) ; Jaypee Institute of Information Technology University, Noida

Contd. fprintf n Used to print to a file n It is like printf,

Contd. fprintf n Used to print to a file n It is like printf, except first argument is a FILE pointer (pointer to the file you want to print in) Jaypee Institute of Information Technology University, Noida

n Some Points How to check EOF condition when using fscanf? n Use the

n Some Points How to check EOF condition when using fscanf? n Use the function feof if (feof (fp)) printf (“n Reached end of file”) ; n How to check successful open? n For opening in “r” mode, the file must exist. if (fp == NULL) printf (“n Unable to open file”) ; Jaypee Institute of Information Technology University, Noida

fread( ) and fwrite( ) size_t fread(void *buffer, size_t numbytes, size_t count, FILE *a_file);

fread( ) and fwrite( ) size_t fread(void *buffer, size_t numbytes, size_t count, FILE *a_file); size_t fwrite(void *buffer, size_t numbytes, size_t count, FILE *a_file); n n Buffer in fread is a pointer to a region of memory that will receive the data from the file. Buffer in fwrite() is a pointer to the information that will be written to the file. The second argument is the size of the element; it is in bytes. For example, if you have an array of characters, you would want to read it in one byte chunks, so numbytes is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you have a variable, int x; you can get the size of x with sizeof(x); Jaypee Institute of Information Technology University, Noida

Contd. . n n n The third argument is simply how many elements you

Contd. . n n n The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array The final argument is simply the file pointer Size_t is an unsigned integer. fread() returns number of items read and fwrite() returns number of items written To check to ensure the end of file was reached, use the feof function, which accepts a FILE pointer and returns true if the end of the file has been reached. Jaypee Institute of Information Technology University, Noida

Example: Merge two files #include <stdio. h> int main() { FILE *file. A, /*

Example: Merge two files #include <stdio. h> int main() { FILE *file. A, /* first input file */ *file. B, /* second input file */ *file. C; /* output file to be created */ int num 1, /* number to be read from first file */ num 2; /* number to be read from second file */ int f 1, f 2; /* Open file. A = file. B = file. C = files for processing */ fopen("class 1. txt", "r"); fopen("class 2. txt", "r"); fopen("class. txt", "w"); Jaypee Institute of Information Technology University, Noida

/* As long as there are numbers in both files, read and compare numbersone

/* As long as there are numbers in both files, read and compare numbersone by one. Write the smaller number to the output file and read the next number in the file from which the smaller number is read. */ f 1 = fscanf(file. A, "%d", &num 1); f 2 = fscanf(file. B, "%d", &num 2); while ((f 1!=EOF) && (f 2!=EOF)){ if (num 1 < num 2){ fprintf(file. C, "%dn", num 1); f 1 = fscanf(file. A, "%d", &num 1); } else if (num 2 < num 1) { fprintf(file. C, "%dn", num 2); f 2 = fscanf(file. B, "%d", &num 2); } else { /* numbs are equal: read from both files */ fprintf(file. C, "%dn", num 1); f 1 = fscanf(file. A, "%d", &num 1); f 2 = fscanf(file. B, "%d", &num 2); } } Jaypee Institute of Information Technology University, Noida

while (f 1!=EOF){/* if reached end of second file, read the remaining numbers from

while (f 1!=EOF){/* if reached end of second file, read the remaining numbers from first file and write to output file */ fprintf(file. C, "%dn", num 1); f 1 = fscanf(file. A, "%d", &num 1); } while (f 2!=EOF){ if reached the end of first file, read the remaining numbers from second file and write to output file */ fprintf(file. C, "%dn", num 2); f 2 = fscanf(file. B, "%d", &num 2); } } /* close files */ fclose(file. A); fclose(file. B); fclose(file. C); return 0; /* end of main */ Jaypee Institute of Information Technology University, Noida