Programming in c


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Programming in c

  1. 1. Programming in ‘C’ Programming in CIntroduction C is a programming language. It was developed by Dennis Ritchie at AT&T belllaboratories in the early 1970’s. C was an offspring of the Basic Combined ProgrammingLanguage (BCPL) called B language. C language was designed from B language by addingsome modifications to the B language. But C language compilers were not readily availablefor commercial use out side of the bell laboratories. So many programmers preferred C toolder languages like FORTRAN or PL/I of the newer ones like PASCAL and APL. Why c seems so popular is because it is reliable, simple, easy to use and easy to learn.First time C language compilers are available for UNIX operating system. The first Cprogramming text is written by Brian Kernighan and Dennis Ritchie but this book notprovides complete information about C. In 1983’s American National Standards Institute (ANSI) is the organization forms acommittee for development of C language. ANSI C committee releases standardizeddefinition of C in 1990. International Standard Organization (ISO) is also involved soon fordevelopment of C, because most of the world uses c language. C is a general purpose, structured programming language. C combines elements ofhigh level language with functionalism of assembly level languages (low level languages) sowe say C language is a middle language.Features of C language:  Programs written in ‘C’ are efficient and fast. This is due to its variety of data types and power full operators.  There are only 32 keywords and its strength lies in its built-in-functions.  Several standard functions are available witch can be used for developing programs.  C language is well suited for structured programming, thus requiring the user to think of problem in terms of `functions’ of ` modules’. A proper collection of these modules of function would make a complete program. This modular structure makes program debugging, testing and maintenance easier.  A c program is basically collection of functions that are supported by the C library. With the availability of a large numbers of functions, the programming task becomes simple. 1
  2. 2. Programming in ‘C’  C programs are highly portable. Portable means a C program written in one environment(O S) can run or executed in another environment with less or with out modifications.  C language is also called middle level language. Because it has both features of high level as well as low level language.  C is applied in system programming like operating systems, assemblers, language compilers, text editors and network devices.  Using c we can solve scientific, business, mathematical, research applications.  C language has an important facility called extendibility. It means you can write your own file and include in other programs. C fundamentals: Programming: Programming is a process to solve a particular problem by using the computer. When ever we need to computerize a particular, we have to solve those problems and write these solutions in the computer understandable code with the help of programming languages. Program: A program is a group of instructions which is used to perform particular task. The task’s like big number out of two numbers, billing process of a hotels or etc… Instruction: It is command given to the computer to perform any operation. These instructions may be addition, subtraction, relation between two numbers etc… Algorithm: A step by step procedure use to perform any task is called algorithm. Step by step represent of a program in general format is called algorithm. Flow chart: A pictorial representation of an algorithm is called flow chart. It can also show the flow of the program. Here we can use several symbols for several works in a program. These instructions and programs can be written in different languages like C, C++, java etc… these languages are called program languages. 2
  3. 3. Programming in ‘C’ Example of an algorithm: To find a number is an even or odd. Step1. Start. Step2. Take a number ‘N’. Step3. Divide the number by 2 => N/2. Step4. If the reminder is ‘0’ then goto Step5 other wise goto Step6. Step5. Print the number is even. goto Step7. Step6. Print the number is odd. Step7. Stop. High level languages: Initially (olden days) the computer programs were written in machine level languages like binary language. Write a program in binary language and learning binary language is very difficult. Later assembly languages were developed, with which a programmer can work with the machine slightly higher level. Assembly language: It is one of the programming languages. This is an advanced programming language than binary language. Write a program in assembly language is nothing; arrange the instructions in a sequence order to complete the task. In this language we can write instructions instead of sequence of binary numbers in binary language. Here instructions are represented in the form of symbolic names like ‘add’,’sub’, etc…. Assembler: An assembler is used to convert the assembly language program into binary language or specified machine instructions. By using assembly languages we can write different programs for different machines.A program write for one machine can not be run on another machine, so these languages arecalled machine dependent languages. Later these assembly languages are replaced by high level languages. The first highlevel language is FORTRAN (FORmula TRANsulator). One FORTRAN instruction orstatement can be executed in different machines unlike assembly language instruction. Thenhigh level languages ate called machine independent languages. 3
  4. 4. Programming in ‘C’Basic structure of a C-program:Documentation sectionLinking sectionDefinition sectionGlobal value declarationmain(){ Local variable declaration part Executable statements}Sub program sectionfunction1(){ Local variable declaration part Executable statements}..function2() { Local variable declaration part Executable statements}……….Documentation Section: The documentation section consists of a set of comments. Here wemention the name of the program and also write the comments for our program. Thecomment text can be bounded with astricks (*) and enclose with in back slash (/). By usingthese characters we can write comments for specified statements in our program. /* The program for addition of two numbers */Link Section: The link section provides instructions to the compiler to link function from theC-language library. In this section, we can write which header files are use in our program. #include<stdio.h>Definition Section: The definition section defines all symbolic constants. We can use theseconstants are use many times in our program. Which value is define in the definition section,we can not modify or redefine those values any where in the program. #difine pi 3.14 4
  5. 5. Programming in ‘C’Global Declaration Section: There are some variables that are used in more than onefunction. Such variable are called global variables and declared in the global declarationsection that is outside of all the function.I int a,b;Main function section: Every C program must have one main() function. This sectioncontains two parts, declaration part and execution part. The declaration part declares all thevariables used in the executable part. There is at least one statement in the executable part.These two parts must appear between the opening and the closing braces. The programexecution begins at the opening brace and ends at the closing brace. All statements in thedeclaration and executable parts end with a semicolon. main()Subprogram Section: The subprogram section contains all the user-defined functions thatare called by the main function. User defined function are generally declare, after, end of themain function.A Function is a subroutine that may include one or more statements designed to perform aspecific taskExample program for structure of C-program:/* Example program */ /* Documentation section */#include<stdio.h> /* Linking section*/#define a 10 /* Definition section */int b; /* Global variable declaration */main() /* Main function */{ int c; b=10; c=a+b; printf(“Sum : %d”,c); sub(b);}void sub(int y) /* (Sub program or function) */{ int z; / * Local variable declaration for function */ z=a-y; printf(“Subt : %d”,z);} 5
  6. 6. Programming in ‘C’Compiling program: Compiling of c- program is nothing, to generate binary code file for our program toexecute the program, with the help of compiler. Compiler: The compiler is a software program, used to convert the program into machine understandable code (binary code). The compiler analyzes a program, and then translates it into a form that is suitable to the running computer. The steps involved to create a program in C-language are entering program,compiling program and running program. The program is typed in the computer with the helpof editor. Editor: Editors provide space to write our program in computer. We can also open the existed programs in the computer. The text editors are usually used to write C- programs in to file. Source program: The program that is entered into the file is known as the source program. Start Editor Source program Name.C Compiler Yes Errors? Object program No Name.obj Linker Library and other obj files Exicutable code Name.exe Execute No Result ok? Yes Start 6
  7. 7. Programming in ‘C’ We have to follow several steps to write, compile and a program in C-programminglanguage. They are:  Open the C-programming language editor.  Write your program or open an existing program in the system.  When you create a new program, you have to save the program with a specific name. We have to follow the naming conventions (rules) to give name for C-program.  Give the file name with the extension ‘.C’. This extension represents a file as a C- Program file.  After saving the program, compile the program. The compilation process depends on the editor or running machines operating system.  For example, if we want to run our program in dos operating system, we have to follow several steps to compile the program. o Go to compile menu in editor. o Then chose ‘compile to obj’ command or press ALT+F9 key combination from the key board. o The compiler will compile the program  The compiler will give the syntax errors in our program. If we have any errors or warnings we have to rectify the errors, then open our source program, correct the errors then do the compile process again.  When ever we have an error free program then the compiler can create a .OBJ(object) file for machine. It is also called binary code file.  After creating the .OBJ file then run the program, go to run menu and choose run command or press CTRL+F9 key combination from the keyboard.  When ever run a program the linker links the .OBJ file and library files then create .EXE (executable) file, execute the program by using this .EXE file. Linker: It also a software program. By using this compiler links the OBJ file and library files the produce executable file this process is called building.  When ever execute our program, the steps in the program is executed sequentially this process is called top down approach. If our program get any data from the user is called input, then process the input and displays result on the output screen. If the output is 7
  8. 8. Programming in ‘C’ correct then completed our task other wise open the program change the logic according to our requirement.Integrated development environment (IDE): The process of editing, compiling, running and debugging program is often managedby a single integrated application is known as Integrated Development Environment (IDE).The IDE’s are differing from form one operating system to n other. Some windows basedIDE’s are Turbo ‘C’, Turbo C++, Microsoft Visual Basics, Microsoft .NET, etc…. Debugging: In the program does not produce desired results, it is necessary to go back and reanalyze the programs logic this process is called debugging. By using this process we can remove bugs (problems) in the program.Language interpreters: Interpreters are another type used for analyzing and executing programs developed inhigh-level languages. Interpreters are analyzed and execution of statements in a program issame time. The method usually allows programs to be more easily debugging. Basic and java programming languages are use these interpreters for analyze andexecution of programs.Character set: Character set means that the characters and symbols that a C program can accept.These are grouped to form the commands, expressions, words, C statements and other tokensfor C language character set is the combination of alphabet or character, digit, specialcharacters and white spaces. 1. Letters (A…….Z and a………z) 52 2. Digits (……9) 10 3. Special characters (. , ; : ? / < >….) 29 4. White spaces Blank, Horizontal tab, 5 Carriage return, new line, Form feeds 96 8
  9. 9. Programming in ‘C’C Tokens: In a passage of text, individual words and punctuation marks are called token.Similarly in a C program the smallest individual units are known as c tokens. C TOKENSKeywords Identifiers Constants Strings Operators SpecialsymbolsFloat main 50.00 “computer” +-*/ { < [ ? ….Int a -21.43 “a”While cost1. KEYWORDS: Every C word is classified as either a keyword or an identifier. All keywords havefixed meaning and these meanings cannot be changed. Keywords serve as basic buildingblocks for program statements. All keywords must be written in lower case. auto double int struct break else long switch case enum register typedef char exturn return union const float short unsigned continue for signed void default goto sizeof vollatile do if static while2. IDENTIFIERS: Identifiers refer to the names of variables, function and arrays. These are user-definednames and consist of a sequence of letters and digits with as a first character. Identifiershould not be a keyword. 9
  10. 10. Programming in ‘C’ Variable: A variable is a data name that may be used to store a data value. A variable may take different values at different times during execution. The programmer can choose a variable name in a meaningful way. Rules for a variable:  The first character of the variable name should be a letter (alphabet).  A variable should not be a keyword.  A variable name can be of any length in recent compilers but some implementations of C recognize the first eight characters as the valid variable name.  No special characters are allowed in the variable name except underscore.  The blank space characters are also not allowed while constructing variable names.  Upped and lower case letters are different in variable names. Because C is case sensitive language.  It is always useful to give the meaningful names to the variables. Some valid variable names are. ROLLNO, Area, arc, n1, n_1, n1_n2……3. CONSTANTS: Constants in C refer to fixed values that do not change during the execution of aprogram. Constants Numbered constants Character constants Integer Float Single String Black slash Decimal Octal Hexa- decimal 10
  11. 11. Programming in ‘C’1. Numeric constants: These have numeric value having combination of sequence of digits i.e from 0-9 asalone digits or combination of 0-9 ,with or without decimal Point having positive or negative sighn. These are further sub—divided into twocategories as: a) Integer Numeric constant b) Float Numeric constanta) Integer numeric constant: Integer numeric constant have integer data combination of 0-9 without any decimalpoint and with any + or – sign. These are further sub-divided into three parts. Decimal integer consists of a set of digits 0-9, preceded by an optional – or + sign. Examples: q23 -321 +7546 Embedded spaces, commas and no-digit characters are not permitted . An octal integer constant consists of any combination of digits from 0 to 7, with a leading 0. A sequence of digits proceeding by OX or ox is considered as hexadecimal integer. They may also include alphabets ‘A’ through ‘F’ or ‘a’ through ‘f’. The letter ‘A’ through ‘F’ represents the numbers 10 through 15. Examples: OX2 Ox9F Oxbcd Note: We rarely use octal and hexadecimal numbers in programming.b) Float Numeric constant Some constants which have a decimal point or a precision value with in having anypositive or negative sign is called floating point constant . Float constants has two parts. Oneis mantissa and the other is exponent pat. These two parts in a real number are represented as: Mantissa E exponent 11
  12. 12. Programming in ‘C’ The mantissa is either a real number expressed in decimal notation or an integer. Theexponent is an integer umber with an optional + or – sign. The letter E separating themantissa and the exponent can be written in either lowercase or uppercase. Example: 3.5x102 can be written as 3.5E22). Character constant:a) Single character constant: It contains a single character enclosed within a pair of single quote marks. Example: “Hellow” “2007” “X” “9+22+17”b) String character constant: String constant is a sequence of characters enclosed in double quotes. The charactersmay be letters, umbers special characters and blank space. Example: “hallow” “2007” “x” “9+22+65”c) Backslash characters: C supports some backslash character constants that are used in output functions.These character combinations are known as escape sequence. Constant Meaning ‘a’ Audible alert (bell) ‘b’ Back space ‘n’ New line ‘t’ Horizontal ‘0’ Null4. OPERATORS: An operator is a symbol that tells the computer to perform certainmathematical manipulations.Types of Operators:1. Arithmetic 2. Relational 3. Logical 4.Assignment5. Increment and decrement 6. Conditional 7. Bitwise 8. Special 12
  13. 13. Programming in ‘C’1. Arithmetic Operators: Arithmetic operators are Operator Meaningused for arithmetic operations like Addition, + AdditionSubtraction, Multiplication, Division etc. - Subtraction If all operands are integers, the result is an * Multiplication integer. / Division If an operand is a floating point or double % Modulo Division (Remainder precision value, the result is a double. after division)2. Relational Operators: We often compare two Operator Meaningquantities, and depending on their relation, take < Is less thancertain decisions. These comparisions can be done <= Is less than or equal towith the help of relational operators. Containing a > Is greater thanrelation operator is termed as a relational expression >= Is greater than or equal tois either 1(true) or (false). == Is equal to != Is not equal to Operator Meaning3.LogicalOperators:Anexpression,which combines && ANDtwo or more relational expression, is termed as alogical expression. || OR ! NOTLogical Table: A B A AND B A OR B NOT A T T T T F T F F T F F T F T T F F F F T4. Assignment Operator (=): Assignment operators are used to assign the result of anexpression to a variable.Syntax: variable=expressionWhere, expression is whose value is to be assigned to the variable.Examples: a=10 b=20 sum= a+b 13
  14. 14. Programming in ‘C’5. Increment and decrement Operators: The operators ++ adds 1 to the operand and theoperator – subtracts 1 from operand. We use the increment and decrement statements are usein for and while loops extensively.Example: A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. m=5; Y=++m; In this case the value of y and m would be 6. A postfix operator first assigns the value to the variable on the left and the increment the operand. m=5; Y=m++; In value of y would be 5 and m would be 6.6. Conditional Operator: A ternary operator pair ‘?:’ is available in C to constructconditional expressions of the form. Var1=condition? exp2: exp3;The operator ‘?:’ works as fallows condition is evaluated first. If it is nonzero (true) then theexpression exp2 is evaluated and becomes the value of the var1. If condition is false, exp3 isevaluated and its value becomes to the value of the var1.Example: a=10; if(a>b) b=15; x=a; X=(a>b)?a:b; else x=b;7.Bitwise Operators: C has a distinction of Operator Meaningsupporting special operators for manipulation of & Bitwise ANDdata at bit level.These operators are used for | Bitwise ORtesting the bits, or shifting them right or left. ^ Bitwise Exclusive ORThese operators are not applicable to the float or << Bitwise Leftdouble data types. >> Bitwise Right ~ Bitwise NOT 14
  15. 15. Programming in ‘C’ 1. Bit wise AND: The bit wise AND operator is represented by the symbol &. When this operator is used, it compare the corresponding bits in the two operands and when they both are 1 then the corresponding bit in the result is 1, in all the other cases it is 0. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a&b=0 0 0 0 0 1 0 1 2. Bit wise OR: The bit wise OR operator is represented by the symbol |. When this operator is use d, it compare the corresponding bits in the 2 operands and when they both are 0 then the corresponding bit in the result is 0, in all the other cases it is 1. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a | b=0 1 0 1 0 1 1 1 3. Bit wise Exclusive OR: The bit wise OR operator is represented by the symbol ^. When this operator is used, it compare the corresponding bits in the 2 operands and when they both are either 0 or 1 then the corresponding bit in the result is 0, in all the other cases it is 1. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a^b=0 1 0 1 0 0 1 0 4. Bit wise NOT: The bit wise NOT operator is represented by the symbol ~. When this operator is used, in inverts each bit in the operand. In other words, each 0 in the operand is changed to 1 and vice-versa. Example: a=0 0 0 0 0 1 0 1 ~a=1 1 1 1 1 0 1 05. Right Shift: It has the purpose to transfer the bits of data to the right side. It is a binary operator that is it has two operands. The left operand is the data and the right operand is the number of times the shift operation to be done. Example: a= 0 0 0 0 0 1 0 1 a>>2= 0 0 0 0 0 0 0 1 15
  16. 16. Programming in ‘C’ Hence, the least significant bit will be discarded and the most significant bit will come outto be 0.6. Left Shift: It has the purpose to transfer the bits of data to the left side. It is a binaryoperator i.e. it has two operands. The left operand is the data and the right operand is thenumber of times the shift operation to be done. Example: a= 0 0 0 0 0 1 0 1 a<<2=0 0 0 1 0 1 0 0 Hence, the most significant bit will be discarded and the least significant bit will come outto be 0.8. Special Operator: These are used for special purpose in C language. These operations areused in pointers, structures and unions etc. 1. Unary operator 2. Comma operator 3. Sizeof() Operator 4. Type operator 5. Pointer operator 6. Member selection operator1. Unary Operator: These are used for identification of about where it is signed or unsigned. These are +and -. Also increment or decrement operators ++, -- are in the unary operator category asspecial operator.Example: x=-3; y=++x-7*32. Comma operator: The comma operator can be used to link the related expression together. A commalinked list of expression is evaluated left to right and the values of right most expression isthe value of the combined expression.Example: z=(x=10,y=5,x+y); First assigns the value 10 to x, then assign 5 to y and finally 15 to z. 16
  17. 17. Programming in ‘C’3. Size of ()operator: The sizeof() is a compile time operator and, when used with an operand, it returns thenumber of byte the operand occupies. The operand may be a variable, a constant or a datatype qualifier.Syntax: Variable=sizeof(v or e)Example: int a; K=sizeof(a) the value of k is 2 (because a occupies two bytes of memory)4. Type operator: Type operator is used for conversion purpose or casting purpose. So it is calledconvert operator. This operator converts float type data into integer form and vice-versa. It isused for casting a value and process to convert from 1 form to another is called casting.Syntax: (Type)v or e; where v is variable e is an expressionExample: int a=10, b=3; float c; C=a/b; If we divide a by b, then result stored in the c variable be 3.000000. But by using thetype operator, we can get the float value as C=(float) a/b; Now c value is 3.3333335. Pointer operator: There are two types of pointer operators used in C language. These are & and *.6. Member selection operator: There operators are used in structure and union. These are used to create a relationbetween owner and member within a structure or union data. These are “.” and . 17
  18. 18. Programming in ‘C’DATA TYPES: C language is rich in its data types. ‘C’ language supports the following data types. DATA TYPES Scalar Derived User Void Pointer Defined Char array or string enum Integer structure Float union typedef Double1. Scalar/ standard/ primary/ fundamental data types: A scalar data type is used for representing a single value only. It is only called simpleor fundamental data type.Size and range of basic data types: Data type Size Range of value char 1 byte -128 to 127 int 2 bytes -32,768 to 32,767 float 4 bytes 3.4e-38 to 3.4+38 double 8 bytes 1.7e-308 to 1.7e+3082. Derived data types: Derived data types are derived from the scalar data type by adding some additionalrelationship with the various elements of the primary or scalar data types. Note that deriveddata type may be used for representing a single value or multiple values. These are furthersub divided into three categories. 1. Array and strings 2. Structures 3. Unions(a). Arrays: An Array is nothing but a collection of sequence of homogeneous(similar) datatype elements.Declaration of an array: Data type variable-name [size];Where datatype can be any primary or secondary datatypes. Size is any integer.Example: int a[50]; 18
  19. 19. Programming in ‘C’(b). Structure: A Structure is nothing but a collection of heterogeneous (different) datatypesof elements.Declaration of structure: Struct tage_name { datatype field1; datatype field2; ……………… datatype field n; };Where tagename is the name of the structure / datatype can be any primary or secondarydatatype.Example: struct student { int sno; char name[10]; float m1,m2,m3; }; Once the structure data type is defined, the variable of that datatype can be declaredof follows.Syntax: struct tagname variablelist;Example: struct student s;3. User defined type: This is also used for definition, i.e. it allows the users to define a variable or anidentifier, which is used for representation of existing data types.a) enum: Another user defined data type is enumerated data type provided by ANSIstandard. Syntax: enum identified {value1, value2…..} variable; The identifier is a user- defined enumerated data type, which can be used todeclare variables that can have one of the values enclosed within the braces known asenumeration constant.Example: enum day{Monday, Tuesday, Wednesday,..} d; 19
  20. 20. Programming in ‘C’b). type def: Supports a feature know “type definition” that allows user to define an identifierthat would represent an exiting data type. The user-defined data type identifier can later todeclare variable. Syntax: typedef data_type identifier; Where type represents the data type of the identifier refers to the ‘new’ name givingto the date type. Ex: typdef int marks; Here marks symbolize int. they can be later used to declare variable as follows. marks m1,m2; m1,m2 are declared as int variable. The main advantage of typedef is that we cancreate meaningful data type names for increasing the readability of the program.4. Void: Void or empty data type is used in user defined function or user defined subprograms. These are used when the function sub-program returns nothing to the callinglocation. Also it is used when a function or a sub-program have not any argument in it.5. Pointer data type: Pointer data type is used to handle the data at their memory address.Input / output functions In ‘C’ language I/O functions are categorized into following two types. Input/output functions UnFormatted I/O Formatted I/O statements statements getchar(); putchar(); scanf(); printf(); gets(); puts(); getch(); getche();1. Formatted I/O statements: All input/output operations are carried out through function calls such as printf andscanf there exist several functions that have more or less become standard for input andoutput operations in C. There functions are collection known as the standard i/o library. 20
  21. 21. Programming in ‘C’ #include<stdio.h> The instruction <stdio.h> tells the compiler to search for a file stdio.h and place it’scontents at this point in the program. The content of the header file become part of the sourcecode when it is compiled. Conversion character Meaning %d Integer %f Float %c Character %s String %lf Doublea). scanf(): The scanf() function is an input function. It used to read the mixed type of data fromthe keyboard. You can read integer, float and character data by using its control codes orformat codes. Syntax: scanf(“control string”,&v1,&v2…); The control string contains the format of data being received. The ampersand symbol‘&’ before each variable name is an operator that specifies the address of variable v1. Example: scanf(“%d”,&n); The control string %d specifies that an integer value is to be read from the terminal(keyboard).b). printf(): printf() fiunction for printing captions and numerical results the general form ofprintf statement is…. printf(“controle string”,arg1,arg2…);control string consists of three types of items:  Characters that will be printed on the screen as they appear.  Format specifications that define the output format for display of each item.  Escape sequence character such as n,t….. the control string indicates how many arguments follow and what their types are the argument arg1,arg2… are the variable whose values are formatted and printed according to the specification of control string. 21
  22. 22. Programming in ‘C’2. Unformatted I/O statements: These functions are used to read or print the data in unformatted way. These are alsocalled as character I/O functions. The following are the character I/O functions. Input functions output functions getchar(); putchar(); getche(); putc() getch(); gets();a). getchar(): This is an input function. It is used for reading a single character from the keyboard. Itis buffered function. Bu8ffered functions get the input from the keyboard and store it in thememory temporarily until you press the enter key. After you pressed the enter key then inputmove to a relevant variable. Syntax: v=getchar(); Example: char a; a=getchar();b). gets(): This is an input function. It is used for read a string from the keyboard. It is a bufferedfunction it will read a string, when you type the string from the keyboard and press the enterkey from the keyboard. It will mark null character (‘0’) in the memory at the end of thestring, when you press the enter key. Syntax: gets(v); Example: char s[20]; gets(s);c) getch(): This is also an input function. This is used to read a single character from thekeyboard like getchar() function. But getchar() function is a buffered function; getch()function is a non buffered function. When type the character data from the keyboard it doesnot visible on the screen. Syntax: v=getch();d). getche(): All are same as getch() function except that when you type the character data from thekeyboard it will be visible on the screen. Syntax: v=getche();e). putchar(): 22
  23. 23. Programming in ‘C’ This function is an output function. It is used to display a single character on thescreen. Syntax: putchar(v); Example: char a; getchar(a);f). puts(): This function is an output function . It is used to display a string inputted by gets()function, which you will read in the next on the screen. Syntax: puts(v); or puts(“text); Example: char a[10]; gets(a);Control statements: Normally C-compiler executes all the statements in the program sequentially in topdown process. In C-language some times we have to control the execution of program, Sometimes the program executes some group of statements in the program, some other timeanother group of statements in the program comes for execution. When ever the programneeds this type of situation, place some condition statements in the program. Thoseconditions are made with the help of relational operators. The condition will execute andreturns the value 1 (TRUE) or 0 (FALSE) to specified location, where the condition place inthe program. C-language provides several types of decision making or control statements.They are: 1. If 2. Switch 3. looping statements.IF conditional statement: ‘ If ’ it is one of the keyword in the C-language, by using this we make some controlson the execution of program. The general syntax of the ‘if’ is: if(condition) { Executable Statements; } 23
  24. 24. Programming in ‘C’ In the above syntax ‘if ‘ is a key word. The condition is following by the keyword if.When ever the condition comes to execution, if the given condition true, it will return 1 to ifstatement. If the given condition is false, it will return 0 to if statement. We have several formof if statements in C-language. They are: 1. Simple if. 2. if else. 3. else if or else if ladder. 4. Nested if.1. Simple if: In simple if, the given condition is true, then some statements in program will comefor execution other wise normal statements will execute. The general syntax of the simple ifis: --------------- if(condition) Texst No exp { Yes Stament1; Statements } In the above syntax the condition following by the keyword ‘ if ‘. The executablestatements are enclosing with opening and closing curling braces ({). The compiler identifies,those statements are comes under if block. When ever the condition in the ‘if’ statement is true it will return 1 to for if statement,other wise it returns 0 for ‘if’ statement. The given condition is true, then the givenstatements (statement1) in the ‘if’ part will come for execution other statement1 absence inthe execution, the compiles goes to execution of normal statements in the program.Example program on simple if condition:#include<stdio.h>main(){ int num; clrscr(); 24
  25. 25. Programming in ‘C’ printf(“Enter your number”); scanf(“%d”,&num); if(num>0) { printf(“ given number is +ve :”); } printf(“Given number is : %d”, num); getch();}2. if else conditional statement: It is also one of the conditional statements in the C-language. If else is the extensionof the simple if. The general syntax of the ‘if else’ conditional statement is: --------------- if(condition) Texst No exp { Yes Stament1; Statement1 Statement2 } else { Statement2; } ---------------- In the above syntax, if else statement having condition following the keyword if. The‘if’ else statement is divided in to two parts, one is if (TRUE) part and another one is else(FALSE) part. If the given condition is true, then if part statements (Statement1) will comesfor execution. If the given condition is false, then else part statements (Statement2) willcomes for execution. When ever the first if statement succeeds, the second must fail, and vice versa. In thisif else conditional statement either if part statements or else part statements only comes forexecution another one absence in the execution time. When ever the C-program having two 25
  26. 26. Programming in ‘C’options for execution we use this is else statement. If the ‘if’ part or else part having singlestatement, opening and closing curling braces are optional.Example program for if else if:#include<stdio.h>main(){ int num; clrscr(); printf(“Enter your number”); scanf(“%d”,&num); if(num%2= =0) { printf(“ %d is even number”, num); } else { printf(“%d is odd number”, num); } getch();}3. else if or else if ladder: When ever the C-program needs to check or build the conditions in different levelselse if ladder type is used. In this else if type, the main if having condition, if the if partcondition is fail, the else part having another condition, if the else if part condition fail thenelse part having another condition… then the conditions are arranger in the ladder or chainformat. The else if conditional statement having common else for the all the else ifstatements, if all conditions in the else if are fail then else part will executes, this else part isoptional. The general syntax of the else if conditional statement is: 26
  27. 27. Programming in ‘C’ --------------- if(condition1) Texst No exp { Yes Stament1; Texst No exp Statement1 } Yes else if(condition2) Statement2 Statement3 { Statement2; } else This else part is optional { Statements3; } ---------------- The above syntax represents the else if conditional statement arrangement. Thecondition1 following main if, if the condition1 is true then if part statements (Statement1)will come for execution. If the if part condition is false then the compiler will check the nextelse if part condition, if it is true then the compiler will executes statements2 in the else ifpart, if it will also false then compiler check the next condition. In this way the compiler willcheck all the sequence of else if conditions in the program, all the conditions are false thendefault else part statements (Statements3) will comes for execution.Example program for else if statement:#include<stdio.h>main(){ int n1,n2,n3; 27
  28. 28. Programming in ‘C’ clrscr(); printf(“Enter 3 number”); scanf(“%d%d%d”,&n1,&n2,&n3); if((n1>n2)&&(n1>n2)) { printf(“ %d is big number”,n1); } else if(n2>n3) { printf(“ %d is big number”,n2); } else { printf(“ %d is big number”,n3); } getch();}4. Nested if conditional statement: When ever the C-program need to check the conditions, condition with in theconditions, use this nested if conditional statement. In this nested if conditional statement allthe conditions or some conditions are arrange in nested form. May be the main if or else partbody having another if of if else statement. The general syntax of the nested if is: ---------------- if(condition1) { if(condition1) { Statement1; 28
  29. 29. Programming in ‘C’ } else This else part is optional { Statement2; } } --------------- The syntax represents the nested if conditional statement. The main if body havinganother if condition, in this we place number of if conditions as condition with in thecondition. If all the given conditions in the ‘if’ part will true then only the statement1 willcome for execution, other wise it will execute the normal program. If the main if is false thenonly the else part will come for execution, if inner most condition of the main if is false, thenthe compiler goes to after the else part statements execution.Example program for nested if conditional statement:#include<stdio.h>main(){ int n1,n2,n3; clrscr(); printf(“Enter 3 number”); scanf(“%d%d%d”,&n1,&n2,&n3); if((n1>n2)) { if(n1>n3) { printf(“ %d is big number”,n1); } else { printf(“ %d is big number”,n3); } } else { 29
  30. 30. Programming in ‘C’ if(n2>n3) { printf(“ %d is big number”,n2); } else { printf(“ %d is big number”,n3); } } getch();}Compound relation test: A compound relation test is a simple way to combine more then one conditions orrelations, with the help of logical operators. Those logical operators are; and (&&), or( || ). Syntactical representation of the compound relations are. ((condition1)&&(condition2)…..) ((condition1)||(condition2)…..) These compound relations are used with the “if” conditional statement. Example: if((a>b)&&(a>c)) if((a>b)||(a>c)) { { Statement1; Statement2; } } The above example shows the compound relation of the condition. The a>b and a>care two individual conditions we can combine these two conditions with help of logical and,or operators, it form a single condition statement.2. Switch conditional statement: The switch statement is used to execute single statement or choices form manystatements or many choices. In this switch each choice can be represented with case of theswitch statement. The switch, case, default these three key words are arranged correctly, thenif will form a control statement. 30
  31. 31. Programming in ‘C’The general form of the switch conditional statement is: switch( variable or integer expressions) { case constant1: statement1; break; case constant2: statement2; break; default: statement n; } The switch is a keyword. The switch statement requires single variable or integerexpression as arguments. The keyword case is followed by an integer or character constant(1,2,3…., ‘a’,’b’,…’A’,’B’…). The keyword default represents the default case of the switch.All the cases of the switch is enclosed with opening and closing curling braces ( { } ), and itis having an other case is called default case. When ever the value in the variable is equals tothe constant value of the specified case in the switch is executed. The value in the variable isnot match with the constant values of all the cases in the switch, and then the default case isexecuted. The value in the variable is equal to the constant in the case 1, and then statement 1is executed, if the value is not mach with the value in the case 1, then the compile check withnext case constant. In this way the compiler will check with each and every constant value ofthe cases in the switch.Example program for switch conditional statement:#include<stdio.h>main(){ 31
  32. 32. Programming in ‘C’ int n1; clrscr(); printf(“Enter number between 1 to 5”); scanf(“%d”,&n1); switch(n1) { case 1: printf(“n I am in case 1”); break; case 2: printf(“n I am in case 2”); break; case 3: printf(“n I am in case 3”); break; case 4: printf(“n I am in case 4”); break; case 5: printf(“n I am in case 5”); break; default: printf(“ I am in default case”); } getch();}Looping statements: Loops are used for, when ever the C-program needs to execute the steps repeatedly. Inwill repeatedly execute some sequence of steps or some portion of the program specifiednumber of times. The loop execution is controlled with the help of the loop controlinstruction or loop condition. The statements in the loop will execute until the givencondition is false. In C-language we have three types of looping statements. They are: 1. While statement. 2. For statement. 3. Do while statement. 32
  33. 33. Programming in ‘C’ The looping statements are divided in to two types based on condition checkinglocation. They are entry level condition checking, exit level condition checking. The for andwhile looping statements are comes under entry level condition checking. The do whilelooping statement is comes under exit level condition checking.1. While looping statement: The while is a keyword C-language; use this keyword as looping statement. The whileis an entry controlled loop statement. The general syntax of the while looping statement is. Variable Initialization; while( test condition ) { Body of the loop; Increment or decrement operations; } Start Initialization No Test exp Yes Stop Body of the loop Increment or Decrement operations It is often execute some sequence of steps or some part of a program, use this whileloop. In the while loop first initialize the starting value to the variable for counting purpose ofthe loop iterations. Iteration is the process of loop execution. The while is a keywordfollowed by the test condition. The body of the loop and the increment or decrementstatements are enclosed by the opening and closing curling braces ({}). The test condition istrue then the body of the loop will come for execution and perform increment or decrementoperations. After performing increment or decrement operations the test condition is once 33
  34. 34. Programming in ‘C’again evaluated, if it is true the body of the loop is again executed. The process of repeatedexecution of the body continues until the condition false the control is transfer to out of theloop. The braces are need only if the body of the loop contains two or more statements.Example program for while looping statement:#include<stdio.h>main(){ int i,num; printf(“Enter number”); scanf(“%d’,&num); i=1; while(i<=num); { printf(‘%dt”,i); i=i+1; } getch();} The above program is used to display the numbers from 1 to given number. The ivalues is initializes with one, and check the while loop condition and executes the body of theloop. Then perform increment operation. The body of the loop executes continually until Ivalue greater then value in the variable num.2. For looping statement: The ‘for’ loop is another Entry controlled looping statement. For is a keyword, byusing this we can build a looping statement. 34
  35. 35. Programming in ‘C’The general syntax of for looping statement is: for(intilization;condition;increment or decrimrnt) { Body of the loop; } Handling of for loop is easy to compare remaining looping statement. In whilelooping statement, the initialization, conditions and increment and decrement statements areplaced in different locations. In for looping statement this initialization, condition andincrement and decrement statements are place in one location these are separated bysemicolon (;). Those three statements are enclosed with parentheses. The initialization part isused for initialize counter variable for loop execution. The body of the loop will execute untilthe given condition is false. The body of the loop is enclosed with closing and openingcurling braces ({ }), if the body of the loop has single statement need not to write braces. Butit is good practice to open the braces even it has single statement.Execution process of for loop: Fires the initialization of control variable of loop will execute, after the execution ofinitialization statement the control will follow up the next condition checking statement in forloop. If the given condition is true, then the body of the loop will come for execution. Nextthe control will transfer to increment or decrement statement and execute the step, then thecontrol goes to condition checking, if the condition is true, again the body of loop willexecute this process is continue until the given condition false.Example program for ‘for’ looping statement:#include<stdio.h>main(){ int i,num; printf(“enter number”); scanf(“%d”,&num); for(i=1;i<=num;i++) { 35
  36. 36. Programming in ‘C’ printf(“%4d”,i); } getch();} In the above, variable ‘i’ is used for counter of the loop. It will initialize to value 1 thefirst time execution of for loop. The execution of loop terminates when the ‘i’ reaches to,value in the variable ‘num’. In this process the ‘i’ value increment once each and every timeexecution of loop.3. Do while looping statement: The do while is the exit controlled looping statement. The while loop construct as thetest condition is made at the beginning of the loop and also condition will comes forexecution beginning of the loop. There fore the body of the loop may not executes, all theconditions of while loop is not satisfied at the entry first time. Some times it might benecessary to execute the body of the loop before the test is performed. In such a situation canbe handling with the help of the do statement.The general form of the do-while statement is:Initialization;do{ Body of the loop; Increment or decrement operations;}while(condition); The working of while and do while loops are same but only difference is, in while testcondition will be executed before executes the body of the loop. In ‘do while’ fist the body ofthe loop will executes, at the end of the loop test condition is executed. This means in ‘dowhile’ the body of the loop executes at least once, if the condition is fail. Remaininginitialization and increment decrement statements are located in same location in ‘while’ and‘do while’ loops. 36
  37. 37. Programming in ‘C’Example program for the ‘do-while’ looping statement:#include<stdio.h>main(){ int i,num; printf(“Enter number”); scanf(“%d’,&num); i=1; do { printf(‘%dt”,i); i=i+1; } while(i<=num); getch();} In the above program the initialization is made at the beginning of the loop, next thebody of the loop is executed. After the execution of the increment statement of the ‘i’, the testcondition of the while is executes.Difference between while and do-while loop:While loop Do-while loop1. While loop can also called as an entry 1. Do-while loop can also be called as an exitcontrolled loop. controlled loop.2. In the While loop the condition is placed at 2. In the Do-While loop the condition isthe beginning of the loop. placed at the end of the loop.3. In the case of While loop after executing 3. In the case of Do-While loop, afterthe initialization section, the condition will executing the initialization section, the bodybe tested if it is true, the body of the loop is of the loop will be executed and then theexecuted. condition will be tested for the continuation of the next iteration. 37
  38. 38. Programming in ‘C’4. In the case of While loop, if the condition 4. In the case of Do-While loop, the body ofis found to be false for the first time, the will be executed at least once withoutbody will never be executed and the loop will depending on the vale of the terminated.5. In most applications the while loop is user 5. In the body is to be executes at least once,friendly. the Do-While loop is much more suitable.6. It is possible to have nested while loop 6. It is also possible to have nested Do-Whilewhile loop can also contain a Do-While loop. loops. Do-While loop can also contain a while loop.7. The general syntax of the While is: 7. The general syntax of the Do-While is:Variable Initialization; Initialization;while( test condition ) do{ { Body of the loop; Body of the loop; Increment or decrement operations; Increment or decrement operations;} }while(condition);Nested loops: The nested loops are used where the program needs loop with in the loop. Whichprocedure used for nesting of ‘if’, that can be used for nesting loops. The nesting loops aremade by using while, do-while and for looping statements. Writing nested loops in while, foris easier to compare do-while. The general form of the nested loops is:Initialization; for(intilization;condition;increment or decrimrnt)while( test condition ) {{ Initialization; for(intilization;condition;increment or decrimrnt) while( test condition ) { { Body of the loop; Body of the loop; Increment or decrement operations; } } Body of the loop; Body of the loop; Increment or decrement operations;} } 38
  39. 39. Programming in ‘C’Working of nested loops: First the outer loop initialization statement is executed, after test condition statementis executed if it is true, then the body of the loop is executed. The outer loop body havinganother looping statement, we can call it is an inner loop. Then the inner loop initializationstatement is executed, next the inner loop test condition will be processed, if it is true then theinner loop body is executed. Next increment process is done. After that the control goes fortest condition, if it is true again the body of the loop is executed this process is continue untilthe inner loop condition become false. When ever inner loop test condition is false the loopwill be terminated control will execute remaining statements in the out loop. After that thecontrol goes to increment or decrement operation, next the control goes to check thecondition of the loop if again it is true, again the inner loop is executed. This process is doneuntil the outer loop condition becomes false.Unconditional statements: In the conditional statements the control will go to specified location when ever thegiven condition either TRUE (1) or FALSE. (0). In the unconditional statements, when everthe compiler reads the unconditional statement the control will goes to specified location without testing any condition. Here the control will jumps to specified location automatically sothis statements also called jumping statements. C-language provides three jumping statementsthey are: 1. goto. 2. break. 3. continue.1. goto: The goto unconditional statement is used to transfer the control from one location toanother location in the program. Here goto is keyword in C-language. This statement is usedwith the help of crating labels in the program; ‘goto’ keyword is followed by the specifiedlabel in the program. Syntax: goto <label name>; Example: goto a;Example program for goto statement:#include<stdio.h> 39
  40. 40. Programming in ‘C’main(){ int a,b,c; ptintf(“Enter 2 numbers”); scanf(“%d%d”,&a,&b); c=a+b; printf(“Sum : %d”,c); goto a; c=a-b; printf(“Sub : %d”,c); a: getch();} In above program after the execution of ‘goto a;’ statement control will goes to label‘a:’, statements after the program will never participate in the execution.2. break: In C language ‘break’ statement is used for stop the execution of statements orprogram unconditionally. When ever use the break statement in program, the control willnever executes the statements available, after the ‘break’ statement. When the compiler readsthe break statement the compiler terminates from the execution of the program. Syntax: break; Example: break;Example program for ‘break’ statement:#include<stdio.h>main(){ int n,i,sum=0,num; printf(“Enter number:”); scanf(“%d”,&n); printf(“Enter %d numbers”,n); 40
  41. 41. Programming in ‘C’ for(i=1;i<=n;i++) { scanf(“%d”,&num); if(num<0) { break; } sum=sum+num; }} The above program we can calculate the sum of ‘n’ numbers. When ever user give –ve value to the variable ‘num’ then the loop execution is terminated. Break is used for stopthe normal execution of for loop at that specified time.3. continue: The ‘continue’ is a keyword in C-language. This ‘continue’ statement is mainly usedin looping statements. Some times the program needs to transfer the control to the starting ofthe loop. When ever the control reads the continue statement in the loops, the control neverexecutes the statements after the ‘continue’ in the loop. The control will transfer to thebeginning of the loop. Syntax: continue; Example: continue;Example program for ‘continue’ statement:#include<stdio.h>main(){ int n,i,sum=0,num; printf(“Enter number:”); scanf(“%d”,&n); printf(“Enter %d numbers”,n); for(i=1;i<=n;i++) { 41
  42. 42. Programming in ‘C’ scanf(“%d”,&num); if(num<0) { continue; } sum=sum+num; }} The above program is used to calculate the sum of ‘n’ +ve numbers. When ever theuser gives –ve number to the variable num the compile never add that value to the previoussome. This process is done by using continue statement with in for loop. The compilerdecides the given number is –ve, automatically the control will goes to beginning of the loop. 42
  43. 43. Programming in ‘C’ Arrays When ever the program need to tack group of similar data elements, it is highlyimpossible to create individual variables, and also accessing values, C-language provide afeature called ‘Array’. An array is a group of related data items that are share common name.Array is a set of homogeneous elements. Values in the array can be accessed by the specialnumber or integer is index of an array. Array indexing is starts every time with ‘0’.Arrays are two types: 1. Single dimensional arrays. 2. Multi dimensional arrays.Single dimensional arrays: A list of items can be given one variable name using only one subscript such avariable is called single dimensional array.Declaration of array: Array variable can be create like normal variable, but only difference is normalvariable take only single value, array variable can accept ‘n’ number of variables, ‘n’represents the size of an array. General declaration of an array variable is: Data type variablename[size]…; In the above syntax, data type represents which type of values accepts into an arrayvariable. Variable name represents the identifier of an array; size represents how manyelements array can accept. Each and every value in the array can be accessed with the help ofan integer or number is called ‘index’ of an array, it can be place with in the brackets after thearray name. int rollno[10]; It represents the ten students roll numbers. Variable ‘rollno’ can share all the ten rollnumbers of the ten students. rollno[0] is the roll number of the single student, rollno[1] is theroll number on another student etc… the array indexing starts with 0 and ends with n-1. 0 isthe lower bound or limit of an array; n-1 is the upper bound or limit of an array.Internal storage of array: If the array variable is declared like this: int a[5]; 43
  44. 44. Programming in ‘C’ Address 2000 2002 2004 2006 2008 Elements 50 34 65 5 12 Locations or a[0] a[1] a[2] a[3] a[4] subscriptsInitializing values into an array: Values initialization process is done like initialization of values to the normalvariable. The values are assigned to each and every location, with the help of index value ofan array. Values assigned at the time of declaration. int a[5]={12,54,23,1,654}; Values assign to individual array variable: a[0]=20; a[4]=43; Read values from the keyboard for array variable: scanf(“%d”,a[0]); Read group of values into an array at a time we need loops. When ever we need toread group of values for an array, we can write scanf statement for each and every variable.This is highly impossible to write scanf statements for number of values, C-languageminimize this process with the help of loops. The below example represents read values intoan array from keyboard. for(i=0;i<n;i++) { scanf(“%d”,&a[i]); }Access values in the array variable: Like normal variables, we can get the values in the array with the help of variablename. But we can distinguish each and every variable with the logical address of the arrayvariable. Suppose you want to access 2nd logical location value in the array we can representlike this ‘a[2]’. We can access group of values at a time with the help of loops. 44
  45. 45. Programming in ‘C’ for(i=0;i<n;i++) { printf(“%d”,a[i]); }Multi dimensional array:Two dimensional arrays: In two dimensional arrays comes under multi dimensional type. In this type the arrayvariable name having two subscripts such a variable is called two dimensional arrays. Whenever program need to organize the data in rows and columns, use this two dimensional array.The first subscript represents row size and second subscript represents column size. By usingthis 2d array we can organize or store data in the form of tables. It is similar to the matrixform to define the table of items the two dimensional are convenient.Declaration of two dimensional arrays: The general declaration of 2d arrays: datatype varablename[row size][column size]…; The data type represents, which type of values can be accepted by the array. Thevariable name represents the identification label of the array. The first subscript represents,how many rows of data can be accepted by the array. The second subscript represents, howmany columns of data can be accepted by the array. int m1[2][2]; The above 2d array variable can accept two rows and two columns of data. The arrayvariable ‘m1’ can accept integer values only. In single dimensional array we can access thearray values, by using single index value. In 2d array, values can be accessed with the help oftwo indexing values. First one represents row index second one represents column indexvalue. For example m1[0][1] represents the value in the ‘0’th row ‘1’ st column.Initializing values to 2d array: Initializing values to 2d array with the help of indexing values, this indexing valuesare represented with combination row and column indexing vales. Values assigned at time of declaration: int a[2][2]={{12,32},{23,54}}; Values assigned to individual variable: a[1][0]=34; 45
  46. 46. Programming in ‘C’Initial storage of 2d array: The array variable can be stored like this: int a[2][2]; Address 2000 2002 Elements 50 34 1st row Locations or a[0][0] a[0][1] subscripts Address 2004 2006 Elements 50 34 2nd row Locations or subscripts a[1][0] a[1][1] 1st column 2nd columnReading values into 2d arrays: When ever we need to read or get values from the output screen. We can get thosevalues with the help of nested looping statements. The general format to read values to 2darrays: for(i=0;i<row size;i++) { for(j=1;j<size of column;j++) { scanf(“ “); } } 46
  47. 47. Programming in ‘C’ StringsString: In arrays we can store group of numerical values, string can also store group of valuesthose values comes under character type. String is a collection of character values, when wedeclare the array variable under char data type the variable is called as string variable.Normal char variable can accept only single character value, it can’t accept group of characterlike persons names etc… C-language minimizes this problem by creating character array. General format to create string variable: Syntax: char variable name[size]; The data type of the string is always char, size can represents the maximum number ofcharacters are store into a string. Example: char na[20];Strlen( ): It is used to find the length of the string, length means how many characters will bestored in a given string variable. This function accepts one string variable as the passingvariable from the calling location. In the calling area we can store the return value into aninteger variable. Syntax:- int var = strlen(string var); Ex:- char na[20] = “abc”; int length ; length = strlen(na);Strcpy:- This is used to copy the string from one string variable to another string variable. Thisfunction can accept two string variables as the passing arguments or one is string variable,second one is string value. It can copy string value in the second variable in to first variable. Syntax:- strcpy(string var1,string var2); Ex:- strcpy(s1,s2); strcpy(s1,”abc”);Strcmp( ): This function performs compression operations between two strings and find outwhether two strings are same or different. It can accept two strings variables as the passingarguments. If two strings are same strcmp( ) returns zero to the calling location other wise it 47
  48. 48. Programming in ‘C’can returns numeric difference between the ascii values of the first non-matching pairs of thecharacter. Syntax:- int var = strcmp(string var1,string var2): ex:- strcmp(s1,s2);Strcat( ): This function performs concatenation (combining) operation between 2-strings. Itcan accept 2-string variables as the passing arguments. It can concatenate 2-strings in a givenstring variables, resultant string will be stored into string variable1. Syntax :- strcat(string var1, string var2); Ex:- strcat(s1,s2);Strrev( ): This function is used to reversing the string in a given string variable. It can acceptsingle string variable as the passing argument. It can reverse string in a given string variableand the resultant string will be stored into the same string variable. Syntax : strrev(string var); Ex:- strrev(s1):Strlwr( ): This function used to convert the string into lower case (small) letters. It can acceptstring variable as the passing argument .The resultant string can store into same variable. Syntax: strlwr(string var); Ex:- strlwr(s1);Strupr( ): This function used to convert the string into upper case (capital) letters. It can acceptsingle string variable as the passing argument. The resultant string will be stored into thesame variable. Syntax: strupr(string var); Ex:- strupr(s1); 48
  49. 49. Programming in ‘C’ FunctionsFunction: It is a set of statements or part of a program, which are executed repeatedly andrandomly in our program. Functions are also called as sub programs. The set of statementsare written for accomplish a particular task or solve a problem. These set of statements areidentified by an identifier called function name. When we need to execute those set ofstatements in our program, we can write the function name in the program. This procedure iscalled function calling. Functions are classified into two types: 1. Library functions or Predefined functions. 2. User defined functions.Library functions: Library functions are also called as predefined functions. Like keywords, task of thefunction is defined or written by the C-language developers. These function definition arewritten in library files. When we to done a particular task in our program simply we can callthose functions with the function names. These functions are use in any C-program. Examples: gets(), putchar(), printf(), scanf() etc……..User defined functions: User defined functions are own functions. These functions are written or developedby the programmer. These functions are developing with in the user programs, we can callthose functions with in the program, we can not call the user defined functions from anotherprogram. Programmer can define number of user defined functions with in one program, eachfunction having individual task. Each one will be separated by the function names. Examples: add(), subtraction(), etc………Advantages of the functions: 1. The complicated problem can be divided into number of smaller tasks and can be solved separately. 2. It is easy to understanding each sub program as it performs only a specified task. 3. We can test the program are sub programs easily. 4. More general functions can be kept in the library files for the later uses. 5. We can reduce the complexity of the program. 6. We can solve the complicated problems easily by using functions. 7. Reduce the length of the programs. 49
  50. 50. Programming in ‘C’Each function has the following working procedures: 1. Function declaration (or) Function prototype. 2. Function definition. 3. Passing arguments. 4. Return statements. 5. Function call.Function declaration (or) prototype: It can tells to compiler, name of the function, which type of values can taken as thepassing arguments from the calling location and which type of value can be return to thecalling location. Function declaration is made at the beginning of the main function in ourprogram. The general format for the declaration of the function: Return type function name(arguments list(optional)); Example: void addition(int x, int y);Function definition: Here the program can specify the task of the function. The task of the function iscalled as the definition of the function. The definition of the function can be written after thecompletion of the main function or at the time of the declaration. We can maintain equalprototype of the function at the time of declaration, at the time of the writing definition. Return type function name(arguments list(optional)) { --------- (Executable statements) } Example: void addition(int x, int y) { printf(“sum = %d”, x+y); }Passing arguments: Each function is design for executing a task in this way the function needs a somevalues for the execution of further steps in function. Some times those values are given to thefunction from the calling location, then those values are pass to the function as the passingarguments. 50
  51. 51. Programming in ‘C’Return statements: The return statement tells to compiler which type of value return by the function tothe calling location. The return type is specifying before the function name. The return typeof the functions is mention as void, scalar or derived type.Function call: After defining the function, we can call the function from main function or anotherused defined function. The calling of the function is nothing but the execution of the functioncode. Where you want to execute the code of the function in our program, just write thefunction name in that location. Function calling: addition(); When we declare the user defined functions in our program above steps should befollowing. User defined functions are classified into 4 types based on the prototype of thefunction. Those are: 1. Functions have No return value and No passing arguments. 2. Functions have No return value and Passing arguments. 3. Functions have Return value and No passing arguments. 4. Functions have Return value and Passing arguments.1. Functions have No return value and No passing arguments: In this type function doesn’t take any values as the passing arguments from the callinglocation. Function doesn’t return any value to the calling location. This type of functions,declaration of variables, and logic of the task and results of the task should be placed in thedefinition of the function. General format of this type is: void function name( ); Example: void addition( ) { Executable statements; } { -------------- addition( ); (calling environment) } 51
  52. 52. Programming in ‘C’ In the above format the data type void represents the function doesn’t return anyvalue. The empty parenthesis represents the function doesn’t require any values as thepassing arguments from the calling location.2. Functions have No return value and Passing arguments: In this type the function doesn’t return any value to the calling location but it can takesome values as the passing arguments from the calling location. The execution of the functionlogic is depends on another values, those values are require from the calling location. Thenthe values are sending to the function as the passing arguments. General format of this typeis: void function name( arguments list); example: void addition(int x,int y) { printf(“Sum = %d”,x+y); } { int a=5,b=10; addition (a,b); (calling environment) ---------------- } In the above type void represents, function doesn’t return any value to the callinglocation. Function requires two integer values as the passing arguments from the callinglocation.3. Functions have Return type and No passing arguments: In this type the function return one value to the calling location, the function doesn’ttake any values as the passing arguments from the calling location. The return value type isspecified in front of the function name. The return value type must be scalar or derived datatype. Then the function returns a value to the calling location with the help of keyword‘return’ this keyword is placed in the body of the function. When the compiler read thisreturn keyword the control goes to the calling location. General format of this type is: 52
  53. 53. Programming in ‘C’ data type funvtion name( ) { ----------- return variable; } Example: int addition( ); { int c; --------- return c; } { int c=addition( ); (calling environment) } In the above function the return value of the function is ‘int’ type. The functionreturns a ‘int’ value in the variable ‘c’. Specified return type of the function should be sameas the return value data type of the function. In the calling location, the return value will bestored into a variable. These types of functions are involved into an expression in the callinglocation.4. Functions have Return value and Passing values: In this type functions return one value to the calling location and the functionsrequired some values as the passing arguments. This type is the combination of 2nd and 3rdtype of the functions. General format of this type is: Data type function name( arguments list) { ---------- return variable; } Example: int addition(intx,int y) { return x+y; } { int c=addition(5,6); (calling environment) } 53
  54. 54. Programming in ‘C’ In the above type the function return an ‘int’ type value, the function requires two‘int’ values as the passing arguments from the calling location. The return value of thefunction is stored into ‘int’ variable c. These types of functions are involved into anexpression in the calling location. The following conditions must be satisfy when the function require values from thecalling location. 1. Numbers of arguments specified in the calling location is must be same as the number of variables declared in the function definition. 2. Data type’s of the variables in the calling location is must be same as the data types of the variables declared in the function definition.Parameter passing mechanism in functions: The arguments passing to the functions are classified into tow types, they are formalarguments and actual arguments. The variables declared in function definition are calledformal arguments. The variables given to the function in the calling location is called actualarguments. In functions, some times the function requires values in the variables as the passingarguments; some times it requires address of the variables as the passing arguments. Based onthese, C-language provides two types of mechanisms for passing arguments: 1. Call y value (or) passing arguments by values. 2. Call by references (or) passing arguments by references.1. Call by value (or) passing arguments by values. In this type the values in the variables as the passing arguments to the functiondefinition. Here we can write the names of the variables or values in function calling, thecompiler transfer the values in the variables to the function definition. When ever we modifythe values in formal arguments the actual arguments are not affected. Changes are made onlyon formal arguments because we can pass the values in the variable. 54
  55. 55. Programming in ‘C’General format of the call by value method: main( ) { -------- Function name( variable names); (calling location) ---------- } return type function name(formal variables declaration) { ------- ------- } Example: main() { int a=10,b=20; swap(a,b); printf(“%d%4d”,a,b); getch(); } void swap(int x,int y) { int c; c=x; x=y; y=c; } Observe the above function; it can get two integer values as the passing argumentsfrom the calling location. Those two values will be stored into the formal arguments of thefunction. The function definition can interchange the values in the formal arguments but thevalue in the actual arguments doesn’t change. Why because, formal arguments are localvariables to that function, the scope of the local variables is with in the declared function.Example program for call by value mechanism: void add(int x,int y) main() { int a,b,c=0; clrscr(); printf(“Enter 2 numbers:”); 55