Вы находитесь на странице: 1из 27

C

Compiler A compiler is a software that translates high-level language in to machine language (source code into object code). A compiler translates the code into an intermediary form. This step is called compiling, and produces an (.obj) object file. The compiler then invokes a linker, which turns the object file into an (.exe file) executable program. Machine language is digital, or binary, instructions that the computer can understand. Because the computer can't understand C source code, a compiler translates source code to machine code, also called object code. The linker combines the object code from your program with the object code from the function library and creates an executable file. In olden days people were using different languages for different purposes. E.g.: FORTRAN for scientific purpose, COBOL for business purpose, so people are forced to study all the languages that are very risky task. So they want to switch to a language that can do all types of works. s.no 1 2 3 4 5 Year 1960 1963 1966 1967 1972 Language ALGOL CPL BCPL B C Developed by International committee Cambridge university Martin Richards Ken Thompson Dennis Ritchie

History of 'C': Martin Richards developed the language BCPL (Basic Combined Programming Language) before 1970. Ken Thompson, a system engineer, from bell lab, did some modification in the BCPL language and for the modified version; he gave the name as B, the first character of BCPL. In 1972, another system engineer, called Dennis Ritchie, developed and first implemented the programming language C at AT & T bell laboratories of USA. C is a middle level programming language that allows you to program applications both using high level and low-level languages and used to develop both business application and system side applications. C is function oriented programming or we can say a C program is a collection of functions why because almost for every thing we have the built-in functions. C is highly structured programming or procedure oriented programming (it follows a particular procedure or structure to write the programs) and this structure makes its debugging, testing and maintenance easier.

Features of C 1. Portability or machine independent 2. Sound and versatile language 3. Fast program execution. 4. An extendible language. 5. Tends to be a structured language. Why C is popular? 1. It has a rich set of built-in functions, operators and data types, which is used to write any complex programs easily.
2

2. C is highly portable, which means programs written in one computer, can be run in other computer with little or no modifications. 3. Programs written in c are efficient and fast.
Basic Structure of C Program Documentation section. Link section Definition section Global declaration section main() { Local Declaration part; Execution part; }

Sub function section


Function 1 Function 2 Function 3 Function n

//BASIC STRUCTURE OF C PROGRAM #include <stdio.h> #define pi 3.1415 int x; void main()

{ int a,b; float y; printf (Hello World); }


Documentation Section Documentation section is used to give the comments about the programs like the author name, program name etc. Two Types: Single Line Comment To make a single line as a comment. Multi Line Comment To make more than one line as comment. /* comment */ Link section Link section is used to link the header files (the file that contain all the built in functions to be used within the program, they are with extension (.h)) Syntax: #include <header filename.h> E.g.: #include <stdio.h> #include <math.h> An #include directive instructs the compiler to add the code from another file into your source code during the compilation process. Definition Section Definition Section allows you to define the symbolic constants in your program. //comment

E.g.: #define PI 3.1415 An #define statement defines a symbolic name or symbolic constant to be a particular string of characters. Syntax: #define name replacement_list Global declaration Global declaration section is used to declare the variables globally. (i.e. before the main function) These variables can be accessed from any where (from any functions) in the program. These variables are called Global Variables. Variables Variables are temporary names given to the memory location where different values are stored. Limitations for variable names 1. Case sensitive. 2. First letter should be an alphabet. 3. It can contain numbers. 4. No white spaces or special symbols are allowed except an underscore (_) character. 5. Should not be a keyword. Data Types The data type of a variable is a keyword used to determine, that what kind (format) of data it can store. Type unsigned char char enum Length 1 byte 1 bytes 2 bytes Range 0 to 255 -128 to 127 -32,768 to 32,767 5

unsigned int short int int unsigned long long int

2 bytes 2 bytes 2 bytes 4 bytes 4 bytes

0 to 65,535 -32,768 to 32,767 -32,768 to 32,767 0 to 4,294,967,295 -2,147,483,648 to 2,147,483,647

float

4 bytes

3.4 * (10**-38) to 3.4 * (10**+38)

double

8 bytes

1.7 * (10**-308) to 1.7 * (10**+308)

long double

10 bytes

3.4 * (10**-4932) to 3.4 * (10**+4932)

Syntax for variable declaration datatype var1,var2,; int x,y,x; float a,b; Format Specifiers They are used to specify the type of data displayed. int %d long int %ld float %f double %lf long double %Lf char %c String %s 6

Hexadecimal %x Unsigned Integer unsigned int %u Variable Declaration Declarations create space for variables. The Figure below illustrates a variable declaration for the variable answer. We have not yet assigned it a value so it is known as an uninitialized variable. The question mark indicates that the value of this variable is unknown. Declaration of answer and assigning it a value

printf Function The library function printf can be used to print the results. printf("Twice %d is %d\n", term, 2 * term); printf structure

Output: Twice 15 is 30 Main function section Main function section is the one where we are going to write the actual code of the program. Local declaration part is to declare local variables. (Inside the main function) These variables can be accessed only in the main function. Execution part is the actual coding part.

Operators: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment or decrement operators 6. Conditional operators 1.arithmetic operators Arithmetic operators are used to perform arithmetic operations like addition, subtraction, multiplication, division and remainder. Operator + * / % Ex:- a=10, b=3
8

Name Plus Minus Asterisk Slash Modulator

Meaning Addition Subtraction Multiplication Division Remainder

Example a+b a-b a*b a/b a%b

a+b = 10+3 =13 a-b = 10 - 3 = 7 a*b = 10 * 3 =30 a/b= 10 / 3 = 3 a%b=10%3=1

2.

Relational operators Relational operators are used to check the relation between two values. Using relational operators we write relational expressions, a relational expression returns a Boolean value either 1 or 0. 1 indicates true, 0 indicates false. a=10; b=3; Operator < > <= >= == != Name Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to Example a<b a>b a<=b a>=b a= =b a!=b Result False or 0 True or 1 False or 0 True or 1 False or 0 True or 1

3.Logical operators: logical operators are used to combine two or more relational expressions. C language contains 3 logical operators. Operator name

&& || !

and or not

&& : It is used to combine two or more relational expressions, it returns true when all conditions are true, other wise it returns false. Truth Table: Expression1 T T F F && expression2 T F T F result T F F F

|| : This operator is used to combine two or more relational expressions, it returns true when any one of the condition is true, else it returns false. Truth table: Expression1 || T T F F expression2 T F T F result T T T F

! (not): This is the negative operator, we can place the not operator before any one of the condition. It returns the opposite result of the condition. i.e. It converts true to false and false to true. Truth table:

10

! expression T F

result F T

1. Assignment operator: C language contains equal to (=) operator to assign a value or expression into a variable. Ex: a=10; a=a+10; C language has the following short cut assignment operators. += -= *= /= %= a=a+10 a=a-10 a=a*10 a=a/10 a=a%10 a+=10 a-=10 a*=10 a/=10 a%=10

2. Increment and decrement operators: 1)++ increment operator 2) -- decrement operator ++: it is used to increment 1 to a variable. a. pre increment( ++a) ex:- printf(%d,++a); First the value will be incremented, and then the new value will be printed. 2)post increment(a++) ex:- printf(%d,a++);

11

First the value will be printed and then the value will be incremented. 2) - - : It is used to decrement the value by 1. a. pre decrement (--a) b. post decrement (a--) 6. Conditional operators: C language contains conditional operators(? , : ) to return a value from 2 values based on a condition. Syn: condition ? value 1 : value 2. If the condition is true then value1 will be returned, if the condition is false then value2 will be returned Ex:- a=40, b=20 Max=a>b ? a : b; Max=40 a=40, b=20 Min=a<b ? a : b Min = 20 Conditional statements: if statement: This statement is used to perform conditional operations. syntax1: if(condition) statement1; If the condition is true then statement1 will be executed.
12

If the condition is false then it will not execute the statement1. syntax 2: if(condition) { statement1; statement2; } If the condition is true then statement1 and statement2 will be executed. syntax 3: if(condition) statement1; else statement2; If the condition is true then statement1 will be executed, if the condition is false then statement2 will be executed. syntax 4: if( condition) { statement 1; statement 2; } else { statement 3; statement 4; }

13

If the condition is true then statement1 and statement2 will be executed. If the condition is false then statement3 and statement4 will be executed. syntax 5: Nested if if(condition1) Statement1; else if(condition2) statement2; else statement3; If the condition1 is true then statement1 will be executed and the remaining statements will be skipped. If the condition1 is false then it will check the condition2, if it is true then statement2 will be executed. If both condition1 and condition2 are false then it will execute statement3.

SWITCH STATEMENT
It is used to execute one of the options from no. of options. It is also called as multi branching statement. switch(expression) { case value: statements; case value: statements; default:

14

statements; } The expression value may be numeric or character type. The switch statement evaluates the expression. It will select one of the cases based on the expression. It will execute default statements when no case is selected. break statement: It is used to exit from a looping statement. We can use this in for, while , do while, and switch statement. ex:- break; goto statement: It is used to transfer the control from one place to another place in the program. It is also called as unconditional jumping statement syntax: example:goto <label name> ; goto print;

continue statement: It is used to transfer the control to the beginning of the looping statements. Ex: continue; Looping statements: while statement:It is used to execute a set of statements repeatedly as long as the given condition is true. syntax: while(condition) { statements; }
15

//body of while loop

First the condition will be tested, if it is true the body of the while loop will be executed first time, again the control will be transferred back to while loop. If it is false the control will come out of the while loop. for loop : It is used to execute a set of statements repeatedly as long as the given condition is true. syntax:for(initial value ; test condition ; increment / decrement) { statements; //body of for loop } When the for loop is executing for the very first time the initial value will be stored in the given variable. Then the condition will be tested. If it is true, the statements will be executed. After executing the last statement the control will return back to the for loop. Then the value will be incremented / decremented. Again the condition is tested, if it is false the control will come out of the for loop. ex:for(i=1; i<=10; i++) for( ;i<=10;i++) for(; i<=10 ; ) for( ; ; ) //infinite loop for(i=1,j=10;i<=10;i++,j--) printf(\n%d %d,i,j); for(i=1;i<=10;i++); //body less for loop do while loop:

16

This statement executes a set of statements as long as the condition is true. syntax: do { statements; statements; }while(condition); This is similar to while loop, but the difference is this loop will execute the statements at least once.

ARRAYS
Arrays Array is a group of values that belongs to similar data type that can share a common name. Array is a user defined data type. Array values can be called by using the index number, index number starts from 0 and ends with the total size-1. It allocates memory continuously.By default it will have all garbage values.

Arrays are divided into 2 types. 1) Single dimensional arrays. or One dimensional arrays 2) Multi dimensional arrays 1) One dimensional arrays:- The array which is using only 1 subscript is known as one dimensional array. In One dimensional array the elements are represented in single row or single column.

17

Syntax:ex:-

Data_type variable_name[subscript] int a[10];

2) Two dimensional arrays: The array which is using two subscripts is known as 2 dimensional array Syntax:ex:Data_type variable_name[subscript][subscript] int a[2][2];
Structures Structures Structure is collection of dissimilar data types. Structure is a user defined data type. Functions What Is a Function? A function is an independent section of program code that performs a certain task and has been assigned a name. By using a function's name, the code in the function can be executed. Every C program has at least one function, main(). When your program starts, main() is called automatically. main() might call other functions, some of which might call still others. Functions come in two varieties: built in and user defined. Built-in functions are part of your compiler package--they are supplied by the manufacturer for your use. 1. Built in functions

Ex:- printf(), scanf(), pow(), strlen(), strcpy(), toupper(),


18

2) User defined functions:- These functions are created by the user. Ex:- address(),name(), add(a,b), area(r) , fact(n), Uses of functions: a. Dividing the task into sub tasks. b. If a particular task is repeated number of times in a program we can create a function and call that function wherever we require. c. Whenever a function is called in a statement the control will be transferred to that called function. After executing all statements it returns back to the calling function. d. The length of the source program will be reduced by using functions at appropriate places. A function can be used in other programs also.
Declaring and Defining Functions Using functions in your program requires that you first declare the function and that you then define the function. The declaration tells the compiler the name, return type, and parameters of the function. The definition tells the compiler how the function works. No function can be called from any other function that hasn't first been declared. The declaration of a function is called its prototype. Function Prototypes Many of the built-in functions you use will have their function prototypes already written in the files you include in your program by using #include. For functions you write yourself, you must include the prototype.

19

The function prototype is a statement, which means it ends with a semicolon. It consists of the function's return type, name, and parameter list. The parameter list is a list of all the parameters and their types, separated by commas. The function prototype does not need to contain the names of the parameters, just their types. A prototype that looks like this is perfectly legal: long Area(int, int); This prototype declares a function named Area() that returns a long and that has two parameters, both integers. Although this is legal, it is not a good idea. Adding parameter names makes your prototype clearer. The same function with named parameters might be long Area(int length, int width); It is now obvious what this function does and what the parameters are. Note that all functions have a return type. If none is explicitly stated, the return type defaults to int. Your programs will be easier to understand, however, if you explicitly declare the return type of every function, including main(). Function Prototype Syntax return_type function_name([type parameterName]...); Function Definition Syntax return_type function_name ([type parameterName]...) { statements; }

20

Function Prototype Examples long FindArea(long length, long width); // returns long, has two parameters void PrintMessage(int messageNumber); // returns void, has one parameter int GetChoice(); // returns int, has no parameters BadFunction(); // returns int, has no parameters

String functions: 1) strlen():- This function is used to return the length of a string. syntax:- strlen(string); note:- When we are using string functions we have to include a header file <string.h> 2) strcpy():- This function copies a string from one string variable to another string variable. syntax:- strcpy(target_string , source_string); 3) strcat(): (String concatenation) This function adds a string at the end of another string syntax:- strcat(string1,stirng2 ); 4) strcmp(): (String comparison) This compares one string with another string, if two strings are equal this function returns 0, else it returns the numeric difference between the non-matching characters.
21

Syntax:- strcmp(string1, string2); 5) stricmp(): This function is similar to strcmp, but this function ignores the case sensitivity. syntax:- stricmp(string1, string2); 6) strrev(): This function reverses the given string Syntax:- strrev(string); 7) strupr(): This function converts the given string into upper case(capitals) syntax:- strupr(string) 8) strlwr(): This function converts the given string into lower case. syntax:- strlwr(string); single character functions 1) toupper() :- This function converts a single character to upper case. syntax:- toupper(character); 2) tolower() :- This function converts a single character to lower case. syntax:- tolower(character); note:- when we are using single character functions we have to include a header file <ctype.h>

22

POINTERS A pointer is a variable which holds the address of another variable. Since addresses are whole numbers pointers would always contains whole numbers. Consider the following declaration int i=10; The declaration tells the C compiler, 1) Reserve space in memory to hold the integer value. 2) Associate the name i with this memory location. 3) Store the value 10 at this location. Memory map:i - location name 10 - Value at location 65524 location number or address.

Structures Structures Structure is a user defined data type. Structure is collection of dissimilar data types.

Declaring a structure:struct <structure name> { structure element 1; structure element 2;

23

--structure element n; }; structure variables;

Example 1: ======== struct student { int sno; char name[20]; int total; }; struct student a,b,c;

Example 2: ======== struct student { int sno; char name[20]; int total; }a,b,c; Accessing structure elements:-

24

We can access the structure elements by using structure_variable.structure_element; example:- a.sno, a.name, a.total a.sno=5; a.total=432; FILES A file is a collection of information stored on a storage device with a particular file name. Uses of a file:1) Stores the data in the form of a file and we can retrieve it whenever we require. 2) Using the data from the file in different programs. Opening a file:- we can open a file by using fopen() Syntax: - fopen(file name, opening mode); Ex: FILE *fp; fp=fopen(cmtes.txt,w); File opening modes:1)w :- Writing the data into a file. If the file already exists its contents will be over written. 2)r:- Reading data from a file. 3)a:- Adds data into an existing file.(Appending) 4)w+ :- We can write data into a file and we can read data from the file. If the file already exists its contents will be over written, else creates a new file. 5)r+ :- Reading existing contents , writing new contents, modifying existing contents of a file.

25

6)a+ :- Reading existing contents, appending new contents at the end of a file. closing a file:- When the file processing is over, the file must be closed. We can close a file by using fclose( ). syntax:- fclose(file pointer); ex:1)getc() This function is used to read a character from a file. syntax :- getc(file pointer); ex:2)putc() This function is used to write a character into a file. syntax:- putc(character, file pointer); ex:putc(ch,fp); getc(fp); fclose(fp); File functions:-

3)fprintf():- This function writes formatted data into a file. Syntax:Ex:fprintf(file pointer, formatted string, list of variables) fp=fopen(student.dat,w); fprintf (fp , %d %s %d,sno ,name, marks); 4)fscanf():- This function reads formatted data from a file. Syntax:Ex:fscanf(file pointer, formatted string, list of variables) fp=fopen(student.dat,r); fscanf(fp , %d %s %d,&sno ,name,&marks);

26

5) fwrite( ) This function is used to write the information in a binary file. Syntax: fwrite(address of struct variable, size of struct variable, no. of blocks, file pointer); ex: 6) fread() fwrite(&b, sizeof(b),1,fp); This function is used to read the data from a binary file. Syntax:fread(address of struct variable, size of struct variable , no. of blocks, file pointer); ex:fread(&b,sizeof(b),1,fp);

7) rewind():This function moves the record pointer to the starting position of the file. Syntax:ex:rewind(file pointer); rewind(fp);

27

Вам также может понравиться