C programming Language

50 %
50 %
Information about C programming Language

Published on June 7, 2010

Author: aSGuest47746

Source: authorstream.com

Slide 1: C LANGUAGE Fundamentals and History of C : 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 PROGRAM STRCTURE IN C : PROGRAM STRCTURE IN C #include<stdio.h> #include<conio.h> void main() { --other statements } HEADER FILES : 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 MAIN FUNCTION : 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 Sample program : Sample program #include<stdio.h> #include<conio.h> int main() { printf(“Hello”); return 0; } This program prints Hello on the screen when we execute it HOW TO RUN C PROGRAM : 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. Points to remember : 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 DATA TYPES : 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. VARIABLES : VARIABLES Variables are data that will keep on changing Declaration <<Data type>> <<variable name>>; int a; Definition <<varname>>=<<value>>; a=10; Usage <<varname>> a=a+1; //increments the value of a by 1 RULES FOR VARIBLE NAME : 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. INPUT & OUTPUT : 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 OPERATORS : OPERATORS Arithmetic (+,-,*,/,%) Relational (<,>,<=,>=,==,!=) Logical (&&,||,!) Bitwise (&,|) Assignment (=) Compound assignment(+=,*=,-=,/=,%=,&=,|=) Shift (right shift >>, left shift <<) OPERATORS(Contd.) : 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 (contd.) : (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 Slide 16: CONTROL CONSTRUCTS Conditional Statements : Conditional Statements if (condition) { stmt 1; //Executes if Condition is true } else { stmt 2; //Executes if condition is false } SWITCH & BREAK : 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; } Slide 19: LOOPS FOR LOOP : 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”); } WHILE LOOP : WHILE LOOP The syntax for while loop while(condn) { statements; } Eg: a=10; while(a != 0) Output: 10987654321 { printf(“%d”,a); a- -; } DO WHILE LOOP : DO WHILE LOOP The syntax of do while loop do { set of statements }while(condn); Eg: i=10; Output: do 10987654321 { printf(“%d”,i); i--; }while(i!=0) Slide 23: ARRAYS ARRAYS : ARRAYS 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 Contd. : 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] String functions : 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 Function : Function Syntax of function Declaration section <<Returntype>> funname(parameter list); Definition section <<Returntype>> funname(parameter list) { body of the function } Function Call Funname(parameter); Example : Example #include<stdio.h> void fun(int a); //declaration int main() { fun(10); //Call } void fun(int x) //definition { printf(“%d”,x); } ACTUAL & FORMAL PARAMETERS : 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 Call by value : 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 Call By Reference : 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 Explanation : Explanation a and x are referring to same location. So value will be over written. Explanation : Explanation Conclusion : 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. Structures : 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 <<structname>> { members; }element; We can access element.members; Example : Example struct Person { int id; char name[5]; }P1; P1.id = 1; P1.name = “vasu”; typedef statement : 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. (contd.) : (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] ; UNION : UNION UNION : UNION 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. EXAMPLE : EXAMPLE #include <stdio.h>union marks{    float percent;    char grade;};int main ( ){    union marks student1;    student1.percent = 98.5;    printf( "Marks are %f   address is %16lu\n", student1.percent, &student1.percent);    student1.grade = 'A';    printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade);} ENUM : ENUM (ENUMERATED DATA TYPE) : (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. (contd.) : (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. POINTER : 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; Pointers(Contd.) : 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 Example : 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 Dynamic Memory Allocation : 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. malloc() : 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: Slide 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)); Contd….. : 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 Calloc : 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); Contd…… : 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. free() : 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 realloc : 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); FILE HANDLING : FILE HANDLING Introduction : 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 Basic File Operations : Basic File Operations Opening a file Reading data from a file Writing data to a file Closing a file Opening a File : 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 Closing a File : 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) ; Read/Write Operations on Files : 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) ; Example :: convert a text file to all UPPERCASE : 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) ; } Contd. : 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) ; Command line argument : 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. INTRODUCTION TO C PREPROCESSOR : INTRODUCTION TO C PREPROCESSOR C Preprocessor : C Preprocessor Overview Preprocessor Directives Conditional Compilation Overview : Overview Six phases to execute C: Edit Preprocess Compile Link Load Execute C Preprocessor : 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 Preprocessor Directives : 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 Conditional Compilation : 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 Slide 72: THANKS

Add a comment

Related presentations

Related pages

C (programming language) - Wikipedia, the free encyclopedia

C (/ ˈ s iː /, as in the letter c) is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable ...
Read more

C programming.com - Learn C and C++ Programming ...

A website designed to help you learn C or C++. Understandable C and C++ programming tutorials, compiler reviews, source code, tips and tricks.
Read more

The C Programming Language - Wikipedia, the free encyclopedia

History. The first edition of the book, published in 1978, was the first widely available book on the C programming language. C was created by Dennis Ritchie.
Read more

The C Programming Language – Wikipedia

The C Programming Language ist das erste Buch über die Programmiersprache C. Die Erstausgabe erschien 1978. Die Zweitausgabe erschien 1988 und wurde in ...
Read more

The C Programming Language. (Prentice Hall Software ...

The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with ...
Read more

The Basics of C Programming | HowStuffWorks

The C programming language is a popular and widely used programming language for creating computer programs. Programmers around the world embrace C because ...
Read more

C Programming - Wikibooks, open books for an open world

C Programming is a featured book on Wikibooks because it contains substantial content, it is well-formatted, and the Wikibooks community has decided to ...
Read more

The C Programming Language - University of Michigan

Significant Language Features C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer.
Read more

C Tutorial - Tutorials Point

C tutorial for beginners - Learn ANSI, GNU and K/R standard of C programming language with simple and easy examples covering basic C, language basics ...
Read more

Amazon.com: The C Programming Language (9780131103627 ...

Amazon.com: The C Programming Language (9780131103627): Brian W. Kernighan, Dennis M. Ritchie: Books
Read more