You are on page 1of 25

C Programming

C Programming
Introduction and Basics C History

Why use C?
Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities

C provides
Efficiency, high performance and high quality s/ws Flexibility and power Many high-level and low-level operations Stability and small size code
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 1

Provide functionality through rich set of function libraries Gateway for other professional languages like C , C++, Java SOFTWARE DEVELOPMENT METHOD Requirement Specification Problem Definition Develop Algorithm

Implementation Write Code

Analysis Refine, Generalize, Decompose the problem definition

Verification and Testing Test and Debug the code

Design

General Format
{ Variable declaration Function calls/statements } Function definition Preprocessor directives Global variable declaration Global Function declaration void main()

Basics #include <stdio.h> void main() { printf(Hello, world!\n); }

Pieces of C
Types and Variables Definitions of data in memory Expressions

Arithmetic, logical, and assignment operators in an infix Notation Statements Sequences of conditional, iteration, and branching instructions
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 2

Functions Groups of statements and variables invoked recursively

Data Types
The Data Type families are Integer Family Storage Classes Extern Static Char Short Register Auto Integer Family Float Family Float Family Float double Int long

Type Casting Type casting is used when u want to convert the value of one data type to another Type casting doesnt change the actual value of the variable Type casting is done using a cast operator. C operators Arithmetic operators Unary operators Binary operators Equalities and relational operators Logical operators Conditional operator

Assignment operators

Arithmetic Operators
There are 2 types of arithmetic operators in C: unary operators - operators that require only one operand. binary operators - operators that require two operands. Unary Operator C Operation Positive Negative
Email: info@desti-group.com

Operator + -

Example a +=3 b -=a


www.desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

Page 3

Increment ++ Decrement -The first assigns positive 3 to a

i++ i--

The second assigns the negative value of a to b. i++ is equivalent to i = i + 1 i-- is equivalent to i = i-1

PRE- / POST-Increment
It is also possible to use ++i and --i instead of i++ and i-However, the two forms have a slightly yet important difference.

Binary Operators
C Operation Operator Example: Addition + a+3 Subtraction a-6 Multiplication * a*b Division / a/c Modulus % a%x The division of variables of type int will always produce a variable of type int as the result. You could only use modulus (%) operation on int variables.

Assignment Operators

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 4

Precedence Rules Precedence rules come into play when there is a mixed of arithmetic operators in one statement. For example: x = 3 * a - ++b%3; The rules specify which of the operators will be evaluated first. Precedence 1 (highest) 2 3 4 5 (lowest) Equality Operators: Operator == != Relational Operators: Operator > < >= <= Operator Associatively Level () left to right unary right to left * / % left to right + left to right = += -= *= /= %= right to left Example x == y x != y Example x>y x<y x >= y x <= y Meaning x is equal to y x is not equal to y Meaning x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

Logical Operators Logical operators are useful when we want to test multiple conditions. There are 3 types of logical operators and they work the same way as the boolean AND, OR and NOT operators. && - Logical AND All the conditions must be true for the whole expression to be true. Example: if (a == 10 && b == 9 && d == 1) means the if statement is only true when a == 10 and b == 9 and d == 1. || - Logical OR The truth of one condition is enough to make the whole expression true. Example: if (a == 10 || b == 9 || d == 1) means the if statement is true when either one of a, b or d has the right value. ! - Logical NOT (also called logical negation) Reverse the meaning of a condition
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 5

Example: if (!(points > 90)) means if points not bigger than 90

Conditional Operator cont


Example 1: if/else statement: if (total > 60) grade = P else grade = F; conditional statement: total > 60 ? grade = P: grade = F; OR grade = total > 60 ? P: F;

Conditional Operator cont


Example 2: if/else statement: if (total > 60) printf(Passed!!\n); else printf(Failed!!\n); Conditional Statement: printf(%s!!\n, total > 60? Passed: Failed);

Arrays in C
Definition Array A collection of objects of the same type stored contiguously in memory under one name May be type of any kind of variable May even be collection of arrays!

For ease of access to any member of array For passing to functions as a group

Examples int A[10] double B[20]


Email: info@desti-group.com

An array of ten integers A[0], A[1], , A[9]

An array of twenty long floating point numbers


Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 6

B[0], B[1], , B[19]

Arrays of structs, unions, pointers, etc., are also allowed Array indexes always start at zero in C int C[] An array of an unknown number of integers (allowable in a parameter of a function) C[0], C[1], , C[max-1]

int D[10][20]

An array of ten rows, each of which is an array of twenty integers D[0][0], D[0][1], , D[1][0], D[1][1], , D[9][19] Not used so often as arrays of pointers

Array Element May be used wherever a variable of the same type may be used Examples: A[3] = x + y; x = y A[3]; z = sin(A[i]) + cos(B[j]); Generic form: ArrayName[integer-expression] ArrayName[integer-expression] [integer-expression] In an expression (including arguments) On left side of assignment

Same type as the underlying type of the array Definition: Array Index the expression between the square brackets

Array elements are commonly used in loops

NOTES It is the programmers responsibility to avoid indexing off the end of an array
Email: info@desti-group.com

Likely to corrupt data


Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 7

May cause a segmentation fault Could expose system to a security hole!

C does NOT check array bounds I.e., whether index points to an element within the array Might be high (beyond the end) or negative (before the array starts)

Declaring Arrays Static or automatic Array size determined explicitly or implicitly Array size may be determined at run-time Automatic only Not in textbook

Outside of any function always static

Static Data Allocation

Inside function or compound statement usually automatic

Array Initialization int A[5] = {2, 4, 8, 16, 32}; Page 8

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Static or automatic

int B[20] = {2, 4, 8, 16, 32}; Unspecified elements are guaranteed to be zero

int C[4] = {2, 4, 8, 16, 32}; Error compiler detects too many initial values

int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n}; Automatically only; array initialized to expressions

int E[n] = {1}; gcc, C99, C++ Dynamically allocated array (automatic only). Zeroth element initialized to 1; all other elements initialized to 0

Implicit Array Size Determination int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; Array is created with as many elements as initial values In this case, 12 elements

Values must be compile-time constants (for static arrays) Values may be run-time expressions (for automatic arrays) Getting Size of Implicit Array sizeof operator returns # of bytes of memory required by operand Examples: sizeof (int) # of bytes per int sizeof (float) # of bytes per float sizeof days # of bytes in array days (previous slide) # of elements in days = (sizeof days)/sizeof(int)

Must be able to be determined at compile time Dynamically allocated arrays not supported Page 9

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Pointers in C
What is a pointer? Syntax : int *ptr; int *ptr; ptr is the name of our variable (just as k was the name of our integer variable). The '*' informs the compiler that we want a pointer variable, i.e. to set aside however many bytes is required to store an address in memory. The int says that we intend to use our pointer variable to store the address of an integer. Such a pointer is said to "point to" an integer. Now ptr has no value, that is we haven't stored an address in it in the above declaration. A pointer initialized in this manner is called a "null" pointer. ** The actual bit pattern used for a null pointer may or may not evaluate to zero since it depends on the specific system on which the code is written.

NULL Macro and Pointer validation To make the source code compatible between various compilers on various systems, a macro is used to represent a null pointer. The macro goes under the name NULL. Setting the value of a pointer using the NULL macro, as with an assignment statement such as ptr = NULL; guarantees that the pointer has become a null pointer. Validation of pointer can be done just as one can test for an integer value of zero, if(k == 0), we can test for a null pointer using if (ptr == NULL). Be aware that "nul" is not the same as "NULL". The null refers to a zero as defined by the escape sequence '\0'. It occupies one byte of memory. NULL, on the other hand, is the name of the macro

How to use ptr?

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 10

Pointer types and Arrays

More on pointers
Pointers Arithmetic Address + Number= Address
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556

Address - Number= Address Address++ = Address


www.desti-group.com

Page 11

Address-- = Address ++Address = Address

Illegal arithmetic Address + Address=Illegal Address * Address=Illegal Address / Address=Illegal Address % Address=Illegal

--Address = Address

Multidimensional Arrays char [10]; The name multi[5] is itself an array indicating that there are 5 elements each being an array of 10 characters. Hence we have an array of 5 arrays of 10 characters each. In memory, it might look as if it had been formed by initializing 5 separate arrays.

multi[0] = {'0','1','2','3','4','5','6','7','8','9'} multi[1] = {'a','b','c','d','e','f','g','h','i','j'} multi[2] = {'A','B','C','D','E','F','G','H','I','J'} multi[3] = {'9','8','7','6','5','4','3','2','1','0'} multi[4] = {'J','I','H','G','F','E','D','C','B','A'} Accessing Multidimensional array content

Individual elements might be addressable using syntax such as: multi[0][3] = 3 multi[1][7] = 'h' multi[4][0] = J

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 12

multi + 1 is the address of the 'a' in the 2nd row. It adds 10, the number of columns, to get this location. If we were dealing with integers and an array with the same dimension the compiler would add 10*sizeof(int). Thus, the address of the 9 in the 4th row would be &multi[3][0] or *(multi + 3) in pointer notation. To get to the content of the 2nd element in the 4th row we add 1 to this address and dereference the result as. *(*(multi + 3) + 1) With a little thought we can see that: *(*(multi + row) + col) and multi[row][col] yield the same results. *(*(multi + row)+col) Vs multi[row][col] To evaluate either expression, a total of 5 values must be known: The address of the first element of the array, which is returned by the expression multi, i.e., the name of the array. The size of the type of the elements of the array, in this case sizeof(int). The 2nd dimension of the array. The specific index value for the first dimension, row in this case. The specific index value for the second dimension, col in this case.

Strings in C Characters in C

char is a one-byte data type capable of holding a character Treated as an arithmetic integer type (Usually) unsigned

May be used in arithmetic expressions Add, subtract, multiply, divide, etc.

Character constants 'a', 'b', 'c', 'z', '0', '1', '9', '+', '-', '=', '!', '~', etc, '\n', '\t', '\0', etc.
Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Email: info@desti-group.com

Page 13

A-Z, a-z, 0-9 are in order, so that arithmetic can be done

Strings in C
Definition: A string is a character array ending in '\0' i.e., char s[256]; char t[] = "This is an initialized string!"; char *u = "This is another string!"; String constants are in double quotes May contain any characters Including \" and \' see p. 38, 193 of K&R

String constants may not span lines However, they may be concatenated e.g.,

"Hello, " "World!\n" is the same as "Hello, World!\n" Let char *u = "This is another string!";

Then u[0] == 'T' u[1] == 'h' u[2] == 'i' u[21] == 'g' u[22] == '!' u[23] == '\0'

Support for Strings in C Most string manipulation is done through functions in <string.h> Examples: int strlen(char *s) returns length of string
Email: info@desti-group.com

String functions depend upon final '\0' So you dont have to count the characters!

Excluding final '\0'


Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 14

char* strcpy(char *s, char *ct) Copies string ct to string s, return s s must be big enough to hold contents of ct ct may be smaller than s

int strcmp(char *s, char *t) lexically compares s and t, returns <0 if s < t, >0 if s > t, zero if s and t are identical

char* strcat(char *s, char *ct) Concatenates string ct to onto end of string s, returns s s must be big enough to hold contents of both strings!

Other string functions strchr(), strrchr(), strspn(), strcspn() strpbrk(), strstr(), strtok(), Definition The Heap A region of memory provided by most operating systems for allocating storage not in Last in, First out discipline I.e., not a stack Must be explicitly allocated and released

May be accessed only with pointers Remember, an array is equivalent to a pointer Many hazards to the C programmer

Static Data Allocation

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 15

Allocating Memory in The Heap See <stdlib.h> void *malloc(size); void free(void *ptr); void *calloc(size_t nmemb, size_t size); malloc() allocates size bytes of memory from the heap and returns a pointer to it. NULL pointer if allocation fails for any reason

free() returns the chunk of memory pointed to by ptr Must have been allocated by malloc or calloc

Notes calloc() is just a variant of malloc() malloc() is analogous to new in C++ and Java new in C++ actually calls malloc()

free() is analogous to delete in C++ delete in C++ actually calls free() Java does not have delete uses garbage collection to recover memory no longer in use

Definition Memory Leak The steady loss of available memory due to forgetting to free() everything that was malloced. Bug-a-boo of most large C and C++ programs

If you forget the value of a pointer to a piece of malloced memory, there is no way to find it again! Killing the program frees all memory!

Functions in C
Modularize a program Benefits of functions Divide and conquer
Email: info@desti-group.com

Manageable program development


Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 16

Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions)

Avoid code repetition

Library function: The library function is not required to be written by us. Eg: printf scanf strcmp strlen malloc free etc..

User defines function: This function has to be developed by the user at the time of writing a program. Eg: main() main is specially used function in C. Every program must have main function to indicate, where the program begins its execution. When a program is large and complex then the result of debugging testing and maintaining becomes difficult.

The 3 aspects of functions are: 1. The Function Declaration also called Prototype 2. The function Definition
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 17

3. The Function Invocation or calling Statement Function Declaration In C user- written functions should normally be declared prior to its use to allow compiler to perform type checking on arguments used in its call statement. The general form is: Return_data_type function_name (data_type Var_name, ..); Function name: this is the name given to the function. It follows the same naming convention as that of any valid variable in C. Return data type: this specifies the type of data given back to the calling construct. Data type list: this list specifies the data type of each variables, the values of which are expected to be transmitted to the function. These variables are known as formal parameters. It is possible not to declare functions prior to the use but the error checking will not be performed. ; is required at the end of function declaration. E.g. int FindMax(int x, int y);

Function Definition The collection of program statements that does specific tasks done by the function is called the function definition. It consist of function header: and function body. variables defined inside the function are local variables Parameters to a functions can be considered as local variables Function Invocation or function call The function is called from the main() The function can in turn call another function. The function call statements invoke the function, which means the program control passes to that function. Once the function completes its task, the program control is passed back to the calling environment. Av = getAverage(10, 20, 30);
Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Email: info@desti-group.com

Page 18

Av = getAverage(v1, v2,v3); Av =getAverage(10,v1,v2); var_name=function_name(var1, var2,..);

Classification of Functions Functions that will not take any arguments and also returns none Functions that will not take any arguments and returns some value Functions that takes one or more arguments but returns none Functions that take one or more arguments and returns some value

NOTES The function name and the type and number of arguments must match with that of the function declaration statement and the header of the function definition. Arguments present in the form of expression are evaluated and converted to the type of formal parameters at the beginning of the body of the function.

Passing of arguments to the function 1. Call by value or pass by value: 1. When arguments are passed by values this means that local copies of the values of the arguments are passed to the function. 2. Call by reference or pass by reference. 1. The address of the variable is passed as value of parameters to the function. Passing arrays to functions Arrays can also be the arguments of function Only the base address of the array is passed to the function Hence the passing of arguments is done by reference. When arrays are passed as arguments then actual contents of the arrays is altered.

Structures and Unions


Definition Structure A collection of one or more variables, typically of different types, grouped together under a single name for convenient handling Known as struct in C and C++
Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Email: info@desti-group.com

Page 19

Struct
Defines a new type E.g., I.e., a new kind of data type that compiler regards as a unit

struct motor { float volts; //voltage of the motor float amps; //amperage of the motor int phases; //# of phases of the motor float rpm; //rotational speed of motor }; //struct motor Declaring struct variables struct motor p, q, r; Declares and sets aside storage for three variables p, q, and r each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; Declares a pointer to an object of type struct motor Accessing Members of a struct Let struct motor p; struct motor q[10]; Then p.volts is the voltage p.amps is the amperage p.phases is the number of phases p.rpm is the rotational speed q[i].volts is the voltage of the ith motor q[i].rpm is the speed of the ith motor Accessing Members of a struct (continued) Let struct motor *p; Then (*p).volts is the voltage of the motor pointed to by p Page 20

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

(*p).phases

is the number of phases of the motor pointed to by p The (*p).member notation is a nuisance Clumsy to type; need to match ( ) Too many keystrokes This construct is so widely used that a special notation was invented, i.e.,

p->member, where p is a pointer to the structure Previous Example Becomes Let Then p -> volts p -> phases Operations on struct Copy/assign struct motor p, q; p = q; Get address struct motor p; Remember: Passing an argument by value is an instance of copying or assignment Passing a return value from a function to the caller is an instance of copying or assignment Initialization of a struct Let struct motor { float volts; float amps; int phases; float rpm; }; //struct motor is the voltage of the motor pointed to by p is the number of phases of the motor pointed to by p struct motor *p;

struct motor *s s = &p; Access members p.volts; s -> amps;

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 21

Then struct motor m = {208, 20, 3, 1800}; initializes the struct

Typedef
Definition: a typedef is a way of renaming a type E.g., typedef struct motor Motor; Motor m, n; Motor *p, r[25]; Motor function(const Motor m; ); typedef may be used to rename any type Convenience in naming Clarifies purpose of the type E.g., typedef char *String; E.g., typedef int size_t; typedef long int32; typedef long long int64; Cleaner, more readable code Portability across platforms

Unions
A union is like a struct, but only one of its members is stored, not all I.e., a single variable may hold different types at different times Storage is enough to hold largest member Members are overlaid on top of each other

Union Syntax Union [union-type-name] { typevariable-names; typevariable-names;... }[unionvariable];

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 22

Difference between Structure & Union Structure A structure allocates the total size of all elements in it. Members inside a structure are always stored in separate memory locations throughout the life time and scope of the entire structure. Manipulations of one member will not affect the values of any of the others in any way unless they are operated on in code to do so. The keyword struct is used to declare a structure All data members in a structure are active at time Union

A union only allocates as much memory as its larges element(member) requires.

The union will store one and only one actual value fo one element at a time.

If another element is stored before the first is retrieve the first stored value is lost. The keyword union is used to declare an union. Only one data member is active at a time

unions are used much less frequently than structs mostly in the inner details of operating system in device drivers in embedded systems where you have to access registers defined by the hardware

FILE OPERATORS
What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. Buffers A buffer is a special work area that holds data as the computer transfers them to/from memory. Buffers help to synchronize data the physical devices with the program.

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 23

The physical requirements of the devices can deliver more data for input than a program can use at any one time. The buffer handles the overflow data until a program can use it. Moreover, the buffer also holds data until it is efficient to write that data to the storage device for output. File Information Table A program requires several pieces of information about a file, including the name the OS uses for it, the position of the current character, etc. C uses a structure called FILE (defined in stdio.h) to store the attributes of a file. Streams In C, we input/output data using streams. We can associate a stream with a device (i.e. the terminal) or with a file. C supports two types of files Text Stream Files Binary Stream Files Text Streams & Binary Streams Text streams consist of sequential characters divided into lines. Each line terminates with the newline character (\n). Binary streams consist of data values such as integers, floats or complex data types, using their memory representation. Files & Streams A file is an independent entity with a name recorded by the operating system. A stream is created by a program. To work with a file, we must associate our stream name with the file name recorded by the OS. Steps in Processing a File 1. Create the stream via a pointer variable using the FILE structure: FILE* spData; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file
Email: info@desti-group.com Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com

Page 24

System-Created Streams C automatically creates three streams that it opens and closes automatically for us in order to communicate with the terminal: stdin stdout stderr

We cannot re-declare these streams in our programs. File Open The file open function (fopen) serves two purposes: It makes the connection between the physical file and the stream. It creates a program file structure to store the information C needs to process the file. Syntax: fopen(filename, mode); More On fopen The file mode tells C how the program will use the file. The filename indicates the system name and location for the file. We assign the return value of fopen to our pointer variable: spData = fopen(MYFILE.DAT, w); spData = fopen(A:\\MYFILE.DAT, w); File Open Modes

Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. To close a file, we use fclose and the pointer variable: fclose(spData);

Email: info@desti-group.com

Call: +91-800 822 5556, +91-800 833 5556

www.desti-group.com

Page 25

You might also like