Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability.

Similar presentations


Presentation on theme: "Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability."— Presentation transcript:

1

2 Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability of code, by breaking large file into smaller modules  Comments in C provides easy readability  C is a powerful language

3 PROGRAM STRCTURE IN C #include void main() { --other statements }

4 HEADER FILES The files that are specified in the include section is called as header file These are precompiled files that has some functions defined in them We can call those functions in our program by supplying parameters Header file is given an extension.h C Source file is given an extension.c

5 MAIN FUNCTION This is the entry point of a program When a file is executed, the start point is the main function From main function the flow goes as per the programmers choice. There may or may not be other functions written by user in a program Main function is compulsory for any c program

6 Sample program #include int main() { printf(“Hello”); return 0; } This program prints Hello on the screen when we execute it

7 HOW TO RUN C PROGRAM Type a program Save it Compile the program – This will generate an exe file (executable) Run the program (Actually the exe created out of compilation will run and not the.c file) In different compiler we have different option for compiling and running. We give only the concepts.

8 Points to remember Case Sensitive Case matters in C. A is not a Add plenty of comments (/* */ or //) Good layout, not: main() {printf("Hello World\n");} Use meaningful variable names Initialize your variables Use parentheses to avoid confusion: a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

9 DATA TYPES Primitive data types int, float, double, char Aggregate data types Arrays come under this category Arrays can contain collection of int or float or char or double data User defined data types Structures and enum fall under this category.

10 VARIABLES Variables are data that will keep on changing Declaration > >; int a; Definition >= >; a=10; Usage > a=a+1;//increments the value of a by 1

11 RULES FOR VARIBLE NAME Should not be a reserved word like int etc.. Should start with a letter or an underscore(_) Can contain letters, numbers or underscore. No other special characters are allowed including space Variable names are case sensitive A and a are different.

12 INPUT & OUTPUT Input scanf(“%d”,&a); Gets an integer value from the user and stores it under the name “a” Output printf(“%d”,a) Prints the value present in variable a on the screen

13 OPERATORS Arithmetic (+,-,*,/,%) Relational (, =,==,!=) Logical (&&,||,!) Bitwise (&,|) Assignment (=) Compound assignment(+=,*=,-=,/=,%=,&=,|=) Shift (right shift >>, left shift <<)

14 OPERATORS(Contd.) Increment and Decrement Operators ++ Increment operator -- Decrement Operator k++ or k-- (Post-increment/decrement) k = 5; x = k++; // sets x to 5, then increments k to 6

15 (contd.) ++k or --k (Pre-increment/decrement) k = 5; x = ++k; // increments k to 6 and then sets to the resulting value, i.e., to 6

16 CONTROL CONSTRUCTS

17 Conditional Statements if (condition) { stmt 1;//Executes if Condition is true } else { stmt 2;//Executes if condition is false }

18 SWITCH & BREAK switch(var) { case 1://if var=1 this case executes stmt; break; case 2://if var=2 this case executes stmt; break; default: //if var is something else this will execute stmt; }

19 LOOPS

20 FOR LOOP The syntax of for loop is for(initialisation;condition checking;increment) { set of statements } Eg: Program to print Hello 10 times for(I=0;I<10;I++) { printf(“Hello”); }

21 WHILE LOOP The syntax for while loop while(condn) { statements; } Eg: a=10; while(a != 0)Output: 10987654321 { printf(“%d”,a); a- -; }

22 DO WHILE LOOP The syntax of do while loop do { set of statements }while(condn); Eg: i=10;Output: do10987654321 { printf(“%d”,i); i--; }while(i!=0)

23 ARRAYS

24 Arrays are collection of data that belong to similar data type Arrays are collection of homogeneous data Array elements can be accessed by its position in the array called as index

25 Contd. Array index starts with zero The last index in an array is num – 1 where num is the no of elements in a array int a[5] is an array that stores 5 integers a[0] is the first element where as a[4] is the fifth element We can also have arrays with more than one dimension float a[5][5] is a two dimensional array. It can store 5x5 = 25 floating point numbers The bounds are a[0][0] to a[4][4]

26 String functions strlen(str) – To find length of string str strrev(str) – Reverses the string str as rts strcat(str1,str2) – Appends str2 to str1 and returns str1 strcpy(st1,st2) – copies the content of st2 to st1 strcmp(s1,s2) – Compares the two string s1 and s2 strcmpi(s1,s2) – Case insensitive comparison of strings

27 Function Syntax of function Declaration section > funname(parameter list); Definition section > funname(parameter list) { body of the function } Function Call Funname(parameter);

28 Example #include void fun(int a);//declaration int main() { fun(10);//Call } void fun(int x)//definition { printf(“%d”,x); }

29 ACTUAL & FORMAL PARAMETERS Actual parameters are those that are used during a function call Formal parameters are those that are used in function definition and function declaration

30 Call by value Calling a function with parameters passed as values int a=10;void fun(int a) fun(a);{ defn; } Here fun(a) is a call by value. Any modification done with in the function is local to it and will not be effected outside the function

31 Call By Reference Calling a function by passing pointers as parameters (address of variables is passed instead of variables) int a=1;void fun(int *x) fun(&a);{ defn; } Any modification done to variable a will effect outside the function also

32 Explanation a and x are referring to same location. So value will be over written.

33 Explanation

34 Conclusion Call by value => copying value of variable in another variable. So any change made in the copy will not affect the original location. Call by reference => Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.

35 Structures Structures are user defined data types It is a collection of heterogeneous data It can have integer, float, double or character data in it We can also have array of structures struct > { members; }element; We can access element.members;

36 Example struct Person { int id; char name[5]; }P1; P1.id = 1; P1.name = “vasu”;

37 typedef statement User Defined Data Types The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; makes the name Length a synonym (or alias) for the data type int.

38 (contd.) The data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used: Length a, b, len ; Length numbers[10] ;

39 UNION

40 Union has members of different data types, but can hold data of only one member at a time. The different members share the same memory location. The total memory allocated to the union is equal to the maximum size of the member.

41 EXAMPLE #include union marks { float percent; char grade; }; int main ( ) { union marks student1; student1.percent = 98.5; printf( "Marks are %f address is %16lu\n", student1.perc ent, &student1.percent); student1.grade = 'A'; printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade); }

42 ENUM

43 (ENUMERATED DATA TYPE) Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name {name_0, …, name_n} ; The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n.

44 (contd.) As an example, the statement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2.

45 POINTER Pointer is a special variable that stores address of another variable Addresses are integers. Hence pointer stores integer data Size of pointer = size of int Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip;

46 Pointers(Contd.) Pointers that store address of a double, char and float are called as double pointer, character pointer and float pointer respectively. char *cp float *fp double *dp; Assigning value to a pointer int *ip = &a; //a is an int already declared

47 Example int a; a=10;//a stores 10 int *ip; ip = &a;//ip stores address of a (say 1000) ip:fetches 1000 *ip : fetches 10 * Is called as dereferencing operator

48 Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.

49

50 malloc() A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

51 ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. Example: x=(int*)malloc(100*sizeof(int));

52 Contd….. On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

53 Calloc Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size);

54 Contd…… The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

55 free() Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. free(ptr); ptr is a pointer that has been created by using malloc or calloc

56 realloc The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize);

57 FILE HANDLING

58 Introduction 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. Cumbersome. Better if the data are kept in a file, and the program reads from the file. Programs generating large volumes of output. Difficult to view on the screen. Better to store them in a file for later viewing/ processing

59 Basic File Operations Opening a file Reading data from a file Writing data to a file Closing a file

60 Opening a File A file must be “opened” before it can be used. FILE *fp; : 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

61 Closing a File After all operations on a file have been completed, it must be closed. 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”, “w”) ; ……. fclose (xyz) ;

62 Read/Write Operations on Files 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) ; 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 (c, fp) ;

63 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) ; }

64 Contd. 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) ; Examples: fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ; fprintf (out, “\nThe result is: %d”, xyz) ;

65 Command line argument Command line arguments are parameters supplied to a program, when the program is invoked. How do these parameters get into the program? Every C program has a main function. main can take two arguments conventionally called argc and argv. Information regarding command line arguments are passed to the program through argc and argv.

66 INTRODUCTION TO C PREPROCESSOR

67 C Preprocessor Overview Preprocessor Directives Conditional Compilation

68 Overview Six phases to execute C: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute

69 C Preprocessor All preprocessor directives begin with # Possible actions Inclusion of other files Definition of symbolic constants & macros Conditional compilation of program code Conditional compilation of preprocessor directives

70 Preprocessor Directives #define for symbolic constants #define identifier text Creates symbolic constants The “identifier” is replaced by “text” in the program Example #define PI 3.14 area = PI * radius * radius; Replaced by “area = 3.14 * radius * radius” by preprocessor before compilation

71 Conditional Compilation Controls the execution of preprocessor directives & compilation of code Define NULL, if it hasn’t been defined yet #if !defined(NULL) #define NULL 0 #endif Use to comment out code (for comments) #if 0 code prevented from compiling #endif

72 THANKS


Download ppt "Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability."

Similar presentations


Ads by Google