Sie sind auf Seite 1von 65

Programming in C

Programming in C
Introduction C is a programming language. It was developed by Dennis Ritchie at AT&T bell laboratories in the early 1970s. C was an offspring of the Basic Combined Programming Language (BCPL) called B language. C language was designed from B language by adding some modifications to the B language. But C language compilers were not readily available for commercial use out side of the bell laboratories. So many programmers preferred C to older 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 C programming text is written by Brian Kernighan and Dennis Ritchie but this book not provides complete information about C. In 1983s American National Standards Institute (ANSI) is the organization forms a committee for development of C language. ANSI C committee releases standardized definition of C in 1990. International Standard Organization (ISO) is also involved soon for development of C, because most of the world uses c language. C is a general purpose, structured programming language. C combines elements of high level language with functionalism of assembly level languages (low level languages) so we 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.

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 tasks 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.

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 are called machine dependent languages. Later these assembly languages are replaced by high level languages. The first high level language is FORTRAN (FORmula TRANsulator). One FORTRAN instruction or statement can be executed in different machines unlike assembly language instruction. Then high level languages ate called machine independent languages.

Programming in C

Basic structure of a C-program:


Documentation section Linking section Definition section Global value declaration main() { Local variable declaration part Executable statements } Sub program section function1() { 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 we mention the name of the program and also write the comments for our program. The comment text can be bounded with astricks (*) and enclose with in back slash (/). By using these 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 the C-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 these constants 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

Programming in C Global Declaration Section: There are some variables that are used in more than one function. Such variable are called global variables and declared in the global declaration section that is outside of all the function. I int a,b;

Main function section: Every C program must have one main() function. This section contains two parts, declaration part and execution part. The declaration part declares all the variables 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 program execution begins at the opening brace and ends at the closing brace. All statements in the declaration and executable parts end with a semicolon. main() Subprogram Section: The subprogram section contains all the user-defined functions that are called by the main function. User defined function are generally declare, after, end of the main function. A Function is a subroutine that may include one or more statements designed to perform a specific task

Example 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); }

Programming in C

Compiling program:
Compiling of c- program is nothing, to generate binary code file for our program to execute 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 help of 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 Cprograms in to file. Source program: The program that is entered into the file is known as the source program.

Start

Editor Compiler
Yes
Errors?

Source program Name.C

No

Object program Name.obj

Linker
Library and other obj files Exicutable code Name.exe

Execute

No

Result ok?

Yes

Start 6

Programming in C We have to follow several steps to write, compile and a program in C-programming language. 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 CProgram 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

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 managed by a single integrated application is known as Integrated Development Environment (IDE). The IDEs are differing from form one operating system to n other. Some windows based IDEs 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 in high-level languages. Interpreters are analyzed and execution of statements in a program is same time. The method usually allows programs to be more easily debugging. Basic and java programming languages are use these interpreters for analyze and execution 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 tokens for C language character set is the combination of alphabet or character, digit, special characters and white spaces. 1. Letters 2. Digits 3. Special characters 4. White spaces (A.Z and az) (9) (. , ; : ? / < >.) Blank, Horizontal tab, Carriage return, new line, Form feeds 52 10 29 5 96

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 TOKENS

Keywords symbols Float Int While

Identifiers main a cost

Constants 50.00 -21.43

Strings computer a

Operators +-*/

Special { < [ ? .

1. KEYWORDS: Every C word is classified as either a keyword or an identifier. All keywords have fixed meaning and these meanings cannot be changed. Keywords serve as basic building blocks for program statements. All keywords must be written in lower case. auto break case char const continue default do double else enum exturn float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void vollatile while

2. IDENTIFIERS: Identifiers refer to the names of variables, function and arrays. These are user-defined names and consist of a sequence of letters and digits with as a first character. Identifier should not be a keyword.

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 a program.
Constants

Numbered constants

Character constants

Integer

Float

Single

String

Black slash

Decimal Octal Hexadecimal

10

Programming in C 1. Numeric constants: These have numeric value having combination of sequence of digits i.e from 0-9 as alone digits or combination of 0-9 ,with or without decimal Point having positive or negative sighn. These are further subdivided into two categories as: a) Integer Numeric constant b) Float Numeric constant a) Integer numeric constant: Integer numeric constant have integer data combination of 0-9 without any decimal point 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 use octal and hexadecimal numbers in

Note: We rarely programming. b) Float Numeric constant

Some constants which have a decimal point or a precision value with in having any positive or negative sign is called floating point constant . Float constants has two parts. One is mantissa and the other is exponent pat. These two parts in a real number are represented as: Mantissa E exponent

11

Programming in C The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer umber with an optional + or sign. The letter E separating the mantissa and the exponent can be written in either lowercase or uppercase. Example: 2). Character constant: a) Single character constant: It contains a single character enclosed within a pair of single quote marks. Example: b) String character constant: String constant is a sequence of characters enclosed in double quotes. The characters may be letters, umbers special characters and blank space. Example: hallow 2007 x 9+22+65 Hellow 2007 X 9+22+17 3.5x102 can be written as 3.5E2

c) Backslash characters: C supports some backslash character constants that are used in output functions. These character combinations are known as escape sequence. Constant \a \b \n \t \0 Meaning Audible alert (bell) Back space New line Horizontal Null

4. OPERATORS: An operator is a symbol that tells the computer to perform certain mathematical manipulations. Types of Operators: 1. Arithmetic Assignment 5. Increment and decrement 6. Conditional 7. Bitwise 8. Special 2. Relational 3. Logical 4.

12

Programming in C 1. Arithmetic Operators: Arithmetic operators are used for arithmetic operations like Addition, Subtraction, Multiplication, Division etc. If all operands are integers, the result is an integer. If an operand is a floating point or double precision value, the result is a double. Operator + * / % Meaning Addition Subtraction Multiplication Division Modulo Division (Remainder after division) 2. Relational Operators: We often compare two quantities, and depending on their relation, take certain decisions. These comparisions can be done with the help of relational operators. Containing a relation operator is termed as a relational expression is either 1(true) or (false). Operator < <= > >= == != Operator && || ! Logical Table:
A T T F F B T F T F A AND B T F F F A OR B T T T F NOT A F F T T

Meaning Is less than Is less than or equal to Is greater than Is greater than or equal to Is equal to Is not equal to

3.LogicalOperators:Anexpression,which combines two or more relational expression, is termed as a logical expression.

Meaning AND OR NOT

4. Assignment Operator (=): Assignment operators are used to assign the result of an expression to a variable. Syntax: variable=expression

Where, expression is whose value is to be assigned to the variable. Examples: a=10 b=20 sum= a+b

13

Programming in C 5. Increment and decrement Operators: The operators ++ adds 1 to the operand and the operator subtracts 1 from operand. We use the increment and decrement statements are use in 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; 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; In value of y would be 5 and m would be 6. 6. Conditional Operator: A ternary operator pair ?: is available in C to construct conditional expressions of the form. Var1=condition? exp2: exp3; The operator ?: works as fallows condition is evaluated first. If it is nonzero (true) then the expression exp2 is evaluated and becomes the value of the var1. If condition is false, exp3 is evaluated and its value becomes to the value of the var1. Y=m++; Y=++m;

Example:

a=10; b=15; X=(a>b)?a:b;

if(a>b) x=a; else x=b;

7.Bitwise Operators: C has a distinction of supporting special operators for manipulation of data at bit level.These operators are used for testing the bits, or shifting them right or left. These operators are not applicable to the float or double data types.

Operator & | ^ << >> ~

Meaning Bitwise AND Bitwise OR Bitwise Exclusive OR Bitwise Left Bitwise Right Bitwise NOT

14

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 0

5. 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

Programming in C Hence, the least significant bit will be discarded and the most significant bit will come out to be 0.

6. Left Shift: It has the purpose to transfer the bits of data to the left side. It is a binary operator i.e. 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 1 0 1 0 0

Hence, the most significant bit will be discarded and the least significant bit will come out to be 0.

8. Special Operator: These are used for special purpose in C language. These operations are used in pointers, structures and unions etc. 1. Unary operator 2. Comma operator 3. Sizeof() Operator 4. Type operator 5. Pointer operator 6. Member selection operator

1. 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 as special operator. Example: x=-3; y=++x-7*3

2. Comma operator: The comma operator can be used to link the related expression together. A comma linked list of expression is evaluated left to right and the values of right most expression is the 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

Programming in C 3. Size of ()operator: The sizeof() is a compile time operator and, when used with an operand, it returns the number of byte the operand occupies. The operand may be a variable, a constant or a data type 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 called convert operator. This operator converts float type data into integer form and vice-versa. It is used for casting a value and process to convert from 1 form to another is called casting. Syntax: Example: (Type)v or e; 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 the type operator, we can get the float value as C=(float) a/b; Now c value is 3.333333 5. Pointer operator: There are two types of pointer operators used in C language. These are & and *. where v is variable e is an expression

6. Member selection operator: There operators are used in structure and union. These are used to create a relation between owner and member within a structure or union data. These are . and .

17

Programming in C DATA TYPES: C language is rich in its data types. C language supports the following data types.

DATA TYPES

Scalar Char Integer Float Double

Derived array or string structure union

User Defined enum

Void

Pointer

typedef

1. Scalar/ standard/ primary/ fundamental data types: A scalar data type is used for representing a single value only. It is only called simple or fundamental data type. Size and range of basic data types: Data type char int float double Size 1 byte 2 bytes 4 bytes 8 bytes Range of value -128 to 127 -32,768 to 32,767 3.4e-38 to 3.4+38 1.7e-308 to 1.7e+308

2. Derived data types: Derived data types are derived from the scalar data type by adding some additional relationship with the various elements of the primary or scalar data types. Note that derived data type may be used for representing a single value or multiple values. These are further sub 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) data type 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

Programming in C (b). Structure: A Structure is nothing but a collection of heterogeneous (different) datatypes of 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 secondary datatype. 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 declared of 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 an identifier, which is used for representation of existing data types. a) enum: Another user defined data type is enumerated data type provided by ANSI standard. Syntax: enum identified {value1, value2..} variable;

The identifier is a user- defined enumerated data type, which can be used to declare variables that can have one of the values enclosed within the braces known as enumeration constant. Example: enum day{Monday, Tuesday, Wednesday,..} d;

19

Programming in C b). type def: Supports a feature know type definition that allows user to define an identifier that would represent an exiting data type. The user-defined data type identifier can later to declare variable. Syntax: typedef data_type identifier; Where type represents the data type of the identifier refers to the new name giving to 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 can create 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 sub programs. These are used when the function sub-program returns nothing to the calling location. 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 statements

Formatted I/O statements

getchar(); gets(); getch(); getche();

putchar(); puts();

scanf();

printf();

1. Formatted I/O statements: All input/output operations are carried out through function calls such as printf and scanf there exist several functions that have more or less become standard for input and output operations in C. There functions are collection known as the standard i/o library.

20

Programming in C #include<stdio.h> The instruction <stdio.h> tells the compiler to search for a file stdio.h and place its contents at this point in the program. The content of the header file become part of the source code when it is compiled.

Conversion character %d %f %c %s %lf a). scanf():

Meaning Integer Float Character String Double

The scanf() function is an input function. It used to read the mixed type of data from the keyboard. You can read integer, float and character data by using its control codes or format 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() fi\unction for printing captions and numerical results the general form of printf 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

Programming in C 2. Unformatted I/O statements: These functions are used to read or print the data in unformatted way. These are also called as character I/O functions. The following are the character I/O functions. Input functions getchar(); getche(); getch(); gets(); a). getchar(): This is an input function. It is used for reading a single character from the keyboard. It is buffered function. Bu8ffered functions get the input from the keyboard and store it in the memory temporarily until you press the enter key. After you pressed the enter key then input move to a relevant variable. Syntax: Example: b). gets(): This is an input function. It is used for read a string from the keyboard. It is a buffered function it will read a string, when you type the string from the keyboard and press the enter key from the keyboard. It will mark null character (\0) in the memory at the end of the string, when you press the enter key. Syntax: Example: c) getch(): This is also an input function. This is used to read a single character from the keyboard 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 does not visible on the screen. Syntax: d). getche(): All are same as getch() function except that when you type the character data from the keyboard it will be visible on the screen. Syntax: e). putchar(): v=getche(); v=getch(); gets(v); char s[20]; gets(s); v=getchar(); char a; a=getchar(); output functions putchar(); putc()

22

Programming in C This function is an output function. It is used to display a single character on the screen. Syntax: Example: 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: Example: puts(v); char a[10]; or puts(text); putchar(v); char a; getchar(a);

gets(a);

Control statements:
Normally C-compiler executes all the statements in the program sequentially in top down process. In C-language some times we have to control the execution of program, Some times the program executes some group of statements in the program, some other time another group of statements in the program comes for execution. When ever the program needs this type of situation, place some condition statements in the program. Those conditions are made with the help of relational operators. The condition will execute and returns the value 1 (TRUE) or 0 (FALSE) to specified location, where the condition place in the 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 controls on the execution of program. The general syntax of the if is: if(condition) { Executable Statements; }

23

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 if statement. If the given condition is false, it will return 0 to if statement. We have several form of 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 come for execution other wise normal statements will execute. The general syntax of the simple if is: --------------if(condition) { Stament1; } In the above syntax the condition following by the keyword if . The executable statements 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 given statements (statement1) in the if part will come for execution other statement1 absence in the execution, the compiles goes to execution of normal statements in the program.
Texst exp

No

Yes

Statements

Example program on simple if condition: #include<stdio.h> main() { int num; clrscr(); 24

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 extension of the simple if. The general syntax of the if else conditional statement is: --------------if(condition) { Stament1; } 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 comes for execution. If the given condition is false, then else part statements (Statement2) will comes for execution. When ever the first if statement succeeds, the second must fail, and vice versa. In this if else conditional statement either if part statements or else part statements only comes for execution another one absence in the execution time. When ever the C-program having two
Texst exp

No

Yes

Statement1

Statement2

25

Programming in C options for execution we use this is else statement. If the if part or else part having single statement, 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 levels else if ladder type is used. In this else if type, the main if having condition, if the if part condition is fail, the else part having another condition, if the else if part condition fail then else part having another condition then the conditions are arranger in the ladder or chain format. The else if conditional statement having common else for the all the else if statements, if all conditions in the else if are fail then else part will executes, this else part is optional. The general syntax of the else if conditional statement is:

26

Programming in C

--------------if(condition1) { Stament1; } else if(condition2) { Statement2; }


Yes
Texst exp

No

Statement1

Texst exp

No

Yes

Statement2

Statement3

else { Statements3; } ----------------

This else part is optional

The above syntax represents the else if conditional statement arrangement. The condition1 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 next else if part condition, if it is true then the compiler will executes statements2 in the else if part, if it will also false then compiler check the next condition. In this way the compiler will check all the sequence of else if conditions in the program, all the conditions are false then default else part statements (Statements3) will comes for execution.

Example program for else if statement: #include<stdio.h> main() { int n1,n2,n3;

27

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 the conditions, use this nested if conditional statement. In this nested if conditional statement all the conditions or some conditions are arrange in nested form. May be the main if or else part body having another if of if else statement. The general syntax of the nested if is: ---------------if(condition1) { if(condition1) { Statement1;

28

Programming in C

} else { Statement2; } } --------------The syntax represents the nested if conditional statement. The main if body having another if condition, in this we place number of if conditions as condition with in the condition. If all the given conditions in the if part will true then only the statement1 will come for execution, other wise it will execute the normal program. If the main if is false then only the else part will come for execution, if inner most condition of the main if is false, then the compiler goes to after the else part statements execution. This else part is optional

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

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 or relations, 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)) { Statement1; } } if((a>b)||(a>c)) { Statement2;

The above example shows the compound relation of the condition. The a>b and a>c are 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 many statements or many choices. In this switch each choice can be represented with case of the switch statement. The switch, case, default these three key words are arranged correctly, then if will form a control statement.

30

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 integer expression 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 it is having an other case is called default case. When ever the value in the variable is equals to the constant value of the specified case in the switch is executed. The value in the variable is not match with the constant values of all the cases in the switch, and then the default case is executed. The value in the variable is equal to the constant in the case 1, and then statement 1 is executed, if the value is not mach with the value in the case 1, then the compile check with next case constant. In this way the compiler will check with each and every constant value of the cases in the switch.

Example program for switch conditional statement: #include<stdio.h> main() {

31

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. In will repeatedly execute some sequence of steps or some portion of the program specified number of times. The loop execution is controlled with the help of the loop control instruction or loop condition. The statements in the loop will execute until the given condition 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

Programming in C The looping statements are divided in to two types based on condition checking location. They are entry level condition checking, exit level condition checking. The for and while looping statements are comes under entry level condition checking. The do while looping 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 while is 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

Test exp Yes

No

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 while loop. In the while loop first initialize the starting value to the variable for counting purpose of the loop iterations. Iteration is the process of loop execution. The while is a keyword followed by the test condition. The body of the loop and the increment or decrement statements are enclosed by the opening and closing curling braces ({}). The test condition is true then the body of the loop will come for execution and perform increment or decrement operations. After performing increment or decrement operations the test condition is once 33

Programming in C again evaluated, if it is true the body of the loop is again executed. The process of repeated execution of the body continues until the condition false the control is transfer to out of the loop. 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(%d\t,i); i=i+1; } getch(); } The above program is used to display the numbers from 1 to given number. The i values is initializes with one, and check the while loop condition and executes the body of the loop. Then perform increment operation. The body of the loop executes continually until I value greater then value in the variable num.

2. For looping statement: The for loop is another Entry controlled looping statement. For is a keyword, by using this we can build a looping statement.

34

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 while looping statement, the initialization, conditions and increment and decrement statements are placed in different locations. In for looping statement this initialization, condition and increment and decrement statements are place in one location these are separated by semicolon (;). Those three statements are enclosed with parentheses. The initialization part is used for initialize counter variable for loop execution. The body of the loop will execute until the given condition is false. The body of the loop is enclosed with closing and opening curling braces ({ }), if the body of the loop has single statement need not to write braces. But it 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 of initialization statement the control will follow up the next condition checking statement in for loop. If the given condition is true, then the body of the loop will come for execution. Next the control will transfer to increment or decrement statement and execute the step, then the control goes to condition checking, if the condition is true, again the body of loop will execute 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

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 the first 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 time execution of loop.

3. Do while looping statement: The do while is the exit controlled looping statement. The while loop construct as the test condition is made at the beginning of the loop and also condition will comes for execution beginning of the loop. There fore the body of the loop may not executes, all the conditions of while loop is not satisfied at the entry first time. Some times it might be necessary to execute the body of the loop before the test is performed. In such a situation can be 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 test condition will be executed before executes the body of the loop. In do while fist the body of the loop will executes, at the end of the loop test condition is executed. This means in do while the body of the loop executes at least once, if the condition is fail. Remaining initialization and increment decrement statements are located in same location in while and do while loops.

36

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(%d\t,i); i=i+1; } while(i<=num); getch(); } In the above program the initialization is made at the beginning of the loop, next the body of the loop is executed. After the execution of the increment statement of the i, the test condition of the while is executes.

Difference between while and do-while loop: While loop Do-while loop

1. While loop can also called as an entry 1. Do-while loop can also be called as an exit controlled loop. controlled loop.

2. In the While loop the condition is placed at 2. In the Do-While loop the condition is the 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, after the initialization section, the condition will executing the initialization section, the body be tested if it is true, the body of the loop is of the loop will be executed and then the executed. condition will be tested for the continuation of the next iteration.

37

Programming in C 4. In the case of While loop, if the condition 4. In the case of Do-While loop, the body of is found to be false for the first time, the will be executed at least once without body will never be executed and the loop will depending on the vale of the condition. be 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-While while 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: Variable Initialization; while( test condition ) { Body of the loop; Increment or decrement operations; } 7. The general syntax of the Do-While is: Initialization; do { Body of the loop; Increment or decrement operations; }while(condition);

Nested loops: The nested loops are used where the program needs loop with in the loop. Which procedure used for nesting of if, that can be used for nesting loops. The nesting loops are made by using while, do-while and for looping statements. Writing nested loops in while, for is easier to compare do-while. The general form of the nested loops is:
Initialization; while( test condition ) { Initialization; while( test condition ) { Body of the loop; Increment or decrement operations; } Body of the loop; Increment or decrement operations; }

for(intilization;condition;increment or decrimrnt) { for(intilization;condition;increment or decrimrnt) { Body of the loop; } Body of the loop; } 38

Programming in C Working of nested loops: First the outer loop initialization statement is executed, after test condition statement is executed if it is true, then the body of the loop is executed. The outer loop body having another looping statement, we can call it is an inner loop. Then the inner loop initialization statement is executed, next the inner loop test condition will be processed, if it is true then the inner loop body is executed. Next increment process is done. After that the control goes for test condition, if it is true again the body of the loop is executed this process is continue until the inner loop condition become false. When ever inner loop test condition is false the loop will be terminated control will execute remaining statements in the out loop. After that the control goes to increment or decrement operation, next the control goes to check the condition of the loop if again it is true, again the inner loop is executed. This process is done until the outer loop condition becomes false.

Unconditional statements: In the conditional statements the control will go to specified location when ever the given condition either TRUE (1) or FALSE. (0). In the unconditional statements, when ever the compiler reads the unconditional statement the control will goes to specified location with out testing any condition. Here the control will jumps to specified location automatically so this statements also called jumping statements. C-language provides three jumping statements they are: 1. goto. 2. break. 3. continue. 1. goto: The goto unconditional statement is used to transfer the control from one location to another location in the program. Here goto is keyword in C-language. This statement is used with the help of crating labels in the program; goto keyword is followed by the specified label in the program. Syntax: Example: goto <label name>; goto a;

Example program for goto statement: #include<stdio.h> 39

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 or program unconditionally. When ever use the break statement in program, the control will never executes the statements available, after the break statement. When the compiler reads the break statement the compiler terminates from the execution of the program. Syntax: Example: break; 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

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 stop the normal execution of for loop at that specified time.

3. continue: The continue is a keyword in C-language. This continue statement is mainly used in looping statements. Some times the program needs to transfer the control to the starting of the loop. When ever the control reads the continue statement in the loops, the control never executes the statements after the continue in the loop. The control will transfer to the beginning of the loop. Syntax: Example: continue; 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

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 the user gives ve number to the variable num the compile never add that value to the previous some. This process is done by using continue statement with in for loop. The compiler decides the given number is ve, automatically the control will goes to beginning of the loop.

42

Programming in C

Arrays
When ever the program need to tack group of similar data elements, it is highly impossible to create individual variables, and also accessing values, C-language provide a feature 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 special number 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 a variable is called single dimensional array. Declaration of array: Array variable can be create like normal variable, but only difference is normal variable 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 array variable. Variable name represents the identifier of an array; size represents how many elements array can accept. Each and every value in the array can be accessed with the help of an integer or number is called index of an array, it can be place with in the brackets after the array name. int rollno[10]; It represents the ten students roll numbers. Variable rollno can share all the ten roll numbers of the ten students. rollno[0] is the roll number of the single student, rollno[1] is the roll number on another student etc the array indexing starts with 0 and ends with n-1. 0 is the 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

Programming in C

Address Elements Locations or subscripts

2000

2002

2004

2006

2008

50
a[0]

34
a[1]

65
a[2]

5
a[3]

12
a[4]

Initializing values into an array: Values initialization process is done like initialization of values to the normal variable. The values are assigned to each and every location, with the help of index value of an 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 to read 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-language minimize this process with the help of loops. The below example represents read values into an 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 variable name. But we can distinguish each and every variable with the logical address of the array variable. Suppose you want to access 2nd logical location value in the array we can represent like this a[2]. We can access group of values at a time with the help of loops.

44

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 array variable name having two subscripts such a variable is called two dimensional arrays. When ever 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 using this 2d array we can organize or store data in the form of tables. It is similar to the matrix form 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. The variable 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, how many 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 array variable m1 can accept integer values only. In single dimensional array we can access the array values, by using single index value. In 2d array, values can be accessed with the help of two indexing values. First one represents row index second one represents column index value. For example m1[0][1] represents the value in the 0th row 1 st column. Initializing values to 2d array: Initializing values to 2d array with the help of indexing values, this indexing values are 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

Programming in C Initial storage of 2d array: The array variable can be stored like this: int a[2][2];

Address Elements Locations or subscripts Address Elements Locations or subscripts

2000

2002

50
a[0][0]

34
a[0][1]

1st row

2004

2006

50
a[1][0]

34
a[1][1]

2nd row

1st column

2nd column

Reading values into 2d arrays: When ever we need to read or get values from the output screen. We can get those values with the help of nested looping statements. The general format to read values to 2d arrays: for(i=0;i<row size;i++) { for(j=1;j<size of column;j++) { scanf( ); } }

46

Programming in C

Strings
String: In arrays we can store group of numerical values, string can also store group of values those values comes under character type. String is a collection of character values, when we declare the array variable under char data type the variable is called as string variable. Normal char variable can accept only single character value, it cant accept group of character like 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 of characters are store into a string. Example: Strlen( ): It is used to find the length of the string, length means how many characters will be stored in a given string variable. This function accepts one string variable as the passing variable from the calling location. In the calling area we can store the return value into an integer 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. This function 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 out whether two strings are same or different. It can accept two strings variables as the passing arguments. If two strings are same strcmp( ) returns zero to the calling location other wise it char na[20];

47

Programming in C can returns numeric difference between the ascii values of the first non-matching pairs of the character. Syntax:int var = strcmp(string var1,string var2): ex:strcmp(s1,s2); Strcat( ): This function performs concatenation (combining) operation between 2-strings. It can accept 2-string variables as the passing arguments. It can concatenate 2-strings in a given string 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 accept single string variable as the passing argument. It can reverse string in a given string variable and 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 accept string 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 accept single string variable as the passing argument. The resultant string will be stored into the same variable. Syntax: strupr(string var); Ex:strupr(s1);

48

Programming in C

Functions
Function: It is a set of statements or part of a program, which are executed repeatedly and randomly in our program. Functions are also called as sub programs. The set of statements are written for accomplish a particular task or solve a problem. These set of statements are identified by an identifier called function name. When we need to execute those set of statements in our program, we can write the function name in the program. This procedure is called 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 the function is defined or written by the C-language developers. These function definition are written in library files. When we to done a particular task in our program simply we can call those 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 developed by the programmer. These functions are developing with in the user programs, we can call those functions with in the program, we can not call the user defined functions from another program. Programmer can define number of user defined functions with in one program, each function 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

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 the passing arguments from the calling location and which type of value can be return to the calling location. Function declaration is made at the beginning of the main function in our program. The general format for the declaration of the function: Return type function name(arguments list(optional)); Example: Function definition: Here the program can specify the task of the function. The task of the function is called as the definition of the function. The definition of the function can be written after the completion of the main function or at the time of the declaration. We can maintain equal prototype of the function at the time of declaration, at the time of the writing definition. Return type function name(arguments list(optional)) { --------- (Executable statements) } void addition(int x, int y) { printf(sum = %d, x+y); } void addition(int x, int y);

Example:

Passing arguments: Each function is design for executing a task in this way the function needs a some values for the execution of further steps in function. Some times those values are given to the function from the calling location, then those values are pass to the function as the passing arguments.

50

Programming in C Return statements: The return statement tells to compiler which type of value return by the function to the calling location. The return type is specifying before the function name. The return type of 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 another used defined function. The calling of the function is nothing but the execution of the function code. Where you want to execute the code of the function in our program, just write the function name in that location. Function calling: addition();

When we declare the user defined functions in our program above steps should be following. User defined functions are classified into 4 types based on the prototype of the function. 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 doesnt take any values as the passing arguments from the calling location. Function doesnt 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 the definition of the function. General format of this type is: void function name( ); Example: void addition( ) { Executable statements; } { -------------addition( ); (calling environment) }

51

Programming in C In the above format the data type void represents the function doesnt return any value. The empty parenthesis represents the function doesnt require any values as the passing arguments from the calling location.

2. Functions have No return value and Passing arguments: In this type the function doesnt return any value to the calling location but it can take some values as the passing arguments from the calling location. The execution of the function logic is depends on another values, those values are require from the calling location. Then the values are sending to the function as the passing arguments. General format of this type is: 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 doesnt return any value to the calling location. Function requires two integer values as the passing arguments from the calling location.

3. Functions have Return type and No passing arguments: In this type the function return one value to the calling location, the function doesnt take any values as the passing arguments from the calling location. The return value type is specified in front of the function name. The return value type must be scalar or derived data type. 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 this return keyword the control goes to the calling location. General format of this type is:

52

Programming in C data type funvtion name( ) { ----------return variable; } int addition( ); { int c; --------return c; } { int c=addition( ); }

Example:

(calling environment)

In the above function the return value of the function is int type. The function returns a int value in the variable c. Specified return type of the function should be same as the return value data type of the function. In the calling location, the return value will be stored into a variable. These types of functions are involved into an expression in the calling location.

4. Functions have Return value and Passing values: In this type functions return one value to the calling location and the functions required some values as the passing arguments. This type is the combination of 2nd and 3rd type of the functions. General format of this type is: Data type function name( arguments list) { ---------return variable; } int addition(intx,int y) { return x+y; } { int c=addition(5,6); (calling environment) }

Example:

53

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 the function is stored into int variable c. These types of functions are involved into an expression in the calling location. The following conditions must be satisfy when the function require values from the calling 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 types 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 formal arguments and actual arguments. The variables declared in function definition are called formal arguments. The variables given to the function in the calling location is called actual arguments. In functions, some times the function requires values in the variables as the passing arguments; some times it requires address of the variables as the passing arguments. Based on these, 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 function definition. Here we can write the names of the variables or values in function calling, the compiler transfer the values in the variables to the function definition. When ever we modify the values in formal arguments the actual arguments are not affected. Changes are made only on formal arguments because we can pass the values in the variable.

54

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 arguments from the calling location. Those two values will be stored into the formal arguments of the function. The function definition can interchange the values in the formal arguments but the value in the actual arguments doesnt change. Why because, formal arguments are local variables 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

Programming in C scanf(%d%d,&a,&b); add(a,b,c); printf(\nSum of %d, %d is %d,a,b,c); getch(); } void add(int x,int y,int z) { z=x+y; } In the above program add function can perform addition operation on two numbers. This function can take three integer numbers as the passing arguments from the calling location. Two values are used for addition operation, third variable is for storing result. In the function definition adds value in the x with value in the y and store result in to variable z, but the value in the actual variable doesnt change. This is the main disadvantage in call by value mechanism.

Call by reference (or) passing arguments by reference: In call by reference mechanism we can pass address of the variables as the passing arguments to the function definition. In this type we can write address of the variables in the calling location (when ever & symbol place before the variable it can represents the address of the variable), the control sends the address of the variables to the function definition. The function definition can get that variable address, by declaring pointer variables. In this type function can perform different operations on the formal arguments the effect will be place on the actual arguments. General format of the call by reference method; main( ) { -------Function name(address of the varables); (calling location) ---------} return type function name(pointer variables) { ------------}

56

Programming in C Example: main() { int a=10,b=20; swap(&a,&b); printf(%d%4d,a,b); getch(); } void swap(int *x,int *y) { int t; t=*x; *x=*y; *y=t; } In the above function the formal arguments are declared as the pointer variables why because the function calling can sends the address of the variables. The pointer variable can store the address of another variable. In the above example function can perform swapping operation on the passing arguments. The swapping operation can perform on the formal arguments; when ever the function can complete their task the values in the actual arguments are swapped. Example program for call by reference mechanism: void add(int *x,int *y,int *z); main() { int a,b,c; clrscr(); printf(Enter 2 numbers:); scanf(%d%d,&a,&b); add(&a,&b,&c); printf(\nSum of %d, %d is %d,a,b,c); getch(); } void add(int *x,int *y,int *z) { *z=*x+*y; } In the above example function definition can get address of the three variables as the passing arguments from the calling location, those address are store the function by creating 57

Programming in C pointer variables in the function definition. We can print the resultant value in the main function with out returning any value, because function can perform addition operation on the address of the variables.

Passing array variable to the function: Functions are accepts array of values as the passing arguments to the function. When ever the function definition requires group of values as the passing arguments, it is difficult to pass each and every variable as the passing arguments. C-language minimizes this problem with a mechanism, passing array of values to the function definition. In this mechanism, in the calling environments we can mention array name, in the function definition we can declare same type of array variable. When we mention the name of the array in the calling location, the compiler gets the starting address location of an array. Send the address to the function definition. Compiler copies the values in the actual array to formal array in the function definition. In the function definition we can make any modifications on values in formal array, the effect will be placed on values in the actual array. Why because we can send address of the actual array to the function. We can the reference of the array. Syntax: Example: Return type function name(data type arrayname[ ]..); void read(int a[],int n) { int i; for(i=0;i<n;i++) scanf(%d,&a[i]); } main() { int x[100],s=5; -------read(x,s); -------}

58

Programming in C Recursive function calling: Recursive function calling means function calls it self. In this type the function calling is available with in the definition of the function. A statement with in the body of a function calls the same function. In this type function calling process is done infinite times, we can made this type of function calling statement in definition with in the condition. When ever the condition is fails the function calling it self is stopped by the compiler. Let us now see a simple example of recursion. Suppose we want to calculate the factorial value of an integer. As we know, the factorial of a number is the product of all the integers between 1 and that number. For example, 4! is 4 * 3 * 2 * 1. this can also be represented as 4! = 4 * 3!. Based on this process, we can made functions in recursion type. Definition of the function: int factorial(int n) { if(n = = 1) return 1; else return n * factorial(n-1); } The above function definition represents the recursive function calling. This function is used for find the factorial of a given value. From the calling location, we can send an integer value, that value will be store into variable n. Function definition can perform checking operation on the value in n, if the value in n is equal to 1 it can returns value 1 to the calling location, if the value not equals to 1, control goes to else part. In the else part perform multiplication between value in n and value return by the same function with value n-1 and store those values in the buffer. This process is done until the vale in n reaches to 1. When, value in n reaches to 1, control stops the recursion process, and perform mathematical operation on the values stored in the buffer. In this way, the function calling is made like this, if the value in the n is 4, return 4 * factorial(4-1); return 3 * factorial(3-1); return 2 * factorial(2-1) return 1. After completion of recursion process the resultant value is calculated by the compiler like this(4 * (3 * (2 * (1))). The total value return toe the main calling of the function.

59

Programming in C Example: #include<stdio.h> int factorial(int n); main() { int n,fact; clrscr(); printf(Enter number:); scanf(%d,&n); fact=factorial(n); printf(\nFactorial of %d is %d,n,fact); getch(); } int factorial(int n) { if(n = = 1) return 1; else return n * factorial(n-1); } Function calling from another function: In this type, functions have individual tasks, but some functions execution is depend on the execution of another function, then in this situation calling of one function from the definition of another function. For example, in student database application we want to print a specified student details based on the student roll number. Then we can write a display function, before displaying the student details, program need to perform searching for specified student. In this type of problems, the search function calling is made in the definition of the display function. General format of this type: Function1(.) { -----} Function2(.) { ------Function1() }

60

Programming in C

Structures
C-language provides one feature is Arrays; these are used for representing a set of values which is having similar data type with a single name and single location. C-language provides another feature for grouping the elements called Structure; structure is collection of dissimilar (different data types of) data elements. All the elements in the structure represents single object (any thing in the living environment). Elements in structure are also called as structure members. All the members of the structure are referring with a single name is called structure name. Structure name is the identification symbol for the structure members. When ever the program deals with different entities, identification of each and every variable is difficult, by using structures we can minimize this problem creating an individual structure for each entity. Declaration of structures: The declaration of structure is accomplished like the declaration of static and array variables. C-language provides one keyword for creating structures, that keyword is struct. struct structure name { Datatype var1,.; Datatype var2; }structure object(var); In the above syntax, structure name followed by the keyword struct. This keyword struct tell to compiler, it a structure for the specified structure name. After specifying the structure name declare the structure members. The structure members are enclosed with a opening and closing carling braces. This can represents, those set of elements are the structure members. You want to declare the structure variable or object, after putting the closing braces, those variables are global variables, we can use this global objects any where in the program. The declaration of global variables is optional, after declaration of global variable place semicolon. This semicolon tell to compile structure declaration is completed. struct date { int dd,mm,yyyy; }d; The above example shows the declaration of structure for date. In C-language we dont have any data type for representing dates. Creating a structure for date is more use full for our program, when we deal with date. In the above example variabled is the global Example: Syntax:

61

Programming in C variable for the structure date. Object d containing three integer variables dd,mm and yyyy. Notes for the declaration of structures: 1. The closing brace in the structure type declaration must be followed by semicolon. 2. A structure type declaration does not tell to compiler to reserve any space in memory. All a structure declaration does is, it defining a template of the structure members. 3. Usually structure type declaration appears at the top of the source code file, before any variable or functions are defined. Declaration of structure variables or objects: When we declare the structure, the compiler does not allot any memory location to the structure members. When we declare the variable for the structure, then only the compiler allot memory locations for each and every element in the structure. Before the declaration of structure variable, structure is a template. When we declare structure variable, life cycle of the structure will start. Which are the rules used for the declaration of static variables those rules applicable to structure variables declaration. General form for declaration of structure variable: struct structure name variable name,; The process of declaration of structure variables is done like the declaration of static variables. In the declaration time the structure name is fallowed by keyword struct, after that give a variable name. Example: struct date d1;

In the above example d1 is the object of the structure date. After the declaration of structure variable the compiler will allot memory location for the members of the structure. Declaration of array of structure variables: When we need to declare structure variables as more than one, we need to declare the structure objects as array. Like scalar variables, we can combine the group of structure objects with a single name that is called array of structure variables. We can refer these structure objects individually, with the help of array indexing value. General format to declare array of structure variables are: struct structure name object name[size];

62

Programming in C In the above syntax size represents, how many objects you need to collect, that is the maximum limit in this program. Example: struct date s[100];

In the above example we can declare array of date objects for 100 dates. We can store hundred date values in the structure array. Each indexing value represents single date value. Functions and structures: Some times we need to pass number of variables to functions; in that situation we can mention each and every variable as argument. Suppose we need to sent student data to the function, it is impossible to send all the elements individually. C-language minimizes this problem with the help of structures. This type of situations, you can declare a structure for that group of variables, then mention the structure object as the passing argument to the function. In function definition we get the passed argument with the help of, declaring an object for same type of structure. In calling environment: Function name(structure object); In the function definition: Return type function name(struct structure name object); In the same manner we can return structure object from function definition to calling location. Here we can use, which mechanism used for returning scalar variables. We can return structure objects with the help of keyword return.

63

Programming in C

Unions
Unions are derived data type like structures. Both structures and unions are used to group a number of different variables together. But while structure enables us treat a number of different variables stored at different places in memory; a union enables us to treat the same space in memory as a number of different variables. That is, a union offers a way for a section of memory to be treated as a variable of one type on one occasion, and as a different variables of different type on another occasion. We can declare union like declaration of structures. Key word union is used to declare unions. Union name is followed by keyword union. Which are operations we perform in structures, we can perform those operations on unions also. General format to declare unions: union union name { Data type var1,var2; Data type var, var; }; Example: union date { int dd,mm,yyyy; }d; If declare the above union in structure it will occupy 6 bytes of memory, in unions it will occupy 2 bytes memory. This is the major advantage in unions. In unions compiler will allot a memory space for single variable, remaining variables also share that memory.

Declaration of union variables: When we need to use the union members, we need to declare an object for the union. We can declare an object for union like declaration of structure objects. We can access the union members with help of member selection operators dot (.) and arrow (->). We can place this member selection operator between union object and union member. General format to declare union object: union union name objece name; Example: union date d; 64

Programming in C

Pointers
Pointers are important feature in C-language. Although they may appear a little confusion for beginners,

65

Das könnte Ihnen auch gefallen