You are on page 1of 42
C Language C HISTORY 1950-60: lots of High Level Languages were introduced. + Its used to communicate the computer by human being easy. + But, all HLL are specifically used for specific application. = Many countries committee founded and developed a new language called ALGOL (Algorithmic Language) Minimum symbols and controls was the drawback of this language Understanding of this language was also hard, © 1963: CPL (Combined Programming Language) Lots of symbols, controls and huge explanations were the drawback But, it contains somewhat some good concepts. + 1967: BCPL(Basic CPL) by Martin Richards(Cambridge University) Itwas not so strong than BCL. Itwas not a common language AT&T Gell) + BLanguage Ken Thomson and Dennis Ritchie created an OS. Tested in DEC PDP-7 and DEC PDP- 11 for UNIX. Meanwhile he tried to develop a compiler for FORTRAN with DEC PDP- 11 with UNIX OS. That time one lanuage is automatically developed. Prepared By V.Ramasamy , Lecturer , Dept. of CSE, PARK College of En: eeroe That lang is“ B "lang. It contains best concepts of BCPL lang. ‘So he named the new lang as“ B" with first letter of * BCPL Itis based on interpreter. Translation is line by line Execution Also it is not for all app. 1972 : C language ( Denis Ritchie ) Its compiler for whole program exe. ANSI American National Standard Institute. The C ~ Programing by Dennis Ritchie & Prian Kernican, Book Name ~ (K & R), IIs not based on UNIX OS. It is based on several OS, FEATURES OF “Cc” HLL Relation to human, LLL Relation to computers (Assembly). MLL isa Middle Level lang, In UNIX OS, 1200 lines out of 1300 lines is C lang. ‘Common compilers were written by Assembly lang. But C compiler was written by C Lang ltselt Dynamic memory allocation and Bit ‘manipulation. Pointer concepts. Recursion concepts. Economy of expressions. Modern control flow and structures. Rich set of operators. www ramsinfodesk webs.com ig & Tech , Coimbatore. C Language 2 CURRENT USES OF “c” C++ LANGUAGE HISTORY. + Operating Systems + Interpreters = Bjome Stroustrup introduces C++ lang in 1980. + Editors + Introduce Reference for Pointers in" " + Assembly Programs + Adds Classes and Objects. + Complers + Itleads OOPS lang ¢ IS USED FOR DEVELOPING © ++ in and so ces, EXECUTING AC PROGRAM + Database Systems + Graphics Packages 4. Creating the program + Spread Sheets 2. Compiling the program + CADICAM Applications 3. Linking the program with functions that are needed {rom the © Library 4. Executing the program + Word Processors + Office Automations + Scientific and Engineering Applications BASIC STRUCTURE OF C PROGRAMS. Documentation Section Link Section Definition Section Global Declaration Section main() Function Section t Declaration Part Executable part Sub Program Section Funetion 1 Function 2 (User-Defined Functions) Funetion n Prepared By www.ramsinfodesk, webs.com V Ramasamy , Lecturer, Dept. of CSE , PARK College of Engg & Tech , Coimbatore C Language PROCESS OF COMPILNG AND RUNNING THE C PROGRAM System Ready Program Code L Enter Program Program Edit Source Program x. Compile Source Program € Compil Object Code System Link with library System Library | Executable Object Code Input Execute Object Code Data Error Logie Errors No Errors CORRECT OUTPUT Stop Prepared By www ramsinfodesk.webs.com V Ramasamy , Lecturer, Dept. of CSE , PARK College of Engg & Tech , Coimbatore C Language 4 4.1 C CHARACTER SET ‘asm auto break | case | catch ‘char—[ class const | continue | default delete [do | double | else | enum + Character set is a set of valid characters that a exten —[ inline [int float | for a friend —[ goto —[ if tong [new ee emcaae ‘operator | private | protected | public | register return [short [signed | sizeof | static KEGET struct —[ switch | tempiate—| this Try ; ‘ypedef_[ union [unsigned | virtual | void 0 volatile —[ while ‘Special | Space + => 7* 1000 Characters ase a oe 1.2.2, Identifiers Formatting | backspace, horizontal tab, characters | vertical tab, form feed, and carriage return 41.2 C TOKENS Executable Statements Set of declaration statements and methods containing instructions. ‘Syntax Rules Instructions are formed using certain symbols and words according to some rigid rules. Tokens The smallest, non reducible, textual elements present in a C program, They are 4. Keywords 2. Identifiers 3. Literals 4. Operators 5. Punctuators 1.2.4 Keywords ‘+ Have fixed meanings and these meanings cannot be changed. + They are pre defined by C Language. + Anessential part of language definition = Cannot be used as a identifier Eg: Prepared By + User defined symbolic names. ‘+ Represented with the help of 'C' character set ‘+ Used to give names of the variables, arrays, methods, classes interfaces etc. Eg. Amount, get_data(), mark{5] etc. Rules for declaring an identifier 1. They must begin with a letter not a digit or special characters except underscore. 2. The maximum length of the variable name is 31 characters 3. Upper case and Lower case letters are significant, 4. The variable name should not be a keyword or reserved word, 5. White spaces not allowed. ‘+ Value constants that assigned to variables in a program ‘+ Fixed values that do not changed at the time of execution www.ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE , PARK College of Engg & Tech , Coimbatore C Language LL Integer Literal = Sequence of Digits. Decimal integer ( 0...9 preceded by optional + or ~ sign ) eg.: 123, -88 etc (1245 , 34,567, $56 are wrong values) Octal Integer Hexadecimal Integer U Real Literal = Decimal notation, having a whole no followed by a decimal point and the fractional part. Eg Il, Single Character Literal = Contains a single character enclosed within a pair of single quote marks, ‘= Character constants have integer values known as ASCII values, Eg. IV, String Literal ‘= Sequence of characters enclosed in double quotes. ‘+ May be letters , Nos and Special Characters. Eo ‘india’, "4577" ,“28s" Prepared By BASIC DATA TYPES C supports a large number of data types. The builtin or basic data types supported by C are integer, floating point and character. These are summarized in table along with description and memory requirement Type | Byte | Range Description int [2 | -s2768t0 | Small whole 432767 number Tong [4 | -2147483648 | Large whole int to number 42147483647 Toat [4 | 3.4x10-38t0 | Small real 3.4x10+38 | number double [@ | 1.7x10-308 to | Large real 1.7x10+308 | number Tong [10 | 3.4x10-4982 | Very Large double to real number 3.4x10+4932 char [1 | Oto A Single 255 Character 1.2.4. Operators The standard C language provides the following operators and punctuators: oli} o};@ wl Pe) ale] +]. f~] | soot}, we]. fo>]<|> > sty faefu}e:| = | www.ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE , PARK College of Engg & Tech , Coimbatore. C Language Categories of Operators and Punctuators © Unary operators Referencing operator (' &") Dereferencing operator (‘*") Unary plus and minus operators ("+ and") Increment operator (° ++) Decrement operator (*--') Logical negation operator ("1") Bitwise complement operator (‘~") + Binary operators, 1 Binary plus and minus operators ('+' and - 2. Multiplicative operators (1 ',"/* and '% 3 Bitwise shift operators (','and'>>") 4,Logical and bitwise operators (' & ','*',"|'," &&'and'||') 5.Assignment operators (* etc.) 6.Relational operators ( ) 7.Equality operators (" ‘and'!=") 8.Selection (structure-access) operators (" "and" a) + Temary operators 1. Conditional operator (°? :') + The operators # and ## are used only by the preprocessor. ‘+ Symbols, used in expressions to describe operations with one or more operands. Prepared By V Ramasamy , Lecturer , Dept. of CSE , PARK College of E 6 They are 1. Arithmetic Operators, 2. Relational Operators 3. Logical Operators 4, Assignment Operators 5. Increment and Decrement Operators Conditional Operators ‘Special Operators 1. Arithmetic Operators. + Addition - ‘Subtraction 7 Muttiptication 1 Division % — Modulo Division 2, Relational Operators > greater than < less than greater than or equal to <= _ less than or equal to equal to I= not equal to 3. Logical Operators && AND (age && gender) oR (age || gender) 1 NOT (ab) 4. Increment / decrement operators. a7 Increment Operators 5 Decrement Operators Type Prefix Posttix | Decrement | Therement 7a i www.ramsinfodesk.webs.cor & Tech , Coimbatore C Language y Prefix The value first incremented or decremented then 5. Short Hand Operator printed, eg. Atst azatt Arsh azata; 6. Conditional Operator(Ternary Operator) Postti >b)?aib; The value is printed then its value incremented or a>b Condition decremented @ when condition true ‘a’ value printed But the next value will be incremented or decremented b when condition true ‘b’ value printed. value only. eg. 7. Special Operators value representation in pointer. & address representation in pointer. 0 array 1.2.8 Punctuators + Symbols, used for grouping separating code. Following characters are used as punctuators * Define the shape and function of a program. ince. Brackets [ ] ‘Opening and losing brackets Indicate single and mullidimensional array subscript. Parentheses ( ) ‘Opening and closing brackets indicate functions calls, function parameters for grouping expressions etc. ‘Opening and closing braces indicate the start and end of a compound www ramsinfodesk webs.com Braces { } eee Comma, itis used as a separator in a function argument list ‘Semicolon ; Itis used as a statement terminator. Colon indicates a labeled statement or conditional operator Symbol. ‘Asterisk Tis used in pointer declaration or as multiplication operator, Equal sign Tis used as an assignment operator, Pound sign # Tis used as pre-processor directive Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK College of Engg & Tech , Coimbatore, C Language Precedence of Operators Category ‘Operator ‘What itis (or does) 7. Highest U7 oO Array Subscript Function call Indirect component selector Direct component selector 2. Unary sizeof (ype) Logical negation (NOT) Bitwise (1's) complement Unary plus. Unary minus Preincrement or postincrement Predecrement or postdecrement Address. Indireetion| Size of operand, in bytes Typecast Mallipicative Maltiply Divide Remainder (modulus) 4 Adllive Binary plus Binary minus = Shit Shift le Shift right & Relational Tess than Less than or equal to Greater than Greater than or equal to 7. Equality Equalto Not equal to é Bilwise AND 3 Bitwise XOR 70. Bilwise OR 7 Logical AND 12 Logical OR 13. Conditional "a? x.y means "Wa then x, ese" 14. Assignment ‘Simple assignment Assign product Assign quotient Assign remainder (modulus) Assign sum Assign difference Prepared By V.Ramasamy , Lecturer , Dept. of CSE , PARK Colle; www.ramsinfodesk.webs.com ce of Engg & Tech , Coimbatore. C Language Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift poe Assign right shift 75. Comma Evaluate 1.3 Expressions Combination of Constants, Variables, Operands and Operators arranged as per the rules of the computer language. Types: Constant Expression Integral Expression Real Expression Pointer Expression Relational Expression Logical Expression Bitwise Expression 4. Constant Expression ‘+ Expression contains only constant values. eg 12 34467-76°34/26 “INDIA’ 2. Integral Expression ‘After implementing all the automatic and explicit conversions, it will produce the interger value resutt eg. x x#6%y where x,y,z are integer variables ztint( 5.6) Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; 3. Real Expression ‘+ After implementing all the automatic and explicit conversions, it will produce the real value result eg prg37 56.78-float(23) where p and q are real variables 4. Pointer Expression + Itwill produce address values. eg “m &n —_/ where m,n are pointer variable 5. Relational Expression ( Boolean Expression ) ‘After implementing all the automatic and explicit conversions, it will produce the bool value ( True or False ) result eg. m#n >=345 6. Logical Expression ‘+ Combine two or more relational expressions using logical operator and produce the bool value( True or False) result eg mesn && x15 3.14 a==60 || a>= 50 www ramsinfodesk webs.com & Tech , Coimbatore C Language 10 7. Bitwise Expression ‘+ Used to manipulate the data at bit level Declaration of a variable eg * Variable must declare before used in programs. x,3 i! shift 3 bit position to left * For each and every variable, memory will be y>>41 i shift bit position to right allocated based upon data type. + In that memory data will store. Special Assignment Expression ‘Syntax Chained Assignment data_type variable_name; eg x= (y= 30); orx=y =10; * data_type must be any valid c data types. Here, can not be initialize variables at the time of eg. declaration int cust_name ; int xy; int men=67; 7 wrong int m=67,n=87; Initialization of variable * Variable's default value is undetermined. + We must define variables with some initial value. Embedded Assignment Syntax eg x= (y= 100) +15; data_type var_name=value; here, ( y=100 ) is a embedded assignment. Embedded Expression complete first. Then, eg. Y=100; int a = 20; +15; 8°50; 1.4 VARIABLES Note « Itis an identifier, referenced to particular memory eee ee location, ‘+ Used to store literal values. Pid ae Predefined Standard Input/Output Functions in C Language Text VO Functions Function Format Description Converts a floating-point value found in string info a floating-point number, atofy) {numvar= Jatof(string); | which can be stored in a variable, numvar, or used immediately. Requires the STDLIB.H header fle to be included atop Thumvar= alollstring); __| Converts an integer value found in string into an integer, which can be Prepared By www ramsinfodesk webs.com V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; & Tech , Coimbatore C Language ul Stored in a variable, numwvar, or used immediately. Requires the STDLIB.H header file to be included. Tlush(stain) | Mush(stdiny, Removes characters from the input stream (keyboard), Removes characters from the input stream (Keyboard). This function must fpurge(stdin) | fpurge(stdiny; Cee eae y be used in Unix rather than fflush(stdin). Reads a single character from the keyboard. The character is displayed getchar) | (ct and, optionally, stored in the char variable ch, lgetchar); Reads a string of text from the Keyboard (lerminated by the Enter Key). ets( jets(string); gets() sets(string) The text is stored in the variable string. Displays formatted text according to the format string. Optional values or printf) printi("format’|.varf.var...I); | variables, var, can be specified to match placeholders or conversion characters in the format string, Displays the character ch on the screen, where ch is a single character putchar() | putchar(oh); (or escape code) in single quotes or the name of a char variable. Displays the text string on the screen, where string is a Ieral string of text puts() puts(string); (enclosed in double quotes) or the name of a string variable. Reads information from the keyboard according fo the conversion character in the format string. The information is then stored in the scant() scanf("format" var); variable var, which must match the type of conversion character that's used (nt, float, or char, for example). Format Specifiers for printf and scanf Ses | io ezomere Formato ou a | —ieger | Sioned decimar ia | teger | Soned decimarint %o | —ieger | unsigned oar au | wager | signed desma nt %x_ | teger | unsigned hex int @ RAED %X integer unsigned hex int (A.B,C.D,E.F) if | Toating port | signed value of form Fda ddGd ‘signed value of form [-]d.dddd or %e | floating point M9 Pont Y tein} ‘signed value in either e or f form trailing zeros and the decimal point are printed only if necessary. %q | floating point Same as e, but with E for %E | floating point : exponen Same as g, but with E for %G | floating point exponent if e format Prepared By www ramsinfodesk webs.com V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; & Tech , Coimbatore C Language %e ‘character | single character prints characters unt a null %s | string pointer | terminator is pressed or precision is reached %% none | the % characleris printed ‘lores (in the Tocalion pointed to ten | pointerto int | by the input argument) a count of the characters written so far prints the input argument as @ %~p pointer memory address Prepared By www ramsinfodesk.webs.com V.Ramasamy , Lecturer , Dept. of CSE , PARK College of Engg & Tech , Coimbatore C Language 13 1.5 C Control Structure Statement ‘= Single line of instruction terminated by semicolon. + Itcan do a particular task Compound Statement ‘= Group (or) block of statements enclosed between pair of braces. + Itcan do a particular task Null (or) empty Statement ‘= Single semicolon. + But, it can't do any useful or logical task Function Used to process the data present in object ‘= Group of instruction to perform particular task = Used to perform any or particular task. = When task is complex. different algorithms are used to solve it. ‘= Program format sometimes leads bugs ‘= So format should be easy to trace the flow of execution of statements, + For an accurate, error resistant and maintainable of code, control structure is used. They are, 1, Sequence Structure( Straight Line ) 2. Selection Structure ( branching ) 3, Loop Structure ( iteration or repetition ) Selection Structure 1. Simple if Simple if-else Nested if ifelse ladder switch case Conditional operator Loop Structure 1, do-while loop 2. while loop 3. forloop Prepared By www.ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE , PARK Colle ce of Engg & Tech , Coimbatore. C Language Flow Chart Entry Entry Entry Action 1 i F Cond Action 2 Action 1 Action 2 Action 1 ¥ Action 3 I Action 2 Action 3 x Exit J Exit (Sequence ) (Selection ) (Loop ) 1.5.2 Selection Structure else 4 1. Simple if statement False stmt body; y Syntax Program : 1_1-if_else.cpp if cond) 11 Simple if-else t #include Body; #include y void main) 2. Ifelse statement { Syntax : clrser0: printf('Enter age :"); if (cond ) int age; t scant("%d", 8age); True stmt body; if (age>=18) y 4 Prepared By www ramsinfodesk. webs.con Lecturer , Dept. of CSE , PARK Colle; of Engg & Tech , Coimbatore 14 C Language printf(*Eligible to vote!) ) else ‘ printf(’Not Eligible to vote!!"); d getchd; ) output : Enter age : 20 Eligible to vote ! 3. nested - if sttement ‘Syntax: if (cond ) { True stmt body; if (cond ) { True stmt body; } else { False stmt body; y y else « False stmt body; it (cond ) { True stmt body; } else { False stmt body; y ) Prepared By nasamy , Lecturer , Dept. of CSE , PARK College of En Program : 11 Nested if Hinclude #include void main { int avg; clrser0; printf¢\n\n Enter avg : scanf("%d" &avg); if(avg>50) 4 printf("n\n Pass !"); iffavg>80) { printf(\nin A Grade » else { printf¢\n\n B Grade !") , } else 4 printf("n\n Fail); if(avg>40) { printf(\n\n Try to get pass mark next time !"); , else { printf¢\n\n very poor , y getcho; d www ramsinfodesk webs.com & Tech , Coimbatore C Language 16 output : print("in\n Pass "); printf(in\n B Grade ! Enter Avg : 75 ) Pass! else if(ava>s0) B Grade ! { printf(in\n Pass 1"); 4. if-else ladder statement print(nin C Grade ! syntax : } if (cond ) else ‘ { ‘True stmt body; printf(inin Fail > ) else if (cond ) getchd; ‘ > True stmt body; ) Output : Enter avg : 45 else Fail ! ‘ False stmt body; 5. switch statement ) Program : + Multiple branching statement. Welse-if ladder #include #include void main) { int avg; airser); printi("in\n Enter avg scanf("2d",8avg); if(avg>80) « printf(in\n Pass !"); print((\n\n A Grade "); } else iffavg>60) « Prepared By nasamy , Lecturer , Dept. of CSE , PARK College of En * Based on the condition the control is transferred to one of the many possible points. ‘Syntax: ‘switch (exp ) { Case 1 { stmt 1 Break; y casen 4 stmt n; Break; www ramsinfodesk webs.com & Tech , Coimbatore C Language nd ) (Cond) ? True part : False part Default t Program : Default stmt; ) Hinclude ) void main ‘ Program : int a, b\max; #inoludestdio.h> #include void main) { ) elrser0: int choice; output : printi("Enter choice between 1 - 3"); Max of a & bis : 20 scanf("96d", choice); switch (choice) 1.5.3 Loop Structure ‘ case 1 1. do - while loop print CSE! break: + Exit controlled loop. case 2: + Based on condition the control is printtc1T); transferred back to a particular point break; case 3: Syntax : printiEC break: eb default print(Enter a No between 1 - 3. ena break; } ) while( exp ); getchd; Program : ) #include output : Finclude Enter a No between 1-3: 2 T void maing) { 6. conditional operator clser0) syntax : int n=1; Prepared By www. ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE, PARK College of Engg & Tech , Coimbatore, C Language do { printfn value :", n); net; y while(n<4); getchd; y output : nvalue: 1 n value nvalue : 3 2. while loop * Entry controlled loop, Syntax : While( exp ) { stm; y Program #include #include void main « clrser(): int while(n<4) « y getchd; y output : Prepared By V Ramasamy printf(’n value :"\n); net: Lecturer , Dept. of CSE , PARK Colle; 18 value : 1 value : 2 value: 3 3. for loop + Entry controlled loop. ‘+ Task is repeated for a predetermined no of times. ‘Syntax : Forinitial value;condsincrement or decrement) { stmt; Program : #include #include void main() { clrserQ; into; for(n=0;n<=3;n+#) 4 printf('n value :"\n); y getchd; y output : value : 4 value : 2 value: 3 Jump Statements + Used to unconditionally transfer program control within a scope. www ramsinfodesk webs.com & Tech , Coimbatore C Language 1.goto statement 2.break statement 3.continue statement 1. goto statement ‘= Used to transfer the control from current line to another line with the help of labels. Syntax : goto lable_name; eg. goto bt; Prepared By V Ramasamy , Lecturer , Dept. of CSE 2. break statement + Immediately exits from the loop, Syntax : break; 3. continue + skips the rest of the loop body and starts a new iteration ‘Syntax : continue; www ramsinfodesk. webs.com 12g & Tech , Coimbatore. C Language 1.6 LIBRARY FUNCTION + Built in functions that saves the programming time Mathematical Functions ‘= Some of the important mathematical functions in header file math.h are Function Meaning sing) | Sine of an angle x (measured in radians) e0s(x) | Cosine of an angle x (measured in radians) tan(x)_| Tangent of an angle x (measured in radians) ‘asin@) | Sin-1 (9 where x (measured in radians) ‘acos(x) | Cos-1 (%) where x (measured in radians) ‘exp(s) | Exponential function of x (ex) og) __| logarithm of x log 10(%) | Logarithm of number x to the base 10, sant) | Square root of x pow(x, y) | xraised to the power y ‘abs(®)__| Absolute value of integer number x fabs(x) | Absolute value of real number x Character Functions * Allthe character functions require ctype.h header file. 20 Function Meaning ‘salpha(e) | Itretums True ifC is an uppercase letter and False ifc is lowercase. isaigit(e) | rretums True ifc is a digit (0 through 9) otherwise False. Trretums True Ife is a digit from 0 through © or an alphabetic ‘salnum(o) character (either uppercase or lowercase) otherwise False. islower(e) | Itretums True if C is a lowercase letter otherwise False. isupper(c) | Itretums True if is an uppercase letter otherwise False. toupper(c) | It converts ¢ to uppercase letter. tolower(e) | it converts c to lowercase letter. Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; & Tech www ramsinfodesk webs.com Coimbatore C Language String Functions ‘+ The string functions are present in the string.h header file. strien(S) It gives the no. of characters including spaces present in a string S. streat($1, $2) ‘$1 must have enough locations to hold $2. Weoneatenates the string S2 onto the end of the string St. The string stropy(St 2) ‘storage locations to hold $2. Weopies character string S2 to string S1. The St must have enough stromp(ST, 82) stromp(S1, $2)>0) stromp((S1, $2) <0) 5 y It compares S1 and S2 and finds out whether S1 equal to S2, S1 greater than $2 or $1 less than $2. strompi(ST, $2 strompi((S1, $2)>0) strempi((St, $2) <0) 2, S1 greater than S2 or S1 less than S2. Ht compares $1 and $2 ignoring case and finds out whether $1 equal to stirev(s) Itconverts a string s into its reverse strupris) It converts a string s into upper case striwe(S) Tt converts a string s into lower case Console VO functions ‘= The following are the list of functions are in stdio.h getchar), Tretums a single character from a standard input device (Keyboard). Ittakes no parameter and the returned value is the input character. putcharQ, Tiakes one argument, which is the character to be Sent to output device. It also returns this character as a result. gets T gets a string terminated by a newline character from the Standard input stream stdin. puts It takes a string which is to be sent to output device. General purpose standard library functions ‘= The following are the list of functions are in stdlib.h randomize) Tinilalizes 7 seeds the random number generator with @ random number random(n) It generates a random number between 0 to n-1 atoi(s) converts string s into a numerical representation itoa(n) Ttconverts a number to a string Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; 21 www ramsinfodesk webs.com & Tech , Coimbatore C Language 22 ‘Some More Functions 4.getch) 2.getche() + The general for of the getch0 and getched is ch=getcheQ; chi=getch); Prepared By www.ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE , PARK College of Engg & Tech , Coimbatore. C Language 1.7 Functions in C Function ‘* Used to process the data present in object. ‘+ Group of instruction to perform particular task. ‘= Used to perform any or particular task. ‘+ When task is complex, different algorithms are used to solve it, ‘= Program format sometimes leads bugs = So format should be easy to trace the flow of execution of statements. © Foran accurate, error resistant and maintainable of code, control structure is used. General form for Function declaration and definition void display); —_// Function Dectaration (or) Prototype main { void display; —_/ Function Declaration (or) Prototype Display); // Function Call Void display); Function Definition { 1 Function Body 4.7.4 The main() function ‘+The maind function returns int type value to os, = OS checks the return value(called exit value)for any program problem. Prepared By V Ramasamy , Lecturer , Dept. of CSE , PARK Colle * If return value is 0 then the function executed successfully Syntax: int main « 1 main body return 0; Program : #include #include void main « clrser): printf(*Jai Hind getchd; O1P : Jai Hind!!! 1.7.2 Fuction Prototype + Itis a template, + Itdescribes function interface to the compiler, * It gives details such that function return_type,function_name and arg_list + By this template , the compiler ensures the function declaration and definition correctly, + Function prototype in calling function is declaration statement and called function it is definition statement. www ramsinfodesk. webs.com 12g & Tech , Coimbatore. C Language 24 syntax : void print(int int addd; return_type fun_name(arg_list): float volume (float int int: ‘+ In declaration statement, the semi colon used void main at end and not in definition statement. ‘ ‘+ In function arg_tist each variable is elrser0) declaredeparately. displayd; eg print(100);, int volume(int xy, float 2); // Illegal printfC\nin 10420 : 9d", adhd); printf(‘inin Volume : %f",volume(S6,2,4)); ‘In function declaration the arg_list variable getchd; names are dummy and optional. ) eg int volcint, oat); void display) ‘ ‘In function definition the arg_tist variable names printf("inin Function 1"); are must, y eg int volint a flaot b) void print(nt a) ‘ + Incalling function arg_lst, type should not be printfCinin a : 96d".a); there. ) ‘+ Empty arg_list also possible in a function. int add eg ‘ void display0: retum (10420); 41.7.3 Types of function d + C function classified into mainly 4 types 1.Function without return type, without argument list float volume(fioat Lint b,int hy 2.Funetion without return type, with argument list t 3.Function with return type, without argument list Fetun(("b*h) 4.Function with return type, with argument list , output : Program : Function ! 11-4 types of function ace 10#20 : 30 Hincludestdio.h> volume : 44.7 #include void display¢) Prepared By www ramsinfodesk.webs.com V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; & Tech , Coimbatore C Language 1.7.4 Call by reference. ‘= Normally, when the function call, the arg passed by copy of value. + Calllby reference in function call, the arg passed by actual address of the variable not value. Program : + When declare and define the reference variable, should add & symbol prefix to variable. + Formal arg_list in the called function wil become actual arg_lst to calling function. ‘Syntax: data_type &var_name: ‘= Consider the following program which will swap the value of two variables. ‘using call by reference ‘using call by value Fincude=staio, > Finchude=staio n> void swap(int & int &); void swap(int int) int maing int main « { int a=10,b=20; 0, swap(a.b); swap(a,b): printf("%d %d",a,b); printf('%ed %d".a,b) retum 0; return 0; y y void swap(int &c, int &d) void swap(int ¢, int d) { { int output: output: 2010 1020 1.7.5 Inline Function Normally when function call occur, the control jump into called function, then perform operation as saving registers,pushing arg into stack and return to calling function ‘+ For small function, spent more time to pass control like above. + So inline function we are using ‘= Compiler replaces the function call with the corresponding function code. Prepared By V.Ramasamy , Lecturer , Dept. of CSE , PARK Colle: eof E ‘Syntax: Inline fun_name(arg_tist); Program #include #include inline int multint x,int y) retum(y); www.ramsinfodesk.webs.com gg & Tech , Coimbatore. C Language ) int maing { alrserd int 0; int b=40; printf(\n\t mul of a and b :",mul(a,b)) getchd; retum 0; } output : mul of a & b : 800 When inline function not work? 1. For functions returning values, if a loop, a switch, or a goto exists. 2. For functionds not returning values,if a return statement exists. If functions contain static variables. 4, {inline functions are recursive, 4.7.6 Default arguments. ‘= Some situations , the function call can have without all ofits arguments. + This time, default value is assigned for that particular parameter. ‘Default variables initialized at the time of declaration in a function. Notes + Trailing arguments can have default values and declare default variables from right to left. eg. int mul(int i, int j=10, int k=10): MW legal int mul(int i=5, int j; illegal int mul(int i=0, int j, int K-10); Willegal int mulint i=2, int j=5, int k=10);—/7 lagal Prepared By V Ramasamy , Lecturer , Dept. of CSE 26 Program Hinclude #include int mul(int aint b=5) void main « int n; clrser0: printf(Enter a no :\n"); seanf(""6d" &n); printf(‘mul value is:",mul(n)); getcho; y int mul(int x,int y) { retum(x’y) y output : Enter ano: 2 mul value is : 10 1.7.7 Function overloading * One function name is used to perform different task with different arg_lst at different situation in a program + For that, family of functions are declared and defined with same function name and different arg_lst. eg. 1 Declaration int add(int a,int by int add(int a, float b) 1 Function call printf( add(10,20); printf(add(10,2.5); www ramsinfodesk webs.com & Tech , Coimbatore C Language Program : #include ‘#include int volumetint); double volume(double, int) ong volume(long. int.int); int main { dirser); printf("volume printf("volume printi(*volume return 0; getcho } int volume(int s)—// cube { return(s*s*s); } double volume(double r,int h) { retun(, } long volume(long Int b,int hy 14°'hy, { retumdrb-h)} Prepared By V Ramasamy Lecturer vvolume(2)); yvolume(1.0,1)); volume(2.0,2,2)); 27 output : volume : 8 volume : 3.14 volume : 8.0 Compilers operations while function overloading. + Checks the No. of arg_list and type of arg_lst + Ifnot match, integral promotions are applied for that arguments, such as, eg. char to int float to double + Multiple matches occur the compiler make an error message eg. fong square(long n) double square(double n) ‘a function call as square(10) * int can convert fong or double, so error will occur. www ramsinfodesk webs.com Dept. of CSE , PARK College of Engg & Tech , Coimbatore. C Language 1.8 Arrays Definition + Series of same type of data placed in contiguous memory locations that can be individually referenced by an unique index 4. One Dimentional Array Declaration 1.data_type ar_name[}=(value 1, value 2..value n}: eg. int roll_nof}={100,104,...123}; 2.data_type art_name|size}: eg. float price[4); Definition 4, data_type arr_namef}=(value 4, value 2.. eg. int roll_no[}={100,104,...123}; 2, data_type arr_name[size]; arr_namefindex_position}=value; eg. float price[4); price[O]=12; 3. data_type arr_name[size]; arr_namefindex_positio eg. alue; float price[4), price[O}=scanf("9d", Prepared By Lecturer , Dept. of CSE , PARK Colle; 28 Program : Hinclude #include void main { int mof}=(100, 101,102}; clrscrQ; printf("\n Roll No :"); print n printf("\n "yno[O)) ; printf’ "\moft}) printf’ "ymo[2)) getcho; Output : Roll No: 100 101 102 Program : 1.2 #include #inelude void main { int mof}=(100, 101,102}; inti int size=sizeof(moy/sizeof(int); clrser0; for(i=0;i ‘#include void main) { int mo[3}; Lecturer , Dept. of CSE , PARK Colle; #include #inelude void main « int mof3} sizeof(mo)isizeof(int); clrser0; printf(’\n Enter Array values one by one for(i=Oi #include void main) { int mof3}; inti printf("\n Enter Atray values one by one :") izeot(mo)/sizeoK(int); “moll atrserd: for(=0;i void print(int Af), int length) { for (int n=0; n #include void main) { int mo{2][2}=(100, 101,102,103) airserQ; printi("\n Roll No : *) printfcvn in Printfe"n".mof[0]{0)) ; printfent “nofO]{t] ); printf" ".mof1]{0} ): Prepared By Lecturer , Dept. of CSE , PARK Colle; 31 rintfc’t "smof']{1] ) getchd, ? Output : Roll No: 100 101 102 103 Program : 1.2 #include #include void main « int mof2it2 (00,101,102, 103}; sizeof(mo)/(sizeofint)*2) printf("\n Roll No :"); printf(‘in ny for(i=0;i #include void maing { int mof2If2; rno[O](0}= mofo of tI{0 oft ]{1}= arser); printf" Roll No :"); printf" a"); printf("in *,rnof0l{01 ); printf("t "smofOjtt]): printf(\n. *\mof}(0}) ; printfct “nofAt]); getchd; } Output : Roll No 100 101 102 103 Program : 2.2 #iinclude #include void maing) { int eno(2}2}; ‘no{0}{0]=100 mo{O]{1}=101; fno[1][0]=102; moft}{1]=103; int ij: Prepared By nasamy , Lecturer , Dept. of CSE , PARK College of En int size=sizeof(mnoy/(sizeof(int)*2) clrserd printfc'\n size : "size; printf(’\n_ Roll No icsizes++) printfe "\mofil]) ) printfe"n"); } getchd), y Output : Roll No: 400 101 402 103 Program : 3.4 #include #inelude void main { int mof2it21; inti int size=sizeof(mo)i(sizeor(int)*2); clrserd printf¢'\n Enter array Value for(ieOi #include void maing) { int mo{2}(2} int ijs int size=sizeof(moy/(sizeof(int)"2); dirser0: printf('\n Enter array Value :"); for(=0:i void print(int Al[3},int N, int M) « for (R = 0; R < N; R++) for (C= 0; C int main () ‘ int arias] =(€12, 28, 11), {25, 25, 13}, (24, 64, 67), £11, 18, 149; print(arr4,3); return 0; > Output : www ramsinfodesk. webs.con of Engg & Tech , Coimbatore. C Language 1.9 Strings Manipulating strings String ‘Sequence of characters. In G "we use null terminated character array for string, ‘Operations on this string is inefficient and complexity, ‘So we created new class for this string with lot of operations. Ifwe want use this class we include in our program, 34 String class contains * Constructors, * Member functions. + Operators. Operations of above Creating string objects. Reading string objects from keyboard. Displaying string objects to the screen Finding a substring from a string. Modifying string objects. Comparing string objects. Adding string objects. ‘Accessing characters in a string, Obtaining the size of the strings. ‘scant ets) ean be used to take Input ofa value of any data type. Tean be used to take input ofa string. itakes the white space Le. @ blank, atab, or anew line character as a string terminator. Trdoes not take the white space le, a blank, @ tab, or anew line character, as a string terminator. requires header file 1ostream.h Trequires the header file stdio.h Example: char S[60), printf(Enter a string Bample: char $[80); printf("Enter a string: gets(S); print Puts) iean be used to display the value of any data type. Trean be used to display the value of a string. does not take a line feed afer displaying the string Takes a line feed after displaying the string, requires the header file iostream.h Terequires the header file stdio.h Example: Example char S[80}="Computers") char S[80]="Computers' print(S.S; puts(S); puts(S); Output Output: ComputersComputers, Computers, Computers Prepared By www ramsinfodesk webs.com V.Ramasamy , Lecturer , Dept. of CSE , PARK Colle; & Tech , Coimbatore C Language Create string objects in following ways. string $1; using constructor with no arg string s2(‘abe"); // using 1 arg constructor. 2; 1 assigning string objects. s3="abo"+s2; /! concatenating strings. scanf("9%d",s1; 11 reading through keyboard(one word) getline(cin,s1); reading through keyboard a line of text. Program : #include include void main () { dirser0: string sO (Initial string’); constructors used in the same order as described above: string $1; string 2 (80); string $3 (0, 8, 3); string s4 ("A character sequence”, 6): string s5 (‘Another character sequence"); string $8 (10, x); string s7a (10, 42); string s7b (s0.begin0, s0.begin+7); printf("s1:", st, “ns2:", s2., "\ns3:", $3); printf("\ns4:", s4 , "ns5:", $5, "\ns6:" , $6); printf(“\ns7a:", s7a , “ins7b: " , s7by; getchQ; } Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; Manipulating string objects + Modify the string objects, such as insert),replace), erase(), and append() pgm Relational operations. ‘+ Relational operators are overloaded in the string objects like follows. pgm String characteris Size or length _ no of elements, Capacity total elements. Maximum size largest possible size of string pom Accessing characters in string * Access sub strings and individual character in a string by followings ways. pgm 1/ String Programs #include #include #include void main { char s1[20}, s2{20} int result,len; printf("\nEnter first string: " gets(st); www ramsinfodesk webs.com & Tech , Coimbatore C Language printf("\nEnter second string: "); gets(s2); 11 Sting Concatenation streat(st, s2); printf¢’\nThe concatenated string is: %s", $1); 41 String Comparisons result = stremp(st, $2); if (esult ) printf("nBoth strings are equal"); else printf("nBoth strings are not equal"); 11 String Copy stropy(s2, $1); printf(’\ns2: %s", $2); 11 String Length len = strlen(st); printf(’\nLength of string: 9a! len); 11 String reverse strrev(s1); printfc\nReverse of string: %s", s1); 1 puts, puts(\nName: *); puts(s1); getcho; } Prepared By VR 36 Compare and swapping pgm www ramsinfodesk. webs.com nasamy , Lecturer , Dept. of CSE , PARK College of Engg & Tech , Coimbatore. C Language 1.10 Pointers Memory Allocation ‘+ While program is compiled, C IDE creates four logically distinct regions of memory. Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack Area : Area to hold the retum address of function calls, argument passed to the functions, local variables, for functions and the current state of the CPU. Heap : Area from which the memory is dynamically allocated to the program. Pointers. + Itis a derived data type. ‘+ Used to store another variable memory address, rather than data Declare a pointer v Syntax ble data_type *ptr_var_name; ea. int *ptr; Define or initialize the pointer variable Syntax ptr_var_name = &var_name; ea. ptr=&roll_ni Pointer to pointer ‘= Possible to store a pointer variable address to another pointer variable. Syntax : data_type *ptr_var_name1; data_type *ptr_var_name2; ptr_var_name2=&ptr_var_name1; Prepared By V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; 37 int roll_no; ptrt=&roll_n ptr2=8ptrt; Pointers to Constants and Constant Pointers + Pointer to a constant: cannot change the value that a pointer is pointed at. © Constant pointer: address in pointer cannot change once pointer is initialized Manipulation of pointer * We can access the pointer variable content with use of indirection operator or dereference operator (“*" ) ‘Syntax var_name=ptr_var_name; eg. roll_no="ptr; + We can change the value of pointer variable content with use of dereference operator. Note: + Pointer variable contains only address of another variable. Program : #include #include void main « int a=10; int; int“; clrser0 www ramsinfodesk webs.com & Tech , Coimbatore C Language be8a: r&b; printf("\n The value of a is :",a); printf("\n The address of a is :*,&a); printf("\n The address reference of b is :".b); printf("\n The value of bis *,*b); printf(\n The address reference of c is :",0); printf("\n The value of cis :",**e) getcho Pointer expression and pointer arithmetic + We can perform any arithmetic operation on pointer variable ( means content ) using dereference operator ("** " ). Program : #include ‘#include void maing) { int C int *pir; atrserd: piesa; printfC'\nin The value of ptr is *ptr=("pti}+10; printfC"n\n The value of ptr+10 is *.*ptr; *ptr=(pt)-5; printfC'\n\n The value of pS is -""ptr); *ptr=(pty'2; printfC"n\n The value of ptr*2 is -*:*pt) “ptr=(ptni2; PrintfC"n\n The value of ptr/2 is :*.*ptr); *ptr=("pt1)%2; printf(\nin The value of ptr%2 is "ptr getchd; } “a; Prepared By V.Ramasamy , Lecturer , Dept. of CSE , PARK Colle: Note: + If*p" is a character pointer then *p++" will by 1 byte, + If*p" were an integer pointer its value on “p++ ‘would be incremented by 2 bytes. increment Pointer with arrays ‘Array Pointer 7. Refers block oF Do not refer section of memory space memory. Refers specific. 2. The memory address | address. can not be changed Content of pointer variable, such that as memory address that it refers can be changed. Initialize pointer variable with array variable syntax int roll_noft0}; int *ptr; ptr=roll_no[0]; or ptr=roll_no; + The base address of array is assigned to pointer. + We can not perform pointer arithmetic non array variable which are not stored in contiguous memory location. Program : #include #include void main { www.ramsinfodesk.webs.com ce of Engg & Tech , Coimbatore. C Language 39 int numfs}; ‘sum=sum+ptr int *ptr, ) int picts int count; arserd; y printf("in\n Enter count value scanf("%d",count; printfc\n\n Enter Array value one by one :"); for(i=0;i #include typedef void«“funpt) int int); void add(int a,int b) { printfcvnin a+b :* } void sub(int a,int b) { printf(\nin a-b :",a-b); } void maing) { airserQ: funptr ptr; pir=&add; ptr (20,30); plr=8sub; ptr(100,50); getcho; ters to object = Pointer can point to an object created by a class. = Useful to create object at run time. ‘* Useful to access the public members of an object. syntax : class stud { body; stud 5; Prepared By V Ramasamy , Lecturer , Dept. of CSE , PARK Colle 40 stud *ptr=as Pointer is initialized with the address of ‘s’, We can refer member function in 2 ways 1. dot operator and object 2. aetrow operator and object pointer s.getdata(10,20); s.show0; is equal to plr>getdata(10,20); ptr>show); pam Pointers to Structures + We can create pointers to structure variables eg struct Student { int rolino; float fees; x ‘Student stut Student *stuPtr= &stut; (‘stuPt).rolIno= 104; -or- Use the form pl->member: stuPtr->rolino = 104; www.ramsinfodesk.webs.com ce of Engg & Tech , Coimbatore. C Language 1.11 Structure ‘© Single identifier( structure name ). ‘= Identifies (or) represents more than 2 different type of ¢ variable (members ) within braces (" any + Act as User defined data type. ‘+ Performs as predefined c variable like int , float . char ete. ‘= Members of structure variable can be accessed with the help of dot ( . ) operator. Structure Declaration ‘Syntax : struct structure_name { Different type of variable declaration Jobject_name; Object Creation ‘Syntax : structure_name object_name; Structue Definition Syntax : object_name . variable_name = value; Nested Structure Syntax: struct structure_name { struct structure_name « Different type of variable declaration Jobject_name; Different type of variable declaration Jobject_name; Prepared By V Ramasamy , Lecturer , Dept. of CSE , PARK Colle 41 Program : Hinclude #include struct student « int ids char “name; float percentage; }studentt, student2, student; void main « clrserd struct student st; student. ‘student2.name = *raja"); student3.percentage = 90.5; printf ("Id is: 9d \n", studentt id); printf¢’ Name is: %s tn’, student2.name); printf(* Percentage is: %f In", student3.percenta ge): getcho; d output : Was Name : raja Percentage : 95.5 www.ramsinfodesk.webs.com ce of Engg & Tech , Coimbatore. C Language 1.12 Union = Union is same like as structure, Only some difference is there, They are, Difference Between Structure and Union : Structure Union i, Access Members We can access all the members of structure at anytime. ‘Only one member of union can be accessed at anytime. i. Memory Allocation Memory is allocated for all variables. Allocates memory for variable which variable require more memory. Initialization All members of structure can be initialized Only the first member of a union can be initialized, iv. Keyword ‘struct’ keyword is used to declare structure. ‘union’ keyword is used to declare union. v. Syntax struct struct_name { structure element 1; structure element 2; structure element n: }struct_var_nm; union union_name { union element 1; union element 2, union element n; }union_var_nm; Example struct item_mst union item_mst { { int mo; int mo; char ni(50} char nm[50} dit ve Prepared By www ramsinfodesk webs.com V Ramasamy , Lecturer , Dept. of CSE, PARK Colle; & Tech , Coimbatore

You might also like