What is C?What is C?CC is a programming language is a programming languagedeveloped at AT & T’s Belldeveloped at AT & T’s BellLaboratories of USA in 1972. It Laboratories of USA in 1972. It
waswasdesigned and written by a mandesigned and written by a mannamed named Dennis Ritche .Dennis Ritche .
Features of CFeatures of C
Portability or machine Portability or machine independentindependent
Sound and versatile languageSound and versatile language Fast program execution.Fast program execution. An extendible language.An extendible language. Tends to be a structured Tends to be a structured
language.language.
Historical developments Historical developments of Cof C
Year Year Language Language Developed by Developed by RemarksRemarks19601960 ALGOLALGOL International International
committeecommitteeToo general, too Too general, too abstract abstract
19631963 CPLCPL Cambridge University Cambridge University Hard to learn, Hard to learn, difficult to difficult to implement implement
19671967 BCPLBCPL Martin Richards at Martin Richards at Cambridge university Cambridge university
Could deal with Could deal with only specific only specific problems problems
19701970 BB Ken Thompson at AT Ken Thompson at AT & T& T
Could deal with Could deal with only specific only specific problems problems
19721972 CC Dennis Ritche at AT Dennis Ritche at AT & T& T
Lost generality of Lost generality of BCPL and B BCPL and B restored restored
Character set of the C Character set of the C languagelanguage
This indicates group of characters which are This indicates group of characters which are useful touseful to
write the programming statements. It contains 3 write the programming statements. It contains 3 parts.parts.
AlphabetsAlphabets:: C language supports upper case C language supports upper case letters (A to Z), lower case letters from letters (A to Z), lower case letters from
(a to z). But both are different. C is a case (a to z). But both are different. C is a case sensitive language. sensitive language.
Numeric digitsNumeric digits:: C language contains the C language contains the numeric digits from 0 to 9.numeric digits from 0 to 9.
Special CharactersSpecial Characters:: The characters other The characters other than alphabets and numeric digits are called as than alphabets and numeric digits are called as special characters.special characters.
IdentifiersIdentifiers
It identifies a memoryIt identifies a memorylocation. In order to location. In order to identifyidentify
any value identifier is any value identifier is used.used.
ConstantsConstants
It is a quantity which does It is a quantity which does notnot
change its value during change its value during thethe
program execution. program execution. ConstantsConstants
are 4 types.are 4 types.
Integer Constants:Integer Constants: These are the numbers without These are the numbers without decimal point or exponent.decimal point or exponent.Ex:-Ex:- int a=10; int a=10;
Float constants:Float constants: These are the numbers with decimal These are the numbers with decimal point or exponent.point or exponent.Ex:-Ex:- float pie=3.14; float pie=3.14;
Single Character Constants:Single Character Constants: It is any one of the It is any one of the single character enclosed in single quotation.single character enclosed in single quotation.
Ex:-Ex:- char ch=’a’; char ch=’a’; char section=’b’;char section=’b’; String constants:String constants: Group of characters enclosed with in Group of characters enclosed with in
double quotations.double quotations.Ex:-Ex:- char name[20]= “Chandra”; char name[20]= “Chandra”;char nation[10]= “India”;char nation[10]= “India”;
VariablesVariables
It is a value that changes its value It is a value that changes its value during program execution. during program execution. Variables are 4 types.Variables are 4 types.
1. Integer variables1. Integer variables 2. Float variables2. Float variables 3. Single character variables3. Single character variables 4. String variables.4. String variables.
Rules to write variable namesRules to write variable names
A variable name contains maximum of A variable name contains maximum of 30 characters.30 characters.
A variable name includes alphabets and A variable name includes alphabets and numbers, but it must start with an numbers, but it must start with an alphabet.alphabet.
It cannot accept any special characters, It cannot accept any special characters, blank spaces except under score( _ ).blank spaces except under score( _ ).
It should not be a reserved word.It should not be a reserved word.
key words (or) Reserved key words (or) Reserved wordswords
Keywords are the words whose meaning hasKeywords are the words whose meaning hasalready been explained to the C compiler. Thealready been explained to the C compiler. Thekeywords cannot be used as variable names. keywords cannot be used as variable names. They areThey are
autoautodefaultdefaultenum enum ififshortshortswitchswitchvolatilevolatile
breakbreakdodoexternexternintint signedsignedtypedoftypedofwhile while
casecasedoubledoublefloatfloatlonglong sizeofsizeofunionunion
charcharelseelsefor for registerregisterstaticstaticunsignedunsigned
constconstcontinue continue gotogotoreturnreturnstructstructvoidvoid
Data typesData types
Data typeData type RangeRange BytesBytes FormatFormatsigned charsigned char -128 to +127 -128 to +127 11 %c%cunsigned charunsigned char 0 to 255 0 to 255 11 %c%cshort signed intshort signed int -32,768 to -32,768 to
+32,767 +32,767 22 %d%d
short unsigned short unsigned int int
0 to 65,535 0 to 65,535 22 %u%u
long signed intlong signed int -2147483648 to -2147483648 to +2147483647 +2147483647
44 %ld%ld
long unsigned long unsigned int int
0 to 4294967295 0 to 4294967295 44 %lu%lu
Float Float -3.4e38 to -3.4e38 to +3.4e38 +3.4e38
44 %f%f
Double Double -1.7e308 to -1.7e308 to +1.7e308 +1.7e308
88 %lf%lf
long doublelong double -1.7e4932 to -1.7e4932 to 1.7e4932 1.7e4932
1010 %lf%lf
Data typesData types
Data typeData type RangeRange BytesBytes FormatFormatunsigned charunsigned char 0 to 255 0 to 255 11 %c%cintint -32,768 to -32,768 to
+32,767 +32,767 22 %d%d
longlong -2147483648 to -2147483648 to +2147483647 +2147483647
44 %ld%ld
Float Float -3.4e38 to -3.4e38 to +3.4e38 +3.4e38
44 %f%f
Double Double -1.7e308 to -1.7e308 to +1.7e308 +1.7e308
88 %lf%lf
Input and Output Input and Output functionsfunctions
Output FunctionOutput Function printf( )printf( ):: This function is used to display This function is used to display
the information on the screen. It the information on the screen. It displays the variable values and the displays the variable values and the string values. This function belongs to string values. This function belongs to stdio.h.stdio.h.
Syntax:Syntax: printf(“control string” ,variable list);printf(“control string” ,variable list);Ex:-Ex:- int a=10; int a=10;
printf(“\n The value of a is %d”,a);printf(“\n The value of a is %d”,a);
Input functionsInput functions
Scanf( ):-Scanf( ):- It is an input function, that is It is an input function, that is used to accept the values into variables at used to accept the values into variables at the time of executing a program. This the time of executing a program. This function belongs to function belongs to stdio.h .stdio.h .
Syntax:Syntax: Scanf(“control string”, variable Scanf(“control string”, variable list);list);
Ex:-Ex:- int a;int a; scanf(“%d”, &a);scanf(“%d”, &a);
Structure of a C programStructure of a C program/* Comment line section */ /* Comment line section */ Documentation Documentation
optionaloptional# header file section # header file section when we use when we use
predefined functions predefined functions main( )main( ){{ Declaration part; Declaration part; To declare the variables To declare the variables
which are used in the which are used in the programprogram Initialization part; Initialization part; To initialize i.e. giving To initialize i.e. giving
values to the variables. values to the variables. Execution part; Execution part; To execute as output. To execute as output.}}
A C program starts with the includeA C program starts with the includestatement. This statement is used to statement. This statement is used to
linklinkthe header files into our program. Thisthe header files into our program. Thisstatement should start with # symbol.statement should start with # symbol.Ex:-Ex:- # include <stdio.h> # include <stdio.h>
stdio.h stands for standard input stdio.h stands for standard input output . header fileoutput . header file
Comment Line SectionComment Line Section
In order to give documentation In order to give documentation for a program comment line is for a program comment line is includes. It is enclosed in includes. It is enclosed in between a /* */ because in the between a /* */ because in the compilation process these lines compilation process these lines are not includes.are not includes.
Header file sectionHeader file section‘‘C’ program consists of predefined C’ program consists of predefined functions for that reason we should functions for that reason we should include the files in which they are include the files in which they are defined. Which are saved with .h defined. Which are saved with .h as extension.as extension.
Main( )Main( )
The compilation and the The compilation and the running process is done with running process is done with the help of Main( ). A ‘C’ the help of Main( ). A ‘C’ program definitely requires program definitely requires Main( ).Main( ).
Declaration partDeclaration part
This area is where we declare all This area is where we declare all the variables which are used in the the variables which are used in the program.program.
Initialization partInitialization part
Here, we give values to the Here, we give values to the declared values.declared values.
Executable partExecutable part
The output is seen from the The output is seen from the executable part. By using output executable part. By using output functions.functions.
Programming rulesProgramming rules
A ‘C’ program should be written in A ‘C’ program should be written in lowerlower
case. Every statement should end case. Every statement should end with; .with; .
The pair of { } should be matched.The pair of { } should be matched.
Compilation and Execution Compilation and Execution processprocess
After writing the program we After writing the program we should compile by pressing on the should compile by pressing on the Compile option of Compile menu. Compile option of Compile menu. This converts the text format that This converts the text format that is source code into Binary format is source code into Binary format which is called as object code. which is called as object code. After that by pressing Run option After that by pressing Run option the output can be seen.the output can be seen.
OperatorsOperators
Arithmetic operatorsArithmetic operators Relational operatorsRelational operators Logical operatorsLogical operators Assignment operatorsAssignment operators Increment or decrement operatorsIncrement or decrement operators Conditional operatorsConditional operators
Arithmetic OperatorsArithmetic Operators
Arithmetic operators are used to perform Arithmetic operators are used to perform arithmetic operations like addition, arithmetic operations like addition, subtraction, multiplication, division and subtraction, multiplication, division and remainder.remainder.OperatorOperator NameName MeaningMeaning ExampleExample
++ PlusPlus AdditionAddition a+ba+b-- MinusMinus SubtractionSubtraction a-ba-b** AsteriskAsterisk MultiplicationMultiplication a*ba*b// SlashSlash DivisionDivision a/ba/b%% ModulatorModulator ReminderReminder a%ba%b
Relational operatorsRelational operators These operators are used to check the relation between the These operators are used to check the relation between the
values.values. Note:Note:-- When we used relational operators the output is seen When we used relational operators the output is seen
in the form of 0 or 1. If the relation is true the output will be in the form of 0 or 1. If the relation is true the output will be in 1. If the relation is false the output will be 0.in 1. If the relation is false the output will be 0.
Ex:-Ex:- a=10 a=10 b=5b=5
OperatorOperator NameName ExampleExample ResultResult>> Greater thanGreater than a>ba>b 11<< Less thanLess than a<ba<b 00>=>= Greater than or equal toGreater than or equal to a>=ba>=b 11<=<= Less than or equal toLess than or equal to a<=ba<=b 00= == = Equal toEqual to a==ba==b 00!=!= Not equal toNot equal to a!=ba!=b 11
Logical operatorsLogical operators
logical operators are used to combine logical operators are used to combine two or more relational expressions. C two or more relational expressions. C language contains 3 logical operators.language contains 3 logical operators.
OperatorOperator Name Name &&&& AndAnd|||| Or Or !! Not Not
&& :&& : (And) (And) Statement:-Statement:- When all arguments When all arguments
are true then only the total condition are true then only the total condition is true. Any one of the arguments is is true. Any one of the arguments is false the total condition is false.false the total condition is false.
Expressinn1 && Expressinn1 && Expression2Expression2
ResultResult
TT TT TTTT FF FFFF TT FFFF FF FF
Truth table
|| : (Or)|| : (Or)
Statement:-Statement:- When one of the When one of the argument is true the total condition argument is true the total condition is true. If all the arguments are false is true. If all the arguments are false then only the condition is false.then only the condition is false.
Expression1 || Expression2Expression1 || Expression2 ResultResult TT TT TTTT FF TTFF TT TTFF FF FF
Truth table
! (Not)! (Not) Statement:-Statement:- This is the negative This is the negative
operator, we can place the ‘not’ operator operator, we can place the ‘not’ operator before any one of the condition. It returns before any one of the condition. It returns the opposite result of the condition. i.e. It the opposite result of the condition. i.e. It converts true to false and false to true.converts true to false and false to true.
! expression! expression resultresult TT FFFF TT
Truth table
Assignment operatorAssignment operator
C language contains equal to (=) C language contains equal to (=) operator to assign a value or operator to assign a value or expression into a variable.expression into a variable.
Ex:-Ex:- a=10; a=10; a=a+10;a=a+10;
Increment and decrement Increment and decrement operatorsoperators
1.1. IncrementIncrement operator (+ +)operator (+ +)Increment operator is used to increase the value by Increment operator is used to increase the value by 1.1.
Pre Increment( ++a)Pre Increment( ++a) First the value will be incremented, and then First the value will be incremented, and then
the new value will be printed.the new value will be printed.Ex:-Ex:- printf(“%d”,++a); printf(“%d”,++a);
Post Increment(a++)Post Increment(a++) First the value will be printed and then the value First the value will be printed and then the value
will be incremented.will be incremented.Ex:-Ex:- printf(“%d”,a++); printf(“%d”,a++);
2)2) Decrement operator ( - - )Decrement operator ( - - ) Decrement operator is used to decrease the Decrement operator is used to decrease the
value by 1.value by 1.
Pre Decrement (--a)Pre Decrement (--a)If the value is decreased before execution it is If the value is decreased before execution it is called as pre decrement.called as pre decrement.Ex:-Ex:- printf(“%d”,--a); printf(“%d”,--a);
Post Decrement (a--)Post Decrement (a--)If the value is decreased after the execution it If the value is decreased after the execution it is called as post decrement.is called as post decrement.Ex:-Ex:- printf(“%d”,a--) printf(“%d”,a--)
Conditional operatorsConditional operatorsC language contains conditional operators (?, : ). ByC language contains conditional operators (?, : ). Byusing conditional operators we can get the output in using conditional operators we can get the output in
thetheform of statements also. form of statements also. ?? and and :: are called as are called asconditional or temporary operators. conditional or temporary operators.
Syn:-Syn:- (condition) ? printf(“value 1”) : printf(“ value 2”); (condition) ? printf(“value 1”) : printf(“ value 2”);
Ex:Ex:-- (a>b) ? printf(“a is greater than b”):printf(“a is (a>b) ? printf(“a is greater than b”):printf(“a isless than b”)less than b”)
If the condition is true then value1 will be returned, ifIf the condition is true then value1 will be returned, ifthe condition is false then value2 will be returnedthe condition is false then value2 will be returned
Conditional statementsConditional statements
The statements which are executed The statements which are executed according to some condition are according to some condition are called as conditional statements. called as conditional statements.
They are 3 typesThey are 3 types If If If-elseIf-else Nested if-elseNested if-else
IfIf
Statement:Statement: This statement is used to perform conditional This statement is used to perform conditional operations.operations.
Syntax:Syntax: if(condition)if(condition)
{{ statement;statement;
}}
If the condition is true then statement will beIf the condition is true then statement will beexecuted. If the condition is false then it will notexecuted. If the condition is false then it will notexecute statement.execute statement.
If-elseIf-elseSyntax:Syntax:
if(condition)if(condition) {{ statement1;statement1; }}
elseelse {{
statement2;statement2; }}
If the condition is true then statement1 will beIf the condition is true then statement1 will beexecuted, if the condition is false then statement2 executed, if the condition is false then statement2 Will be executed.Will be executed.
Nested if-elseNested if-elseSyntax:Syntax: if(condition1)if(condition1)
{{statement1;statement1;}}elseelseif(condition2)if(condition2){{statement2;statement2;}}elseelse{{statement3;statement3;}}
If the condition1 is true then statement1 will be executed and If the condition1 is true then statement1 will be executed and the remaining statements will be skipped. If the condition1 is the remaining statements will be skipped. If the condition1 is false then it will check the condition2, if it is true then false then it will check the condition2, if it is true then statement2 will be executed. If both condition1 and condition2 statement2 will be executed. If both condition1 and condition2 are false then it will execute statement3.are false then it will execute statement3.
Switch statementSwitch statement It is used to execute one of the options from no. of It is used to execute one of the options from no. of
options. It is also called as multi branching statement.options. It is also called as multi branching statement.
Switch (expression)Switch (expression) {{
case value:case value: statements;statements;case value:case value: statements;statements;default:default: statements;statements;
}}
The expression value may be The expression value may be intint or or charactercharacter type. The switch statement evaluates the expression. It type. The switch statement evaluates the expression. It will select one of the cases based on expression. It will will select one of the cases based on expression. It will execute default statements when no case is selected. execute default statements when no case is selected.
Break statementBreak statement It is used to exit from a looping statement. We can use this in It is used to exit from a looping statement. We can use this in
for, while , do while, and switch statement.for, while , do while, and switch statement.
Ex:-Ex:- break; break;Switch caseSwitch case
Syntax:Syntax: switch(expression)switch(expression){{case 1:case 1:{{}}break;break;case 2:case 2:{{}}break;break;default:default:{{}}}}
Goto statementGoto statement It is used to transfer the control It is used to transfer the control
from one place to another place from one place to another place in the program. It is also called in the program. It is also called as unconditional jumping as unconditional jumping statementstatement
Syntax:-Syntax:- goto <label name> ;goto <label name> ;Ex:-Ex:- goto orbit;goto orbit;
Continue statementContinue statement It is used to transfer the control to It is used to transfer the control to
the beginning of the looping the beginning of the looping statements. If the condition is statements. If the condition is false then the statement is false then the statement is executed. If it is true then the executed. If it is true then the statement is not executed.statement is not executed.
Ex:-Ex:- continue; continue;
Loop control structuresLoop control structures
LOOPING:-LOOPING:- The process of executing aThe process of executing ablock of code repeatedly is called asblock of code repeatedly is called aslooping. They are 4 typeslooping. They are 4 types For loopFor loop While loopWhile loop Do while loopDo while loop Nested for loopsNested for loops
All the four loops are used for same process All the four loops are used for same process butbut
there syntax is different.there syntax is different.All the four loops have 3 steps in common.All the four loops have 3 steps in common. Initialization:-Initialization:- It is the starting point of It is the starting point of
the loop process.the loop process. Condition:-Condition:- In this step logical test is In this step logical test is
applied. It is true the block of code is applied. It is true the block of code is executed. Till the condition fails.executed. Till the condition fails.
Increment / Decrement:-Increment / Decrement:- In order to In order to proceed or stop the loop increment or proceed or stop the loop increment or decrement is required.decrement is required.
For loopFor loop It is used to execute a set of statements repeatedly as long as the given It is used to execute a set of statements repeatedly as long as the given
condition is true.condition is true.
Syntax:- Syntax:- for (initial value ; test condition ; increment /decrement)for (initial value ; test condition ; increment /decrement) {{statements;statements; //body of for loop//body of for loop}}
When the When the for loopfor loop is executing for the very first time the initial value is is executing for the very first time the initial value is stored in the given variable. Then the condition will be tested. If it is true, 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 the statements will be executed. After executing the last statement the control will return back to the for loop. Then the value will be control will return back to the for loop. Then the value will be incremented / decremented. Again the condition is tested, if it is false incremented / decremented. Again the condition is tested, if it is false the control will come out of the the control will come out of the for loopfor loop..
Ex:-Ex:- for(i=1; i<=10; i++)for(i=1; i<=10; i++)
While loopWhile loopWhile statementWhile statement It is used to execute a set of statements It is used to execute a set of statements
repeatedly as long as the given condition is true.repeatedly as long as the given condition is true.
Syntax:- Syntax:- while (condition)while (condition) {{ statements; statements; //body of while loop //body of while loop }} First the condition is tested, if it is true the body First the condition is tested, if it is true the body
of the while loop will be executed first time, again of the while loop will be executed first time, again the control is transferred back to while loop and the control is transferred back to while loop and checks the condition, If it is false the control will checks the condition, If it is false the control will come out of the while loop. come out of the while loop.
Do While LoopDo While Loop This statement executes a set of statements This statement executes a set of statements
as long as the condition is true.as long as the condition is true.Syntax:Syntax: do do {{
statements;statements; statements;statements;
}while(condition);}while(condition);This is similar to while loop, but the differenceThis is similar to while loop, but the differenceis this loop will execute the statements at is this loop will execute the statements at
leastleastonce. once.
Nested for loopNested for loop In order to get the output in the In order to get the output in the
form of rows and columns we use form of rows and columns we use nested for loops. If the outer loop nested for loops. If the outer loop condition is true it enters into the condition is true it enters into the inner loop. Till the outer loop inner loop. Till the outer loop condition is false the looping condition is false the looping process is continued.process is continued.
ARRAYSARRAYS An array is contiguous area in the memory An array is contiguous area in the memory
referred by a common name. The array allows referred by a common name. The array allows the storage of a number of data values in one the storage of a number of data values in one variable. Each array element i.e. each individual variable. Each array element i.e. each individual data item is referred by specifying the array data item is referred by specifying the array name followed by one or more subscripts. Each name followed by one or more subscripts. Each subscript is enclosed with square brackets. Each subscript is enclosed with square brackets. Each subscript indicates the position of the element in subscript indicates the position of the element in the array. Arrays are divided into 2 types.the array. Arrays are divided into 2 types.
1.1. Single dimensional arrays or One dimensional Single dimensional arrays or One dimensional arraysarrays
2.2. Two dimensional arrays Two dimensional arrays
One dimensional arrayOne dimensional array– The array which is using only 1 subscript is known as oneThe array which is using only 1 subscript is known as onedimensional array. In one dimensional array the elements aredimensional array. In one dimensional array the elements arerepresented in single row or single column.represented in single row or single column.
Syntax:-Syntax:- Data_type variable_name[subscript] Data_type variable_name[subscript]Ex:-Ex:- int a[5]={40, 50, 70,90,100};int a[5]={40, 50, 70,90,100};
Float b[4]={20.5, 40.9, 45.7, 23.8};Float b[4]={20.5, 40.9, 45.7, 23.8}; Char c[5]={‘O’,’R’,’B’,’I’,’T’};Char c[5]={‘O’,’R’,’B’,’I’,’T’};
The above declaration states that ‘a’ is an array variable in The above declaration states that ‘a’ is an array variable in whichwhichwe can store 5 values of integer data type. Similarly ‘b’ is an we can store 5 values of integer data type. Similarly ‘b’ is an arrayarrayvariable in which we can store 4 values of float data type. variable in which we can store 4 values of float data type. SimilarlySimilarly‘‘c’ is an array variable in which we can store 5 characters.c’ is an array variable in which we can store 5 characters.
Multi dimensional arrayMulti dimensional array The array which is using two subscripts is known as The array which is using two subscripts is known as
2 – dimensional array2 – dimensional array
Syntax:-Syntax:- Data_type variable_name [subscript] Data_type variable_name [subscript][subscript][subscript]
Ex:-Ex:- int a[2][2]={{1,2,},{3,4}};int a[2][2]={{1,2,},{3,4}};
The above declaration states that ‘a’ is an two The above declaration states that ‘a’ is an two dimensionaldimensional
Array variable in which the values are stored in 2 rows Array variable in which the values are stored in 2 rows and inand in
2 columns2 columns
String FunctionsString Functions A character array is defined as a string. A A character array is defined as a string. A
group of characters is called a string. We group of characters is called a string. We cannot handle with string same like cannot handle with string same like integers or real values.integers or real values.
For example, if you want to compare an For example, if you want to compare an integer value with another int value. We integer value with another int value. We can do that by using = = operator. But can do that by using = = operator. But the same procedure cannot be applied the same procedure cannot be applied for strings. In order to handle with strings for strings. In order to handle with strings there are some string handling functions.there are some string handling functions.
Strlen( )Strlen( )
This function is used to find the This function is used to find the length of a string.length of a string.
Syntax:-Syntax:- strlen(string); strlen(string);
Note:-Note:- When we are using string When we are using string functions we have to include a header functions we have to include a header file <string.h>file <string.h>
Strcpy( )Strcpy( )
This function copies a string from This function copies a string from one string variable to another one string variable to another string variable.string variable.
Syntax:-Syntax:- strcpy(target_string , strcpy(target_string , source_string);source_string);
Strcat( ):- Strcat( ):- (String (String concatenation)concatenation)
This function adds a string at the This function adds a string at the end of another stringend of another string
Syntax:-Syntax:- strcat(string1,stirng2); strcat(string1,stirng2);
Strcmp( ):- Strcmp( ):- (String (String comparison)comparison)
This compares one string with This compares one string with another string.another string.
Syntax:-Syntax:- strcmp(string1, string2); strcmp(string1, string2);
Stricmp( )Stricmp( )
This function is similar to strcmp, This function is similar to strcmp, but this function ignores the case but this function ignores the case sensitivity.sensitivity.
Syntax:-Syntax:- stricmp(string1, string2); stricmp(string1, string2);
Strrev( )Strrev( )
This function reverses the given This function reverses the given string.string.
Syntax:-Syntax:- strrev(string); strrev(string);
Strupr( )Strupr( )
This function converts the given This function converts the given string into upper case(capital string into upper case(capital letters)letters)
Syntax:-Syntax:- strupr(string); strupr(string);
Strlwr( )Strlwr( )
This function converts the given This function converts the given string into lower case.string into lower case.
Syntax:-Syntax:- strlwr(string); strlwr(string);
Single characterSingle character toupper( )toupper( ) :- :- This function converts a single This function converts a single
character to upper case.character to upper case.
Syntax:-Syntax:- toupper(character); toupper(character);
2) tolower( ) 2) tolower( ) :-:- This function converts a single This function converts a single character to lower case.character to lower case.
Syntax:-Syntax:- tolower(character); tolower(character);
Note:-Note:- when we are using single character functions when we are using single character functions we have to include a header file <ctype.h>we have to include a header file <ctype.h>
FunctionsFunctions A function is a set of A function is a set of
statements that performs a statements that performs a specific task. Functions are 2 specific task. Functions are 2 typestypes
1.1. Pre defined functions or Pre defined functions or Standard functionsStandard functions
2.2. User defined functions User defined functions
Pre defined FunctionsPre defined Functions
These functions which are already These functions which are already defined (in built) along with C are defined (in built) along with C are called as pre defined functions.called as pre defined functions.
Ex:-Ex:- printf( ), scanf( ), pow( ), printf( ), scanf( ), pow( ), strlen( ), strcpy( ), toupper( ),……strlen( ), strcpy( ), toupper( ),……
User defined functionsUser defined functions
These functions defined by the user These functions defined by the user in order to work with complex in order to work with complex program and to develop the program and to develop the efficiency of the program are called efficiency of the program are called as user defined functions. In order to as user defined functions. In order to define a function we have 3 types.define a function we have 3 types.
– Function definitionFunction definition– Function prototypeFunction prototype– Invoking a functionInvoking a function
Function definitionFunction definition Function headingFunction heading
a.a. Return type:-Return type:- Return is called as data type mention Return is called as data type mention according to the type of value returned from the according to the type of value returned from the function.function.Note:-Note:- When there is no return statement we should mention When there is no return statement we should mention void as a default return type.void as a default return type.
b.b. Function name:-Function name:- Here we mention the name of a Here we mention the name of a function. It is just like a variable namefunction. It is just like a variable name
c.c. Specification of parameters:Specification of parameters:-- The specify the The specify the number of values are variables taken by the called number of values are variables taken by the called function from main program.function from main program.Note:-Note:-The parameters mentioned in the main program for The parameters mentioned in the main program for calling a function are called as actual parameterscalling a function are called as actual parameters..The parameters mentioned in the function which are The parameters mentioned in the function which are received from the main program are called formal received from the main program are called formal parameters.parameters.
Block of codeBlock of codeThe code which is written with in the braces ofThe code which is written with in the braces ofa function is called as block of code.a function is called as block of code.
Return statementReturn statementThis is the last statement of a function it isThis is the last statement of a function it isto written a value from the user defined function to the to written a value from the user defined function to the
mainmainprogram.program.
It is declared in the main program about It is declared in the main program about the function.the function.
Note:- Note:- Function prototype is optional if Function prototype is optional if the function is defined before the main. the function is defined before the main. It is compulsory if the function is It is compulsory if the function is defined after the main.defined after the main.
Function PrototypeFunction Prototype
Invoking a FunctionInvoking a Function
From here we call the function. A From here we call the function. A functionfunction
as no live when it is not Invoked.as no live when it is not Invoked.
Uses of functionsUses of functions
– Dividing the task into sub tasks.Dividing the task into sub tasks.– If a particular task is repeated number of times If a particular task is repeated number of times
in a program we can create a function and call in a program we can create a function and call that function wherever we want.that function wherever we want.
– Whenever a function is called in a statement Whenever a function is called in a statement the control will be transferred to that called the control will be transferred to that called function. After executing all statements it function. After executing all statements it returns back to the calling function.returns back to the calling function.
– The length of the source program will be The length of the source program will be reduced by using functions at appropriate reduced by using functions at appropriate places.places.
– A function can be used in other programs also.A function can be used in other programs also.
Syntax of a functionSyntax of a functionReturn_type function_name (argument Return_type function_name (argument
list)list){{ declarations;declarations;
statements;statements; -------------------------- return value;return value;} }
Return statementReturn statement
It returns a value of the expression to It returns a value of the expression to the calling function.the calling function.
Syntax:-Syntax:- return(expression)return(expression) Ex:-Ex:- return(a);return(a);
return(a+b);return(a+b); return a;return a;
Recursive functionRecursive function Recursive function is a function Recursive function is a function
which calls itself (or) The process which calls itself (or) The process of calling the same function itself.of calling the same function itself.
PointersPointers A pointer is a variable which holds the address of A pointer is a variable which holds the address of
another variable. Since addresses are whole another variable. Since addresses are whole numbers pointers would always contain whole numbers pointers would always contain whole numbers.numbers.
Consider the following declarationConsider the following declaration Ex:-Ex:- int i=10;int i=10;
The declaration tells the C compilerThe declaration tells the C compiler Reserve space in memory to hold the integer value.Reserve space in memory to hold the integer value. Associate the name ‘i’ with memory location.Associate the name ‘i’ with memory location. Store the value 10 at this location.Store the value 10 at this location.
Memory mapMemory map
ii 6552465524
‘ ‘i’ - Location namei’ - Location name 10 - Value at location10 - Value at location 65524 – Location number or address.65524 – Location number or address.
Declaration of a pointer:Declaration of a pointer:
Int a, *x;Int a, *x;Float b, *y;Float b, *y;Char c, *z;Char c, *z;Pointer variable is same as normal variable. But a * symbol Pointer variable is same as normal variable. But a * symbol is addedis addedbefore the variable.before the variable.
10
Usage of pointersUsage of pointers
As pointers work with addresses accessingAs pointers work with addresses accessingthrough addresses first then through a normalthrough addresses first then through a normalvariable. When the values are called with thevariable. When the values are called with thehelp of address by a function the modificationshelp of address by a function the modificationsdone to the variables shows the reflection.done to the variables shows the reflection.Indirectly we can get the value of a variable byIndirectly we can get the value of a variable byusing *. So * is called as indirection operator.using *. So * is called as indirection operator.Whatever the data type may be a pointerWhatever the data type may be a pointervariable occupies only 4 bytes of memory.variable occupies only 4 bytes of memory.
Parameter passing Parameter passing mechanismmechanism
Call by valueCall by value Call by addressCall by address
Call by value:-Call by value:- When the function calls the When the function calls the parameters by taking values the parameters by taking values the modifications done to the parameters by modifications done to the parameters by the function doesn’t reflect.the function doesn’t reflect.
Call by address;-Call by address;- When the parameters When the parameters are called by address the changes done to are called by address the changes done to the values within the function shows the the values within the function shows the reflection.reflection.
StructuresStructures Structure is a user defined data type. A structure is a Structure is a user defined data type. A structure is a
collection of variables that is referenced under a single name. collection of variables that is referenced under a single name. A structure contains a number of data types grouped A structure contains a number of data types grouped together. These data types may or may not be of the same together. These data types may or may not be of the same type.type.
Definition of a structure: -Definition of a structure: - Structure is a collection of Structure is a collection of variables whichvariables which
are of dissimilar data types.are of dissimilar data types.
Declaring a structure:-Declaring a structure:-struct <structure name>struct <structure name>{{ structure element 1;structure element 1; structure element 2;structure element 2; ------ structure element n;structure element n;};};structure variables;structure variables;
Ex:-Ex:- struct book struct book {{ int pages;int pages; char author[20];char author[20]; float price;float price; };};
The above declaration states that struct is a keywordThe above declaration states that struct is a keywordwhich is called as a data type in variables is declared which which is called as a data type in variables is declared which
are ofare ofdifferent data types.different data types.
In the above declaration book is called Tag name and In the above declaration book is called Tag name and pages,pages,
Author, price are called as data members of the structure Author, price are called as data members of the structure
Declaring a variable for a structureDeclaring a variable for a structureEx:-Ex:- Student S1; Student S1;
Here, s1 is a variable of a structure to which we canHere, s1 is a variable of a structure to which we cangive 3 details.give 3 details.The data members of the structure are called by theThe data members of the structure are called by thevariable using ( . ) operator.variable using ( . ) operator.
For example:-For example:- S1.sno S1.sno S1.name S1.name S1.marksS1.marks
Features of a structure:-Features of a structure:- With the With the help of structure we can maintain a help of structure we can maintain a data in a systematic order. We can data in a systematic order. We can handle a structure within a structure. handle a structure within a structure. And also we can call the structure And also we can call the structure variable through functions and Arrays variable through functions and Arrays also can be implemented through also can be implemented through structures. Pointer to structure is also structures. Pointer to structure is also possible.possible.
FilesFilesA file is a collection of information on a storage deviceA file is a collection of information on a storage devicewith a particular file name.with a particular file name.
Uses of a file:-Uses of a file:- Stores the data in the form of a file and we can Stores the data in the form of a file and we can
retrieve it whenever we require.retrieve it whenever we require. Using the data from the file in different programs.Using the data from the file in different programs.
Opening a file:-Opening a file:- we can open a file by using fopen( ) we can open a file by using fopen( )Syntax: -Syntax: - fopen(file name, opening mode); fopen(file name, opening mode);Ex: -Ex: - FILE *fp; FILE *fp;
fp=fopen(“file1.txt”,”w”);fp=fopen(“file1.txt”,”w”);
File opening modesFile opening modes ww :- :- Writing the data into a file. If the file Writing the data into a file. If the file
already exists its contents will be over written.already exists its contents will be over written. rr:-:- Reading data from a file. Reading data from a file. aa:-:- Adds data into an existing file. (Appending) Adds data into an existing file. (Appending) ww+ :-+ :- We can write data into file and we can We can write data into file and we can
read data from the file. If the file already exists read data from the file. If the file already exists its contents will be over written, else creates a its contents will be over written, else creates a new file.new file.
rr+ :-+ :- Reading existing contents, writing new Reading existing contents, writing new contents, modifying existing contents of a file.contents, modifying existing contents of a file.
aa+ :-+ :- Reading existing contents, appending Reading existing contents, appending new contents at the end of a file.new contents at the end of a file.
Closing a fileClosing a file
When the file processing is over, When the file processing is over, the filethe filemust be closed. We can close a file by must be closed. We can close a file by usingusingfclose( ).fclose( ).
Syntax:-Syntax:- fclose(file pointer); fclose(file pointer); Ex:-Ex:- fclose(fp);fclose(fp);
File functionsFile functions getc( )getc( )
This function is used to read a character from a file.This function is used to read a character from a file.Syntax :-Syntax :- getc(file pointer); getc(file pointer);Ex:-Ex:- getc(fp); getc(fp);
putc( )putc( )This function is used to write a character into a file.This function is used to write a character into a file.
Syntax:-Syntax:- putc(character, file pointer); putc(character, file pointer);Ex:-Ex:- putc(ch,fp); putc(ch,fp);
fprintf( ):-fprintf( ):- This function writes formatted data into a file. This function writes formatted data into a file.Syntax:-Syntax:- fprintf(file pointer, “formatted string”, list of variables) fprintf(file pointer, “formatted string”, list of variables)Ex:-Ex:- fp=fopen(“student.dat”,”w”); fp=fopen(“student.dat”,”w”); fprintf (fp , “%d %s %d”, sno ,name, marks);fprintf (fp , “%d %s %d”, sno ,name, marks);
fscanf( ):-fscanf( ):- This function reads formatted data from a file. This function reads formatted data from a file.Syntax:-Syntax:- fscanf(file pointer, “formatted string”, list of variables) fscanf(file pointer, “formatted string”, list of variables)Ex:-Ex:- fp=fopen(“student.dat”,”r”); fp=fopen(“student.dat”,”r”); fscanf(fp , “%d %s %d”, &sno, name, &marks);fscanf(fp , “%d %s %d”, &sno, name, &marks);
Storage classesStorage classes
Where the variable would be storedWhere the variable would be stored What will be the initial value of the What will be the initial value of the
variable, if the initial value is not variable, if the initial value is not specifically assigned?specifically assigned?
What is the scope of the variable, i.e. What is the scope of the variable, i.e. in which functions the value of the in which functions the value of the variable would be available.variable would be available.
What is the life of the variable? i.e. What is the life of the variable? i.e. how long would the variable exist.how long would the variable exist.
There are 4 storage classes There are 4 storage classes in Cin C
1.1. Automatic storage classesAutomatic storage classes2.2. Register storage classesRegister storage classes3.3. Static storage classesStatic storage classes4.4. External storage classesExternal storage classes
Automatic storage classesAutomatic storage classes Storage - memoryStorage - memory Default initial value - garbage valueDefault initial value - garbage value Scope - local to the block in which Scope - local to the block in which
the variable is defined the variable is defined Life - till the control remains with in Life - till the control remains with in
the block in which the variable is the block in which the variable is defined.defined.
Register storage classesRegister storage classes
Storage - CPU registersStorage - CPU registers Default initial value - garbage valueDefault initial value - garbage value Scope - local to the block in the Scope - local to the block in the
variable is defined variable is defined Life - till the control remains in the Life - till the control remains in the
block in which the variable is block in which the variable is defined.defined.
Static storage classesStatic storage classes Storage - memoryStorage - memory Default initial value - 0Default initial value - 0 Scope - local to the block in the Scope - local to the block in the
variable is defined variable is defined Life - value of the variable persists Life - value of the variable persists
between different function calls between different function calls
External storage classesExternal storage classes
Storage - memoryStorage - memory Default initial value - 0Default initial value - 0 Scope - globalScope - global Life - As long as the program Life - As long as the program
execution does not come to an end.execution does not come to an end.