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

C Language Notes

(1).History of C History Of C
* First C developed on UNIX operating system and it was coded in low level language in 1969.(PDP-7 assembly language). * After that "Marting Richard" developed BCPL language. BCPL is in assembly language and error prone. * Thereafter B language is developed by "Ken Thomson". B is a high level language and it has typical functionality. * Thereafter based on B language finally C language is developed in 1973 by "Dennis Ritchie". And C is a middle level language

Features Of C
Efficient Fast C language is very efficient due to built functions. Due to conditional statements and control statements. Module Programming C program written for one computer can run in other computer (with different Operating systems) with some modifications or some modifications

Structured Programming Portability -

Characteristics Of C
* Small size * Extensive use of function calls * Loose typing * Structured programming * Low level (BitWise) programming readily available * Pointer implementation - extensive use of pointers for memory, array, structures and functions.

Advantages And Disadvatages Of C


Advantages of C: In c, Programmers can create and maintain a unique library functions which can be used by many different programs. Thus large projects can be managed easily with minimal duplication of effort. Disadvantages Of C: Its main drawback is that it has poor error detection which can make it off

C Language Notes
putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of C we can break them. Not many languages allow this. This if done properly and carefully leads to the power of C programming

(2).C basics Structure of C Language


1. Documetation Section /*------------*/ 2. Link Section #include<filename> 3. Definitio of constants #define variable value 4. Global variable declaration datatype variable 5. main() { declaration; executable statements; } 6. Sub functions [optional]

[optional] [optional]

Datatypes in C Language
Datatype: Datatype tells which type of data we are giving as the input. The following are the datatypes available in c-Language. * Primary Datatypes * Derived Datatypes * User defined Datatypes Primary Datatypes Type 1.char 2.Unsigned char 3.signed char 4.int 5.signed int 6.short int 7.Unsigned short int 8.signed short int 9.long int 2,147,483,646 10.signed long int 2,147,483,646 11.unsigned long int 12.float 13.double 14.long double Derived Datatypes Size in bits 8[1 byte] 8[1 byte] 8[1 byte] 16[2 bytes] 16[2 bytes] 16[2 bytes] 8[1byte] 8[1 byte] 32[4 bytes] 32[4 bytes] 32[4 bytes] 32[4 bytes] 64[8 bytes] 128[16 bytes] Arrays, strings structures, unions Range -128 to 127 0 to 255 -128 to 127 -32,768 to 32,767 -32,768 to 32,767 -32,768 to 32,767 0 to 65,535 0 to 65,535 -2,147,483,647 to -2,147,483,647 to 0 to 4,294,967,295 6 digits of precision 10 digits of precision 10 digits of precision

User defined Datatypes -

C Tokens

C Language Notes
C token is an individual word present in the c-language. There are 6 types Keywords: meaning. keywords are defined by the software with the specified In c language 32 keywords are there

Identifiers: User defined variable names.

Constants:

The value which is not changed during the execution

Strings:

Group of caharacters enclosed in " "

Operators:

The following are the operators available in c

1.Arthematic Operators: [+,-,*,/,%] 2.Assignment Operators: [=] 3.Relational Operators: [<,<=,>,>=,==,!=] 4.Logical Operators: [and,or,not] 5.increment/decrement Operators:[++,--] 6.Bitwise Operators: [&,|,~,^,>>,<<] 7.Conditional or terinary Operator:[?:]

Special characters: ,(comma) -to seperate 2 variables sizeof Operators -returns the size of the variable

32 Keywords
auto break case char const continue default do double else enum extern float for goto if int long

C Language Notes
register return short signed sizeof static struct switch typedf union unsigned void volatile while

auto keyword
automatic variables are nothing but local variables. syntax: auto datatype var; * automatic variables are stored in memory * Default value is garbage value * scope is local to the block in which the variable is defined. * life time is till the control remains within the block in which the variable is defined eg: main() { auto int x=20; printf("x=%d",x); { auto int y=2; auto int x=35; printf("/n x=%d /t y=%d",x,y); } printf("/nx=%d",x); } o/p: x=20 x=35 x=20

y=2

break keyword
(i) (ii) It can be used to terminate a case in the switch statement It can be used for immdiate terminations of a loop that means it breaks the loop and passes to the next statement

syntax:break;

C Language Notes
example: main() { int i; for(i=1;i<=100;i++) { if(i>50) { break; } } }

switch, case, default keywords


switch keyword allows us to make a decision from the number of choices with case and default keywords syntax: switch(expression) { case constant1: statement; break; case constant2: statement; break; . . default: statement; } The integer expression following the keyword switch is any c expression. The keyword case is followed by an integer or a character constant and the 'statement' in the above syntax is the represent any valid c expression or statement. process: First, the expression in the switch statement will be evaluated. If the value is matched against the case constants, the program executes the statements following that case. If no match is found with the case statements, the default statement will be executed.

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255.

C Language Notes
float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

const keyword
If you declare a constant with the const keyword, it acts like a safeguard and does not change the value of variable. In case you automatically reasign a value to that variable, it gives error. eg: const int width=10; * once this is declared, statements like width=12; would be illegal.

continue keyword
The continue statement causes the next iteration of the enclosing loop to begin. When continue statement is encountered in the program, the remaining statements in the body of the loop are skipped and the control is passed to the re-intialization step. syntax:continue; example: main() { int i; for(i=1;i<=100;i++) { if(i%9==0) { continue; } printf("%d",i); } }

switch, case, default keywords


switch keyword allows us to make a decision from the number of choices with case and default keywords syntax: switch(expression)

C Language Notes
{ case constant1: statement; break; case constant2: statement; break; . . default: statement; } The integer expression following the keyword switch is any c expression. The keyword case is followed by an integer or a character constant and the 'statement' in the above syntax is the represent any valid c expression or statement. process: First, the expression in the switch statement will be evaluated. If the value is matched against the case constants, the program executes the statements following that case. If no match is found with the case statements, the default statement will be executed.

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

enum keyword
Enumerations: An enumeration is a set of named integer constants that specify all the legal values a variable of that type may have. syntax: enum tag{list of values};

C Language Notes
example: enum metro{Bombay,Delhi,Madras,Calcutta}; enum metro town; town=Bombay; valid town=Banglore; invalid * printf("%d%d",Bombay,Madras); o/p: 0,2 [numeric constants] * We can change the values i.e enum{Bombay, Delhi, Madras=13, calcutta} Now constants will be Bombay 0 Delhi 1 Madras 14 Calcutta 15 [By using enmerated datatype we can generate a numeric sequence automatically starting with 0]

extern keyword
external variables are global variables. syntax:extern datatype var; * * * * extern varibales are stored in memory default value is zero scope is throughout the function where it is defined the extent of external variable is alive upto the termination of program.

example: extern int p=4; main() { printf("%d",p); p=29; printf("%d",p); } o/p: p=4 p=29

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory.

C Language Notes
eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

goto keyword
goto: The goto statement transfers control to any other statement within the same function in a c program. syn: goto label; eg: goto abc; abc: { ----}

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

C Language Notes
char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

register keyword
when operands are brought into processor, they stored up high speed storage. Those are called registers. Each register can store one word of data i.e 16bits. * stored in registers * default value is garbage value

C Language Notes
* scope is local to the block in which the variable defined. * lifetime is till the control remains within the block in which the variable is defined

return keyword
Return keyword carries some value and returns to the calling function. The default return type is int. syntax: return [expr]; example: int power(x,y) { return pow(x,y); }

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of

C Language Notes
memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

sizeof keyword
If we want to know about how much memory your variable take up, then sizeof keyword will be used eg: main() { printf("size printf("size printf("size printf("size printf("size

of of of of of

printf("size of printf("size of printf("size of printf("size of printf("size of printf("size of printf("size of }

int is %d bytes /n",sizeof(int)); short int is %d bytes /n",sizeof(short int)); long int is %d bytes /n",sizeof(long int)); signed int is %d bytes /n",sizeof(signed int)); signed short int is %d bytes /n", sizeof(signed short int)); signed long int is %d bytes /n", sizeof(signed long int)); signed int is %d bytes /n",sizeof(signed int)); unsigned short int is %d bytes /n", sizeof(unsigned short int)); unsigned long int is %d bytes /n", sizeof(unsigned long int)); char is %d bytes /n",sizeof(char)); float is %d bytes /n",sizeof(float)); double is %d bytes /n",sizeof(double));

static keyword
static variables are permanent variables within their own functions. syntax: static datatype var; * static variables are stored in memory * default value is zero * scope is local to the block in which the variable is defined. * lifetime is throughout the block.

example: void increment(); void main() {

C Language Notes
increment(); increment(); increment(); } void increment() { static int i=1; printf("/n%d",i); i=i+1; } o/p: 1 2 3 Differences between auto and static variables: Like auto variables, static variables are also local to the block in which they are declared. The difference between them is that static variables don't disappear when the function is no longer active. Their values persist. If the control comes back to the same function again, the static variables have the same values they had last time around.

switch, case, default keywords


switch keyword allows us to make a decision from the number of choices with case and default keywords syntax: switch(expression) { case constant1: statement; break; case constant2: statement; break; . . default: statement; } The integer expression following the keyword switch is any c expression. The keyword case is followed by an integer or a character constant and the 'statement' in the above syntax is the represent any valid c expression or statement. process: First, the expression in the switch statement will be evaluated. If the value is matched against the case constants, the program executes the statements following that case. If no match is found with the case statements, the default statement will be executed

typedf keyword

C Language Notes
New datatype names can be defined by using the keyword 'typedf'. syntax: typedf type name; example1: typedf float deci; deci amt; (Here type is a valid datatype) (This tells the compiler that deci is another name for float) (Here, the amt is floating point datatype) (point is another name for deci. That means point is also another name for float)

example2: typedf deci point;

example3: typedf for structures typedf struct { int day; int month; int year; }date; (Here, date is new datatype and date due_date; due_date is the variable of date) Note:typedf can't be used with storage calsses.

union keyword
A union is a memory location that is shared by two or more variables, generally of diffrent types at different times. syntax: union tag { type var-1; type var-2; } example: union temp { int i; char ch; };

when we give union temp xyz; the memory is allocated. Here, in union xyz, both integer i, character ch share the same memory location.

char, double, float, int, long, short, signed and unsigned keywords
char: char keyword or datatype accepts a single alphabet and occupies 1 byte of memory. eg:char ch; Signed char: A signed char is same as an ordinary char and has

C Language Notes
range from -128 to +127 and occupies 1 byte of memory. unsigned char: An unsigned char has the range from 0 to 255. float, double and long double: A float occupies 4 bytes of memory and can range from -3.4e38 to +3.4e38. If this is insufficient,then c offers a double data type which occupies 8 bytes of memory and has a range from -1.7e308 to +1.7e308. If the situation demands usage of real numbers that lie even beyond the range offered by double datatype, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes of memory.

printf()
printf() used to display the content on the screen which is written with in the quotation marks. * Used to display the output by using conversion specifiers * Returns no.of characters printed on the screen. examples: eg1:prints the simple message on the screen #include <stdio.h> main() { printf("Welcome to c world"); } eg2:prints sum of 2 nos on the screen #include <stdio.h> main() { int a=2,b=3,c; c=a+b; printf("c=%d",c); } o/p:c=5 eg3: prints more than one value on the screen #include <stdio.h> main() { float f1=3.5,f2=2.5,sum,diff; sum=f1+f2; diff=f1-f2; printf("%f %f",sum,diff); } o/p:6.0 1.0 eg4: prints no.of characters printed on the screen #include <stdio.h> main() { int i; i=printf("welcome%d",i); } o/p:7

printf()

C Language Notes
printf() used to display the content on the screen which is written with in the quotation marks. * Used to display the output by using conversion specifiers * Returns no.of characters printed on the screen. examples: eg1:prints the simple message on the screen #include <stdio.h> main() { printf("Welcome to c world"); } eg2:prints sum of 2 nos on the screen #include <stdio.h> main() { int a=2,b=3,c; c=a+b; printf("c=%d",c); } o/p:c=5 eg3: prints more than one value on the screen #include <stdio.h> main() { float f1=3.5,f2=2.5,sum,diff; sum=f1+f2; diff=f1-f2; printf("%f %f",sum,diff); } o/p:6.0 1.0 eg4: prints no.of characters printed on the screen #include <stdio.h> main() { int i; i=printf("welcome%d",i); } o/p:7

Sample Program in C Language


/*First Program in C Language*/ main() { printf("Welcome to C world"); } Short cut keys for compiling C-Program F2 ctrl+F9 Alt+F5 To save the c-program file To compile the c-program To View the result.

Three files will be generated when compiling the C-program .bak .obj .exe backup file objective file (machine language) executable file

C Language Notes
Program Compiling And Running Process in C Language
* Editor/Word Processor: The source code is written using an editor or a word processor. * Source Code : Source code is the text what user can read and it is the input to the compiler. * CPreprocessor : The source code is first passed through the C preprocessor. The preprocessor acts on special statements called directives. * Expanded C Source : The C Preprocessor expands the shortand of the Code directives and produces as output and it is passed to on the C-compiler. * C Compiler : The compiler translates the expanded source code into computer's assembly language (which can be understood by computer) * Assembly Language : The assembler takes the code from the c-compiler and Code produces object code. This object code can be read and executed directly and provides to the linker (.obj file) * Linker : The object code along with support routines from the standard library and any other seperately compiled functions are linked together by the linker into an executable code (.exe file) * Loader : The executable code is run using the system's loader.

(3).C Operators
In C, there are some unusual operators used to perform the task of logical decision making. The following are the operators availble in C. * Arthematic Operators * Assignment Operators * Relational Operators * Logical Operators * Equality Operators * Special Operators

Arthimatic Operators
Arithimatic operations are the basic and common operations performed using any computer programming. Normally, these operators are considered as basic operators and known as a binary operators as they require two variables to be evaluated. For example if we want to multiply any two numbers, one has to enter or feed the multiplicand and the muliplier. That is why it is considered as a binary operator. In c, the arithimatic operators used are as follows: + Addition Subtraction * Multiplication

C Language Notes
/ % Division Modulus Example: main() { int a,b,c,d,e,f,g; a=5,b=2; c=a+b; /*adds a,b and stores in c */ d=a-b; /*subtracts a,b stores in d*/ e=a*b; /*multiplies a,b stores in e*/ f=a/b; /*divides a,b stores co-efficient value in f*/ g=a%b; /*divides a,b stores the remainder value in g*/ printf("%d/t%d/t%d/t%d/t%d",c,d,e,f,g); } The o/p will be: 7 3 10 2 1

Assignment Operators
An assignment operator is used to assign back to a variable, a modified value of the present holding. Operator = += back -= it *= it /= %= variable Meaning Assign right hand side value to the left hand side Value of LHS variable will be added to the RHS and assign it to the varible in LHS Value of LHS variable will be subtracted to the RHS and assign back to the varible in LHS Value of LHS variable will be multiplied to the RHS and assign back to the varible in LHS Value of LHS variable will be divided to the RHS and assign it back to the varible in LHS The reminder will be stored back to the LHS after integer division carried out between the LHS variable and the RHS

Relational Operators
For the program flow, the relational operators are required. Relational operators compare values to see if they are equal or if one of them is greater than the other so on. Relational operators in C produce only one or zero result. These are often specified as "true" or "false" respectively. The following operators are used to perform the relational operations of the two

C Language Notes
variables or expressions. Operator < > <= >= Meaning Lessthan Greaterthan Lessthan or equal to Greaterthan or equal to

The relational operators are represented in the following syntax exp1 relational_Opertor exp2 The exp1 will be compared with exp2 and depending upon the relation like greaterthan, greaterthan or equal to and so on. The result will be either "true" or "false". Example: Expression 3>4 6<=2 10>-32 Result false false true

Logical Operators
For the program flow the logical operators are required. The following are the logical operators Operator Meaning && Logical AND || Logical OR ! Not Logical AND: A compound expression is true when two conditions(expressions) are true. To write both conditions, the operator && is used in the following manner exp1 && exp2 In the two expressions, the conjunction must be integers. The char data are converted to integer and are thus allowed in the expression. Logical OR: The logical OR has the following form exp1 || exp2 and evaluates to true if either exp1 or exp2 is true. Logical negation operator: A logical expression can be changed from false to true or from true to false with the negation operator !. And it has the following form !(exp)

Equality Operators
The following operators are used to check the equality of the given expression or a statement. These operators are normally represented by using the tow keys naemly "equal to" by the operator "==" and "not equal to" by the operator != The equality operators produce the result either "true" or "false"

C Language Notes
example: a=4; b=6; c=8; expression Result a == b false 's' == 'y' false

Special Operators
In C, there are some special operators to perform particular type of operation. Unary Operators: The unary operators require only a single expression to produce a line. Unary operators usually precede their single operands. Sometimes some unary operators may be followed by the operands such as incrementer and decrementer. The most common unary operation is unary minus where minus sign precedes a numerical constant, a variable or an expression. The following are the unary operators in C a) Pointer Operator(*) : The pointer operator is used to get the content of the address operator pointing to a particular memory element or cell. (b) Address Operator(&) : The address operator & is used to get the address of the other variable in an indirect manner. (c) Sizeof Operator : The sizeof operator is used to give the direction to the C compiler to reserve memory size or block to the particular data type which is defined in the strucutre type of data in the linke list. (d)Incrementer and decrementer: Two special operators are used in C namely incrementer and decrementer. These operators are used to control the loop in an effective manner. incrementer: The symbol ++ or notation is used for incrementing by 1. i++ is equal to i=i+1 ++i is equal to i=i+1 decrementer: The symbol -- or notation is used for decrementing by 1. i-- is equal to i=i-1 --i is equal to i=i-1 Special Operators contd....

Control Statements
Control Statements are mainly divided into three. Conditional Expressions: The conditional expressions are mainly used for decision making. The following statements are used to perform the task of the conditional operations. if statement if-else statement nested if statement else-if Ladder switch statement

C Language Notes
Loop Statements: The loop statements are essential to construct systematic bllock styled programming. In C, three various ways one may define the control structures using different types of loop operations. The following are the loop structures in C. while loop do-while loop for loop

Breaking control statements: For effective handling of the loop statements, C allows the use of the following 3 types of control break statements. Break Statement Continue Statement goto statement

if statement in C
if statement The if statement is used to write conditional expressions. If the given condition is true then it will execute the statements. Otherwise it will execute optional statements. syntax: if<conditon> { --------} The expression is evaluated and if it is "true", the statement following the if is executed. In case the given expression is "false", the statement is skipped and execution continues with the next statement. example: a=20; b=10; if(a>b) printf("Larget value=%d"); If the given condition is satisfied, then it prints the message "Lagest value=20" and if not, it will simply skip the statement

if-else statement in C
if-else statement The if-else statement is used to write conditional expressions. If the given condition is true then it will execute the statements. Otherwise it will execute else block statements. syntax: if<conditon> { --------} else { --------}

C Language Notes
The expression is evaluated and if it is "true", the statement following the if is executed. In case the given expression is "false", the statement . under else block will be executed. example: if(a>b) printf("Largest value=%d",a); else printf("Largest value=%d",b)

nested if statement in C
nested if statement The if statement within if statement is nested if. syntax: if(condition-1) { if(condition-2) { statement-1 } } else statement-2 if the condition-1 is satisfied, then only it checks the condition-2. Otherwise else block will be executed. example: #include <stdio.h> main() { int a; printf("enter value for a"); scanf("%d",&a); if(a>0) { if(a==5) { printf("Your input is corretct"); } } else printf("Your input is not correct"); }

else-if Ladder
else-if ladder statement format if(condition-1) statement-1 else if(condition-2) statement-1 else statement-2 example:big no among three numbers #include <stdio.h>

C Language Notes
main() { int a,b,c; printf("enter values for a,b,c"); scanf("%d%d%d",&a,&b,&c); if(a>b && a>c) printf("%d is big",a); else if(b>c) printf("%d is big",b); else printf("%d is big",c); }

Switch statement in C
Switch statement The switch statement is a multiway decision maker that tests whether an expression matches one of the number of constant values, and braces accordingly. Syntax: syntax: switch(expression) { case constant1: statement; break; case constant2: statement; break; . . case constantn: statement; break; default: statement; } * The expression whose value is being compared, may be any valid expression including the value of the variable, an arithimatic expression, logical comparision, a bitwise expression or the return value from a function call, but not the floating point expression. * The constants in each of the case statements must obiviously be of the same type. * The expression value is checked against each of the specified cases and when a match occurs, the statement following that is executed. Again to maintain generality, the statement can be either a simple or a compound statment. * The value that follows the keyword case may only be constants they can't be expressions. They may be integers or characters, but not floating point numbers or character strings. * The last case of this statement which is called the default case is optional and should be used according to the program's specific requirement. * Execution or the switch constant in C follows this logic. No statements are executed until a case has been matched or the default case has been encountered.

C Language Notes
While Loop
While Loop The while loop is used when we are not certain that the loop will be executed. After checking whether the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operations. syntax: For single condition while<condition> statement; For a block of statements while<condition> { statement-1; statement-2; ...... } * The condition cab be any valid expression including the value of a variable a unary or binary expression, or the value returned by a function. The statement can be a single or compound statement. The condition is actually test condition. * The while loop does not explicitly contain the initilization or incrementation parts of the loop. These two statements are normally provided by the programmers. initial condition while(test condition) { statement-1 statement-2 change of initial condition }

do-While Loop
do-While Loop The do-while loop is used whenever one is certain about a test condition, then the do-while loop can be used. As it enters into the loop atleast once and then checks whether the given condition is true or false. As long as the test condition is true, the loop operations or statements will be repeated again and again. Syntax: do { statement-1 statement-2 ----------

C Language Notes
}while(condition);

for Loop
for Loop The for loop is most commonly used in C. This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for further iteration. Sometimes the oprations carried out by the while loop can also be done by using the for loop. Depending on the situation programmer can decide the loop. Syntax: for(exp1;exp2;exp3) statement; where expression-1 is the initialization of the expression or condition; expression-2 is the condition checked as long as the the given expression is true. expression-3 is the incrementer or decrementer to change the index value of the for loop variable.

break statement
break statement The break statement is used to terminate the control from the loop statements of the case-structure. The break statement is normally used in the switchcase loop and in each case condition, the break statement must be used. If not, the control will be transfered to the subsequent case condition. syntax: break; break statement in while loop The break statement used in while loop. The following example shows how break statement will be used in the while loop. main() { int value,i; i=0; while(i<=10) { printf("enter number:"); scanf("%d",&value); if(value<=0) { printf("Zero or -ve value found"); break; } i++;

C Language Notes
} } The above program segment will process only the +ve integers. Whenever a zero or non -ve value is encountered, the computer will display the message "zero or negative value found" as an error and exit from the while loop.

continue statement
continue statement The continue statement is used to repeat the same operations once again even if it checks the error. syntax: continue; The continue statement is used for the inverse operation of the break statement. example: main() { int value,i; i=0; while(i<=10) { printf("enter number:"); scanf("%d",&value); if(value<=0) { printf("Zero or -ve value found"); continue; } i++; } } This program segment process only +ve integers. Whenever a zero or -ve value is encountered, the computer will display the message "zero or -ve value found" as an error and it continues the same loop as long as the given condition is satisfied.

goto statement
goto statement The goto statement is used to alter the program execution sequence by transfering the control to some other part of the program. syntax: goto label; Here, label is the valid C identifier. There are 2 ways of goto statements * Conditional goto * Unconditional goto UnConditional goto:The unconditional goto statement is just used to transfer the control from one part of the program to other part without checking any condition. example: main() {

C Language Notes
start: printf("Welcome to yellowpen.co.in"); goto start; } Conditional goto: The conditional goto is used to transfer the control of the execution from one part of the program to the other in certain conditional cases. example: main() { int value,i; i=0; while(i<=10) { printf("enter number:"); scanf("%d",&value); if(value<=0) { printf("Zero or -ve value found"); goto error; } i++; } error: printf("Input data error"); }

Programming On Conditional Expressions Programming On While Loop Programming On for Loop Technical Interview On Control Statements C FAQ's by top companies CSE Computer Programming LAB Excercises

(4).Arrays in C Arrays
An array is a collection of identical data objects which are stored in consecutive memory locations under a common heading or a variable name. (or) An array is a group or a table of values referred to by the same variable name. (or) Arrays are set of values of the same type, which have a single name followed by an index. The individual values in an array are called elements. Array elements are

C Language Notes
also variables. Square brackets appear arround the index right after the name, with the first element referred to by the number. Whenever an array name with an index appears in an expression, the C compiler assumes that element to be of an array type.

Array Declaration
Declaring the name and type of an array and setting the number of elements in the array is known as dimensioning the array. Before linear or multidimensional array used in the program we must provide the compiler the following information. * Type of the array (i.e integer, floating point, char type etc.) * Name of the array * Number of subxcripts in the array (i.e., whether the array is 1D or 2D) * Total number of memory locations to be allocated. syntax for 1D array storage_class data_type array_name[index];

where, storage_class refers to the scope of the array variable such as external, static, or an automatic. data_type used to declare the nature of the data elements stored in the array like character is the type, integer name of or floating the type. array. array_name

index is used to declare the size of the memory locations required for further processing by the program. index should be integer value and it starts from 0 and ends with n-1. Array in the memory: 0 1 2 3 ....................n-1

example: int marks[300]; char name[100]; float avg[20];

Programming on Arrays Technical Interview on Arrays C FAQ's by top companies CSE Computer Programming LAB Excercises

Array Initilization

C Language Notes
storage_class data_type array_name[index]={ele-1,ele-2......ele-n}; where, storage_class refers to the scope of the array variable such as external, static, or an automatic. data_type used to declare the nature of the data elements stored in the array like character type, integer or floating array_name is the name of the array. index is used to declare the size of the memory locations required for further processing by the program. Index should be integer value and it starts from 0 to n-1. the elements are placed one after another within the braces and finally ends with the semicolon example: int value[5]={10,20,30,40,50}; char sex[2]={'M','F'}; The above array is represented in the memory as follows value[0]=10; value[0]=20; value[0]=30; value[0]=40; value[0]=50; sex[0]='M'; sex[1]='F';

Array Processing
Address of integer array elements in the array: eg: int a[5]; let us say it starts with 658000 initially Array in the memory with the addresses is 0 1 2 3 4

&a[0]=658000;

&a[1]=658002;

&a[2]=658004; &a[3]=658006;

&a[4]=658008;

Note:total memory occupied for an array is depends on the datatype of the array for example: * If we declare integer array of size 10 elements, the total memory occupied by the array is 10*2=20 bytes.(because for 1 integer 2 bytes memory is required) * If we declare character array of size 10, it requires 10*1=10 bytes memory * If we declare float array of size 10, it requires 10*4=40 bytes memory. defining an array: main() { int a[5]={8,9,0,1,3}; int i; /*displaying array elements on the screen*/

C Language Notes
for(i=0;i<=4;i++) /* i is the looping variable { and index from 0 to 4*/ printf("%3d",a[i]); } } Array in the memory 0 1 2 3 4 5

8 9 0 1 3
and eachalled with index of the element like a[0]=8; a[1]=9; a[2]=0; a[3]=1; a[4]=3;

Two Dimensional Arrays


Two dimensional array will be in the form of rows and columns format. Syntax: storage_class datatype arrayname[rows][cols]; where storage_class refers to scope of the array variable such as external, static, automatic or register. datatype refers to the nature of the data elements in the array such as character type, integer type, or float etc., arrayname refers to multidimenstional array. rows refers to the number of rows of the array. cols refers to the number of columns of the array. Two Dimensional Array in the memory 0 1 2

0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2


Address of each element in 2-D integer Array: eg: int a[3][3];let us say it starts with 658000 initially Array in the memory with the addresses is &a[0][0]=658000 &a[0][1]=658002 &a[0][2]=658004 &a[1][0]=658006 &a[1][1]=658008 &a[1][2]=658010 &a[2][0]=65812 &a[2][1]=658014 &a[2][2]=658016 Note:Elements in the 2-D array depends on the size of the array. In the a[3][3] integer array, there will be 3*3=9 elements

Char Array
Charcter array mainly used to declare alpha numeric characters. The general syntax for defining character array is storage_class char_data_type array_name[exp]; The storage class is optional and it may be either one of the scope of the

C Language Notes
variable such as auotmatic, external, static or register. array_name is the any valid C identifier. exp is a +ve integer constant. example: char name[50]; char address[100]; Character array in the memory

R A V I \0
Each element of the array is placed in a definite memory space and each element can be accesssed seperately. The array element should end with the null character as a reference for the termination of the character array. Initializing the character array: char name[5]="Ravi"; The elements would be assigned to each of the character array position in the following way name[0]='R'; name[1]='a'; name[2]='v'; name[3]='i'; The character array always terminate with the null character, that is a back -slash followed by a letter zero. And the computer will treat them as a single character. The null character will be added automatically by the C compiler provided there is enough space to accommodate character. example: char line[]="this is a test program"; Here, the square brackets are empty. The array size would have been specified as part of the array definition.

One Dimenstional Array


To find out ith element in the array When a[0] is given &a[i]= &a[0]+((i-1)*scalefactor) scale factor is the size of the datatype example: Let us take the following integer Array 0 1 2 3 4

&650800

&650802

&650804

&650806

&650808

&650810

To find out the address of 4th element in the array &a[6]=&a[0]+((4-1)*scalefactor) &a[6]=650800+(3*2) /*for integer 2 bytes memory, so here =650800+6 scalefactor will be 2*/ =6

(5).Strings in C Strings

C Language Notes
Sequence of characters enclosed in double quotes is called a string. A character array is also called as a string. And every string ends with a null character '\0'. Initializng a string char site[]={'y','e','l','l','o','w','p','e','n'}; char site[10]={'y','e','l','l','o','w','p','e','n','\0'}; char site[10]="yellowpen"; Reading string from the keyboard: main() { char site[10]; printf("Enter string:"); scanf("%s",site); } Writing string to the screen: main() { char site[10]; printf("Enter string:"); scanf("%s",site); printf("Given string:%s",site); }

getchar()
getchar() is used to read a single character from the keyboard. example to read a single character using getchar() main() { char s; printf("\nEnter any character:"); s=getchar(); printf("\nEntered character:%c",s); }

putchar()
putchar() is used to print the single character on the screen. example to write a single character on the screen using putchar() main() { char s; printf("\nEnter any character:"); s=getchar(); printf("\nEntered character:"); putchar(s); }

strlen()

C Language Notes
strlen() function is used to find out the length of the given string. It takes the string as a parameter and returns the integer value. syntax: strlen(str); example: strlen("yellowpen"); example code on strlen() main() { char s[100]; static int i,len; clrscr(); printf("/nEnter the string:"); gets(s); len=strlen(s); printf("/nlength=%d",len); getch(); } o/p: Enter the string:yellowpen length=9

strrev()
strrev() function is used to reverse the given string. It takes the string as the parameter. syntax: strrev(str); example: strrev("yellowpen"); example code on strrev() main() { char s[100]; clrscr(); printf("/nEnter the string:"); gets(s); printf("/nlength=%s",strrev(s)); getch(); } o/p: Enter the string:yellowpen reverse string is nepwolley

strcpy()
strcpy() function is used to copy the one string into another. It takes two string parameters. First string is destination string and another one is

C Language Notes
source string. syntax: strcpy(str1,str2); /*copies str2 into str1*/ example: strcpy(str,"yellowpen"); /* copies "yellowpen" to str*/ example code on strcpy() main() { char s[100],str[100]; clrscr(); printf("/nEnter the string:"); gets(s); strcpy(str,s); printf("/nOriginal string is:",puts(s)); printf("/nCopied string is:",puts(str)); getch(); } o/p: Enter the string:this is c programming original string: this is c programming copied string: this is c programming

strcat()
strcat() function is used to combine two given strings. It takes two string parameters. syntax: strcat(str1,str2); example: strcat("yellowpen","website"); example code on strcat() main() { char s[100],c[100]; clrscr(); printf("/nEnter first string:"); gets(s); printf("/nEnter second string:"); gets(c); printf("/nAfter concatenation: %s",strcat(s,c)); getch(); } o/p: Enter first string:yellowpen Enter second string:website After concatenation: yellowpenwebsite

strcmp()

C Language Notes
strcmp() function is used to compare two given stirngs. It takes two string parameters. The strcmp() returns 0 if two strings are alphabetically equal. The strcmp() returns +ve value if first string is alphabetically greater than the second string. The strcmp() returns the -ve value if first string is alphabetically lessthan the second string. syntax: strcmp(str1,str2); example: strcmp("abc","abc"); example code on strmp() main() { char s[100],c[100]; clrscr(); printf("/nEnter first string:"); gets(s); printf("/nEnter second string:"); gets(c); if(strcmp(s,c)==0) printf("strings are equal"); else if(strcmp(s,c)>0) printf("/n first string is biggerthan second"); else printf("/nsecond string is biggerthan first"); getch(); }

strupr()
strupr() function is used to convert the given string into uppercase. It takes the string as parameter. syntax: strupr(str); example: strupr("yellowpen"); example code on strupr() main() { char s[100]; clrscr(); printf("/nEnter string:"); gets(s); printf("/nstring in uppercase:%s",strupr(s)); getch(); } o/p: Enter string:yellowpen string in uppercase:YELLOWPEN

C Language Notes
strlwr()
strlwr() function is used to convert the given string into lowrcase. It takes the string as parameter. syntax: strlwr(str); example: strlwr("yellowpen"); example code on strlwr() main() { char s[100]; clrscr(); printf("/nEnter string:"); gets(s); printf("/nstring in lowercase:%s",strlwr(s)); getch(); } o/p: Enter string:YELLOWPEN string in lowercase:yellowpen

Array of strings
Array of strings can be declared as two dimensional array. The following is the syntax for array of strings. char_datatype array_name[No.of strings][size of each string]; example: char name[3][20]; Initializing array of strings char name[3][20]={"yellowpen","for","beginers"}; Code for reading three strings main() { char s[3][100]; static int i; clrscr(); for(i=0;i<3;i++) { printf("/nEnter %d string:",i+1); gets(s[i]); } for(i=0;i<3;i++) { printf("/n%d sting: ",i+1); puts(s[i]); }

C Language Notes
getch(); }

(6).Structures in C Structures
Structure is a collection of hetrogeneous datatypes grouped together. When this is done, the entire collection can be refered to by a structure name. The individual components are called fields or members. And these fields or members are accessed or processed seperately. A structure definition is specified by the keyword struct. This is followed by user defined name surrounded by braces, which describes the members of the structure. A member of a strucutre is a single unit. Structure format storage_class struct user_defined_name { data_type mem1; data_type mem2; data_type mem3; . . . data_type mem n; }; The storage_class is optional, whereas the keyword struct and the braces are essential The user_defined_name is usually used. The datatype and members are any valid C data objects such as int, float and char. example: struct date`s { int day; int month; int year; }; Each member of a structure is specified by a variable name with a period and the member name. The period is a structure member operator which we can be refered simply as the period operator.

Structures Initialization
A structure can be initialized in two ways. Consider the following student particulars. struct school { int rollno,age; char sex; float height,weight; }; First method:static struct school student= {1010,24,'M',167.9,56.7}; The compiler assigns the following values to each of the fields. rollno = 1010 age = 24 sex = 'M' height = 167.9 weight = 56.7 Second Method: student s; s.rollno=1010; s.age=24; s.sex='M';

C Language Notes
s.height=167.9; s.weight=56.7;

Array of Structures
An array is a group of identical data which are stored in consecutive memory locations in a common heading or a variable. A similar type of structure is placed in a common heading or a common variable name is called arrays of structures. example:If one would process the student's particulars for the entire school(more than one or two students) then array of structures are needed. example: struct school { int rollno,age; char sex; float height,weight; }; school student[300]; The student[300] is a structure variable. It may accomodate the structure of a student upto 300. Each record may be accessed and processed seperately like individual elements of an array.

Initialization of Array of Structures


Initializing Array of Structures: The strucutre can be initialized in the following way. struct school { int rollno,age; char sex; float height,weight; }; school student[2]={ {5001,24,'M',67.9,56.7}, {5002,25,'M',67.9,56.7} }; The C compiler will assign the values to the individual elements of the particular structure in the following way For the first record student[0].rollno=5001; student[0].age=24; student[0].sex='M'; student[0].height=67.9; student[0].weight=56.7; For the second record student[1].rollno=5002; student[1].age=25; student[1].sex='M'; student[1].height=67.9; student[1].weight=56.7;

Arrays within Structures


A member of a structure can be an array datatype also. i.e., we can declare array as member in structure. example:

C Language Notes
struct school { char name[20],sex; int rollno,age; float height,weight; }; The C compiler initialize the members in the following way. school student[2]= { {"Ravi",'M',5001,24,156.6,56.7}, {"Ramu",'F',5002,25,156.6,56.7} }; The C compiler asigns the values to its members of a structure as student[0].name[]="Ravi"; student[0].sex='M'; student[0].rollno=5001; student[0].age=24; student[0].height=156.6; student[0].weight=56.7; and so on. In case if some of the members are not initialized explicitly, the compiler will treat them as zero.

Nested Structures
In C, we can use a structure as a member of another structure. When a structure is declared as member of another structure, it is called a nested structure or structure within a structure. example: struct date { int day,month,year; }; struct student { char name[20],sex; int rollno; struct date dob; }; To process the individual elements in a nested structure, first we have to declare the structure variable of the date structure(dob) and then its individual fields.

(7).Functions in C Functions
A complex program may be decomposed into a small or easily manageable parts or modules called functions. Functions are very useful to read, write, debug and modify complex programs. They can also be incorporated in the main program. In C, the main() itselff is a function that means the main function is invoking

C Language Notes
the other functions to perform various tasks. Advantages of using functions: * easy to write a correct small functions. * easy to read, write and debug a function. * easier to maintain or modify such a function * small functions tend to be self documenting and highly readable. * it can be called any number of times in any place with different parameters

Defining Functions
Defining the function has the following syntax. functiontype functionname(datatype argument1, datatype argument2......) { body of function --------------------------return (statement); } Declaring the type of a function: The function refers to the type of value it would return to the calling portion of the program. Any of the basic datatypes such as int, float, char etc. may appear in the function declaration. example: int functionname(....); float functionname(....); char functionname(....); Function Name: Normally a function name is made relevant to the function operation, as it will be easy to keep a track of it, whenever a transfer of similar functions is used in the main program. example:dec counter(); square(); Formal arguments: example: void square(int a,int b) /*a and b are formal arguments*/ { ---} Function body:After declaring the type of a function, function name and formal arguments, a statement or block of statemnts are enclosed between open and close braces is a function body.

Actual and formal arguments


The arguments may be classified under two groups actual and formal arguments. Actual Arguments: An actual argument is a variable or an expression contained in a function call that replaces the formal parameter which is a part of the function declaration. Sometimes, a function may be called by a portion of a program with some parameters and these parameters are konwn as the actual arguments. example:

C Language Notes
main() { int x,y; void sum(int x,int y); ----------sum(x,y); /*x and y are actual arguments*/ } Formal Arguments: Formal arguments are the parameters present in a function definition which may also be called as dummy arguments or the parametric variables. When the function is invoked, the formal parameters are replaced by the actual parameters. example: main() { int x,y; void sum(int x,int y); ----------sum(x,y); /*x and y are actual arguments*/ } sum(int a,int b) /* a and b are formal or dummy parameters*/ { ----}

Local and Global variables


The variables in general may be classified as local or global variables. Local Variables: The variables which are define inside a function block or a compound statement is known as local variables. example: sum(int a,int b) { int x,y;/*local variables*/ ------} Global Variables: Global variables are variables defined outside the main function block. These variables are refered by the same data type and by the same name through out the program in both the calling portion of a program and in the function block. example: int a,b=5; /*global variables*/ main() { int sum(); a=10; ----------sum(); } sum() {

C Language Notes
int s; s=a+b; return s; }

Return Statement
The keyword return is used to terminate function and return a value to its caller. The return statement may also be used to exit a function without returning a value. The return statement may or maynot include an expression. syntax: return; return (exp); example: return; return(345); return(a+b); return(++i); The return statement terminates the execution of the function and pass on the control back to the calling environment.

Function Types
The functions are mainly divided into two types. * Library Functions. * User defined Functions. Library Functions: The following are the standard library functions in C. <assert.h> <ctype.h> <errno.h> <float.h> <limits.h> <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h> <stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h> User defined Functions: The user defined functions are classified in 3 ways based on the formal arguments passed and the usage of the return statement. functions with no arguments and no return types functions with arguments and no returntypes functions with arguments and returntypes

Function with no arguments and no return Types


It is the simplest way of writing a user defined function in C. There is no data communication between the calling portion of a program and a called

C Language Notes
function block. The function is invoked by a calling environment by not passing any formal argument and the function also does not return back any value to the caller. example: main() { clrscr(); add(); /*calling function*/ } add() /*called function*/ { float x,y; printf("/nenter 2 floating point nos:"); scanf("%f%f",&x,&y); printf("/nsum of two floating point nos=%f",x+y);

Function with arguments and no return Types


The second type of user defined function passes some formal arguments to a function but the function does not return back any value to the caller. It is a one-way data communication between a calling portion of a program and the function block. example: main() { long int n; clrscr(); printf("/nenter no:"); scanf("%ld",&n); amstrom(n); /*we are passing 'n' value as the argument to the function amstrom and 'n' is the actual argument*/ getch(); } amstrom(a) /*'a' is the formal argument and it gets the value of 'n' */ int a; { int c,s=0,d; c=a; while(a!=0) { d=a%10; s=s+(d*d*d); a=a/10; } if(s==c) printf("/nAmstrom number"); else printf("/nNot amstrom number"); }

Function with arguments and return Types


The third type of user defined function passes some formal arguments to a function from a calling portion of the program. And the computed value, if

C Language Notes
any is transfered back to the caller. Data are communicated between both the calling portion of a program and the function block. example: main() { int n,f; clrscr(); printf("/nEnter number:"); scanf("%d",&n); f=fact(n); printf("/n%d!=%d",n,f); getch(); } int fact(n) int n; { int i,f=1; for(i=n;i>=1;i--) f=f*i; return f; }

Passing Arrays to Functions


The entire array can be passed on to a function in C. An array name can be used as an argument for the function declaration. No subscripts are required to invoke a function using arrays. example: main() { int sumarray(int a[],int n); int a[10],sum; --------------------------sum(a,n); /*passing array to Function*/ }

Passing structures to Functions


A structure can be passed to a function as a single variable. The scope of a structure declaration should be an external storage class whenever a function in the main program is using a structure data types. The field or member data should be same throughout the program either in the main or in a function. example: struct sample { int x; float y; }; sample first; main() { display(struct sample one); /*Function declaration*/

C Language Notes
--------------------------display(one); /*Function calling*/ }

Recursive Functions
A function which calls itself directly or indirectly again and again is known as the recursive function. Recursive functions are very useful while constructing the data structures like linked lists, double linked lists and trees. There is a dintinct difference between normal and recursive functions. A normal function will be invoked by the main function whenever the function name is used. whereas the recursive function will be invoked by itself directly or indirectly as long as the given condition is satisfied. example: recursive function for factorial is n*fact(n-1) It works in the following way. Let us assume n=5 5*fact(5-1)->5*fact(4) 4*fact(4-1)->4*fact(3) 3*fact(3-1)->3*fact(2) 2*fact(2-1)->2*fact(1) 1*fact(1-1)->1*fact(0) syntax: main() { function(); /*calling function*/ --------------} function() { --------------function();/*function call recursively*/ }

(8).Pointers in C Pointors
pointor: A pointor is a variable which contains the address of memory location of another variable. A pointor provides an indirect way of accessing the value of a data item. Uses of pointors: * pointors are used to communicate information about memory. * pointors are used to saving memory. * With the pointors data manipulation is done with the address, so the execution time is faster. * pointors are used to return more than one value from a function. * To pass arrays and strings more conveniently from one function to another.

C Language Notes
* pointors are used to allocate memory and access it [dynamic memory allocation]. * pointors are used to create complex datastructures like linked lists.

Pointor Operators
A pointor contains a memory address. Most commonly, this address is the location of another variable where it has been stored in memory. If one variable contains the address of another variable, then the first variable is said to point to the second. In C, pointors are distinct such as integer pointors, floating point number pointor, character pointor etc., A pointor variable consists of two parts. (a) the pointor operator (b) the address operator Pointor Operator: A pointor operator can be represented by a combination of *(asterisk) with a variable. syntax: datatype *pointor_variable; where, datatype is a type of pointor variable such as integer, char and float.. pointor_variable is the any valid C identifier. example: int *iptr; Here, iptr is a pointor variable which holds the address of an integer datatype. Address Operator: An address operator can be represented by a combination of &(ampersend) with a pointor variable. The & is a unary operator that returns the memory address of its operand. A unary operator requires only one operand. example: m=&iptr; Here, the m recieves the address of iptr.

Pointor Operators
We + * / % ++ -can perform the following arthimatic operators on pointors addition eg: *c=*a+*b; subtraction eg: *c=*a-*b; multiplication eg: *c=*a**b; division eg: *c=*a/*b; modulus eg: *c=*a%*b; increment and decremant

Note: ++operator causes the pointor to be incremented, but not by 1. --operator causes the pointor to be decremented, but not by 1. example: int value, *ptr; value=120; ptr=&value; ptr++; printf("%u\n",ptr); The pointor ptr is originally assigned the value 2000. The incrementation, ptr++ increments the number of bytes according to the datatype.

C Language Notes
And also we can compare two pointor varibales by using following comparision operators > greater than < less than >= greater than or equals to <= less than or equal to == equals to != not equal to.

Pointor And 1D Arrays


example: int value[20]; int *ptr; Here, the pointor variable holds the address of first element in the value array i.e address of value[0].means ptr=&value[0] (or) ptr=&value[] we can use the pointors in the following way ptr++==value[1]; *ptr==&value[0]; *ptr==value[]; *(ptr+6)==value[6]; ptr++==&vale[1]; /*example for reading and writing one dimensional array*/ main() { static int a[10],i,n=5; int *temp; printf("/nenter elements"); for(i=0;i<=n-1;i++) scanf("%d",&a[i]); temp=&a[0]; /*Address of 0th element*/ for(i=0;i<=n-1;i++) printf("/n%d",*(temp+i)); /*Address of ith element*/ } Note:The above program will be executed in the following way also main() { static int a[4]={11,12,13,14}; int i,n,temp; clrscr(); for(i=0;i<=3;i++) { temp=*((a)+(i)); printf("/n%d",temp); } }

Pointor And 2D Arrays


A pointor to an array contains the address of the first element.In one dimensional array, the first element is &a[0] but in the two dimensional array the first element is &a[0][0] example: int a[][]; int *ptr; ptr=a; /*the address of 0throw and the 0th

C Language Notes
row of the 2d array a is assigned to the ptr. /*example for reading and writing two dimensional array*/ main() { static int a[10][10]; int i,j,n=2,m=2; clrscr(); printf("/nenter elements"); for(i=0;i<=n-1;i++) for(j=0;j<=m-1;j++) scanf("%d",&a[i][j]); for(i=0;i<=n-1;i++) for(j=0;j<=m-1;j++) printf("/n%d",*(*(a+i)+j)); getch(); }

Pointor And Functions


Pointors are very much used in a function declaration. Sometimes only with a pointor a complex function can be easily represented and accessed. The use of pointors in a function definition may be classified into two groups. Call by value Call by reference

Call by value
Whenever a function is called, the control will be transfered from the main to the called function and value of the actual argument is copied to the function. Within the function, the actual value copied from the calling portion of the program may be altered or changed. When the control is transfered back from the called function to the calling protion of the program, the altered values are not transfered back. This type of passing formal arguments to a function is technically known as call by value. example:/*Swapping of two variables*/ main() { int a=10,b=20; printf("/nBefore swaping a=%d b=%d",a,b); swap(a,b); printf("/nAfter swaping a=%d b=%d",a,b); } swap(int a,int b) { a=a+b; b=a-b; a=a-b; }

C Language Notes
o/p: Before swaping a=10 b=20 After swaping a=10 b=20 Explanation:In the above example, the values won't be changed. Why because when we declare a and b in the calling function, some memory will be allocated to a and b. And for a and b in the called function some other memory will be allocated and those are temporary varibles. according to the definition of swap() function the values will be changed in the temporary varibales but not in the actual variables.

Call by Reference
When a function is called by a portion of a program, the address of the actual arguments are copied onto the formal arguments, though they may be refered by different variable names. The content of the variables that are altered within the function block are returned to the calling portion of a program in the altered itself, as the formal and the actual arguments are referencing the same memory location or address. This is technically known as call by reference or call by address or call by location. /*swapping of two varibales*/ main() { int *a=10,*b=20; printf("/nBefore swaping a=%d b=%d",a,b); swap(&a,&b); printf("/nAfter swaping a=%d b=%d",a,b); } swap(int *a,int *b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; } o/p: Before swaping a=10 b=20 After swaping a=20 b=10 Explanation:Here we are passing the reference of the variblaes(address) but not the direct value so, the values will be interchanged in the original memory location. so, the values will be interchanged

Pointors And Structures


A pointor can be used to hold the address of the structure variable too. The

C Language Notes
pointor variable is very much used to construct complex data structures such as linked lists, double linked lists and binary trees etc., example: struct sample { int x; char y; }; struct sample *ptr; Where ptr is a pointor variable holding the address of the structure sample and is having three members such as int x,char y; The pointor structure variable can be accessed and processed in one of the following ways: 1. (*structure_name).field_name=variable; 2. structure_name -> field_name=variable; example: struct sample { int x; char y; }; struct sample *ptr; (*ptr).x=10; (or) (*ptr).y='y';

ptr->x=10; ptr->y='y';

Pointors To Pointors
The pointor to a pointor is a form of multiple of indirections or a class of pointors. In the case of a pointor to a pointor, the firs pointor contains the address of the second pointor, which points to the variable that contain the values desired. example: int **ptr2; where ptr2 is a pointor which holds the address of the another pointor.

(9).Files in C Files
File: A file is collection of records. Record: collection of fields. Field: Individual thing or entry. File Pointor: A file pointor is a pointor to structure which contains information about the file including its name, current position of the file. declaration: FILE *fp; Basic Operations on file: -> fopen(): This is used to open a file. syntax: fopen("filename",mode); There are several modes available

C Language Notes
r: opens a text file for reading. w: opens a text file for writing. a: append to a text file. rb: open a binary file for reading. wb: create a binary file for writing. ab: append to a binary file. rw: opena text file for read/write. wr: create a text file for read/write. r+b: open a binary file for read/write. w+b: create a binary file for read/write. a+b: append a binary file for read/write. example : FILE *fp; fp=fopen("xyz","w"); -> fclose(): To close a file. syntax: fclose(pointor); eg: fclose(fp); -> fputc(): Writes a character to a file. eg: int fputc(int ch,FILE *fp);

Files
-> fgettc(): Reads a character from the file. eg: int fgetc(FILE *FP); do { ch=fgetc(fp); }while(ch!=EOF); -> fgets(): It reads the entire string from the specified stream. eg: char *fgets(char *str,int length, FILE *fp); -> fputs(): It writes the entire string to the specified file. eg: int fputs(const char *str,FILE *fp); -> feof(): end of file. eg: while(feof(fp)) ch=fgetc(fp); -> fputc(): Writes a character to a file. eg: int fputc(int ch,FILE *fp); -> fprintf(): To write the data into file. eg: fprintf(fp,"content"); -> fscanf(): It reads the data from the file. eg: fscanf(fp,"content");

Example On Files
main() { int no,m1,m2,m3,ch,tot; FILE *fp; clrscr(); do { printf("/n1.Read Data");

C Language Notes
printf("/n2.Get Data"); printf("/n3.Exit"); printf("/nEnter choice:"); scanf("%d",&ch); if(ch==1) { printf("/nEnter student details:"); scanf("%d%d%d%d",&no,&m1,&m2,&m3); fp=fopen("pqr.dat","a"); fprintf(fp,"%d%d%d%d/n",no,m1,m2,m3); fclose(fp); } if(ch==2) { fp=fopen("pqr.dat","r"); while(!feof(fp)) { fscanf(fp,"%d%d%d%d/n",&no,&m1,&m2,&m3); tot=m1+m2+m3; printf("no=%d m1=%d m2=%d m3=%d tot=%d/n",no,m1,m2,m3,tot); } fclose(fp); } if(ch==3) exit(0); }while(ch!=3); getch(); }

(11).Storage Classes in C Storage Classes


c language supports 4 types of storage clasees to store the variables. A variable storage class tells us: (i) where the variable would be stored (ii) what will be the initial value of the variable (i.e default value) iii) what isthe scope of the variable i.e in which functions the value of the variable would be available (iv) what is the life of the variable; i.e how long would be the varibale exist. The 4 storage classes are Auto Extern Static Register

Auto
automatic variables are nothing but local variables. syntax: auto datatype var; * automatic variables are stored in memory

C Language Notes
* Default value is garbage value * scope is local to the block in which the variable is defined. * lifetime is till the control remains within the block in which the variable is defined eg: main() { auto int x=20; printf("x=%d",x); { auto int y=2; auto int x=35; printf("/nx=%d /t y=%d",x,y); } printf("/nx=%d",x); } o/p: x=20 x=35 x=20

y=2

Extern
external variables are global variables. syntax:extern datatype var; * * * * extern varibales are stored in memory default value is zero scope is throughout the function where it is defined the extent of external variable is alive upto the termination of program.

example: extern int p=4; main() { printf("%d",p); p=29; printf("%d",p); } o/p: p=4 p=29

Static
static variables are permanent variables within their own functions. syntax: static datatype var; * static variables are stored in memory * default value is zero * scope is local to the block in which the variable

C Language Notes
is defined. * lifetime is throughout the block. example: void increment(); void main() { increment(); increment(); increment(); } void increment() { static int i=1; printf("/n%d",i); i=i+1; } o/p: 1 2 3

Register
when operands are brought into processor, they stored up high speed storage. Those are called registers. Each register can store one word of data i.e 16 bits. * stored in registers * default value is garbage value * scope is local to the block in which the variable defined. * lifetime is till the control remains within the block in which the variable is defined.

(12).Command Line Arguments in C Command Line Arguments


sometimes it is useful to pass information into a program when running it. The information is passed into main() through command line arguments. A command line argument is the information that follows the program name on the command line of the operating system. There are 2 special built-in arguments (a) argv[] : It is the character array pointor. Each element in this array points to a command line argument. All command line arguments are strings. (b) argc : It holds no.of arguments on the command line and is an integer.

C Language Notes
Note:The value argc is atleast one because the name of the program qualifies as the first argument. Example: main(int argc,char *argv[]) { int i=1; clrscr(); while(argv[i]!=NULL) printf("%s",argv[i++]); printf("%d",argc); } o/p: F:/TC/BIN>cmdlines a b c d abcd5

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