C Programming
C Programming
C Programming
'C'-Programming
Creating a program:
Converting the given flow-chart or pseudo code into executable code is called creating a program. For example the given flow-chart or pseudo code can be converted into assembly language program or to high level language program such as c,c++ etc.
Elements of C language:
C is an efficient and portable general purpose programming language. It was developed in the year 1972 at Bell Telephone laboratories (AT&T) by Dennis Ritchie. The name C was taken from the second letter of the earlier version BCPL basic combined programming language developed by ken Thompson of Bell laboratories. Until 1978 C was restricted within Bell laboratories. but after publication of definite decryption of the language by Brain Kernighan and Ritchie the language began to promote.
Features of C-language:
i. ii. iii. iv. v. vi. It is a flexible high level structured programming language. It includes the features of low level language like assembly language. It is portable. A program written for one type of computer can be used in in any other type. It is much faster and efficient. It has an ability to extend itself. It has a number of built in functions, which makes the programming simple
C Character set:
Keywords are words belonging to c- language. They have standard predefined meaning. These words should be used only for their intended purpose. The users have no right to change its meaning. Keywords should be written in lowercase. C uses the following characters in order to develop its language. They are Alphabets Digits Special characters White spaces -AZ ,a.z -0,1,2,.9 - ! # % ^&+;:={}[]()-| @$<>?/ - blank space, horizontal tab carriage return, new,from feed characters such as
Apart from the above , C uses certain combination of \b, \n,\t,\f,\r,\v,\a to denote special conditions.
'C'-Programming
Identifiers:
Identifiers are names given to variables, functions ,arrays and other user defined objects. These are user defined names .
Rules:
I. II. III. IV. Identifiers are formed with alphabets, digits and a special character underscore(_). The first character must be an alphabet. No special characters are allowed other than underscore. They are case sensitive. That is AA is different from aa.
Examples: The following are some valid identifiers AO,BASICPAY, basic pay, TOTAL-PAY,B12. 2.The following are invalid identifiers= Variable AB 9A auto Reason for invalidity Special character period (.) not allowed The first character must be an alphabet Reserve word 1.
C-Constants:
A constant is a quantity whose value does not change during programming execution . There are three types of constants. They are i. Numeric constant ii. Character constant iii. String constant
'C'-Programming
Numeric constant:
A numeric constant is a constant made up of digits and some special charaters. There are two types of numeric constants They are i. ii. Integer or fixed point constant Real or floating point constant
I. Integer constant:
Integer constant is a made up of digits without decimal point. This can have values from -32,708 to 32,627
Rules:
i. ii. iii. An integer constant is formed with digits 0 to 9. The constant can be preceded by + or - sign. No special characters are allowed anywhere in the constant.
Example:
a. The following are some valid decimal constants 10 +10 -5420 5743
b. The following are invalid decimal integer constants CONSTANTS 5,734 0452 15.03 183 REASON FOR INVALIDITY COMMA IS NOT ALLOWED THE FRIST DIGIT SHOULD NOT BE ZERO DECIMAL POINT IS NOT ALLOWED THE SIGN SHOULD PRECEDE THE DIGITS
They are three types of integer constant. They are 1) Long integer This can have values from -2,147,483,648 to 2,147,483,647. This is denoted by placing letter L at the end. 2) Short integer This can have values from -128 to 127 3) Unsigned integer This can have values from 0 to 65,535 REAL CONSTANT: Any number written with one decimal point is called real constant or floating point constant.
'C'-Programming
Rules :
A real constant is formed with the digits o to 9 and a decimal point digits before or after the decimal point can be omitted A number can be preceded by + or - sign . No special characters are used other than decimal point. A real constant can be expressed in any one of the following two forms FRACTIONAL FORM EXPONENT FORM
FRACTIONAL FORM :
A number written with one decimal point is called a real constant in fractional form
EXAMPLES:
The following are some valid real constants in fractional form -0.157 .64 2.4
EXPONENT FORM :
Exponent form is used to represent very large and very small real constants. The general form is Mantissa e or E exponent Where Mantissa Exponent either real integer value integer number
'C'-Programming
Rules :
The mantissa and exponent may have a positive or negative sign. Exponent should not have a decimal point Exponent must have at least one digit
Examples :
A. The following are some valid real constants in exponent form 1) 0.000002571 can be expressed as .2571e-5 2) -0.000000000047 can be expressed as -47E-11 or -47E -10 3) 3.14 can be expressed as .314E1
4) B. The following are some invalid real constants in exponent form constant
840E.5
50
OR AN
EXPONENT
CHARATER CONSTANT:
There are 2 types of character constants. They are Direct Escape sequence
Direct :
A direct character constant consists of a single character enclosed within single quotation marks this gives the integer value of the enclosed character. This value is known as ASCII value. Example:
CONSTANT
A O % a
VALUE
65 48 37 97
'C'-Programming
Escape sequence :
An escape sequence consists of more than one character within single quotation marks. The first character must be a backslash (\). Even though it has more than one character it represents only one.
Meaning
Bell (audiable alert) Back space Form feed New line Carriage return Horizontal tab Vertical tab Single quote Double quote Question marks Backslash Null character
constant
\a \b \f \n \r \t \v \ \ \? \\ \0
String constant :
A string constant is a sequence of characters enclosed within double quotation marks. This can be formed with digits, alphabets and special characters.
Example :
NAGARCOIL 13-th-march 12573 5.743 difference between character constant and string constant The character constant produces numeric value (ASCII) of the character enclosed within single quotes. The string constant is a sequence of character enclosed with in double quotes Thus B is not as same as B
C Variables :
A variable. C variable refers to the name given to the memory location to store data. A particular memory location is given only one name. yet this name is called a variable because this memory location can store sequence of differ rent values during the execution of the same program. quantity whose value change during the execution of the program is called a
Rules :
6
SSi -Computer Education 'C'-Programming a) a variable name is formed with alphabets, digits and a special character underscore (_). b) The first character must be an alphabet. c) No special character are used other than underscore d) Both upper case and lower case letters are used. but they are not treated as same e) It should not be a reserved word.
Example :
1) The following are some valid variable name AO BASIC-PAY VOLUME B12 2) The following are some invalid variable names
variable
A,B 9A goto
Types of variables:
Variable refers to the name given to the memory location to store data. Depending upon the data in the memory location, the variables are classified as a) b) c) d) e) f) g) h) i) j) Integer variable Long integer variable Short integer variable Unsigned integer variable Floating point variable Double variable Character variable Signed character variable Unsigned character variable String variable.
Data-types:
C supports different types of data.. Each type is represented differently within computers memory.
Basic data-type :
The table given below lists the basic data types. 7
'C'-Programming
Data
Description
Memory requirement
Char
1 byte
These can be used with integer and character data types only . long can be Used with double. The table given below lists the basic data types and range of numbers that can be stored in each data type. TYPE Char (or) signed char Unsigned char Int (or) signed int Short int or signed short int Unsigned short int Long int (or) signed long int float double long 8 8 16 8 8 32 32 64 80 SIZE (bits) RANGE -128 to 127 0 to 255 0 to65,535 -128 to 127 0 to 255 -2,147,483,648 to 2,147,483,647 0 to 4E-38 to 3,4E+38 1.7E-308 TO 1.7E+3081.1E+4932
Declaring variables: All variables presented in the program must be declared before it is used. This is done with the help of declaration statement. The general form is Data type variable 8
SSi -Computer Education Where, Data type - valid data type such as int char etc.
'C'-Programming
Variable list - list of variables separated by comma Example : 1.intA,B,C: This declares A,B and C as integer variables and allocates memory space. 2. short int a,b,c; long int GROSS; 3. float X,Y; double abc , xyz; 4. char name; 5. char name [4]; This declares name as string variable. The number 4 in the square bracket represents the maximum number characters in the string plus one. The last place is to store \o character to represents the end of the string or terminator.
If we want name to the string RAMU in the variable name, it is stored as given below. [0] R [1] A [2] M [3] U [4] \O
User of declaration 1. It provides name to a memory location. 2. It is used to allocate memory space Initializing variables: The process of assigning initial values to variables is called initializing variables. This is done at time of variable declaration. The general form is
SSi -Computer Education This statement declares all as an integer variable 2.char sex = F; Assigning values to variables:
Giving values to variables is called assigning values to variables. This is done with the help of assignment operator (=) the general form is
Variable-name =value; Where Variable name valid user defined name and it should be declared. Example 1. X = 20; 2. P1=3.14; 3. float C = 2.43; This is also a valid assignment statement.
Header files: Header files are special source files which contain various library functions. library functions are pre-written functions used to carry out commonly used routines. In order to use the library functions in the program it is necessary to include the special file which contains the function declaration within the program. During compilation the included header file will be merged with the program. The form is #include<file name >
Where #include file name - directive which directs the compiler to merge the header file with the Program. - name of the header file.
SSi -Computer Education 1.stdio.h - contains declaration of input\output routines. 2.srring.h -contains deceleration of string manipulation routines. 3.math.h - contains declaration of sin,cos,abs,tan etc.
'C'-Programming
Comment statements: comment statements are non-executable statements. these statements are used to increase the readability and understanding of a program. All comment statement should start with /* and end with /* no space is allowed between * and /. A comment can be include anywhere in the program. Example: /* program by Edwin on 8/3/2000 */ /* function to calculate average */ Operators : an operator is a symbol which represents some operation that can be performed on data. There are eight operator available in C to carry out the operations. They are 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Short hand assignment operators 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators
Arithmetic operators Arithmetic operators are used to do arithmetic calculations they are 2 types a. binary operators b. unary operators
A.. Binary operators: Binary operators need two operands for operations. They are Operator + operation addition subtraction example X=5+3 y = X-10 Z=5*3 X=5/3 = 1 or 11.67 X = 5%3 = 2 11
SSi -Computer Education B. Unary operators : Unary operators need m only one operated for operation. They are Operator ++ -operation unary minus increment decrement example -10 ++i --i
'C'-Programming
Relational operators : relational operators are used to fined out the relationship between two operands. They are operator Operation > < >= <= == != Greater than Less than Greater than equal to Less than equal to Equal to Not equal to example A>B A<B A>=B A<=B A= =B A!=B
Logical operators: Logical operators are used to find out the relationship between two or more relational expressions. They are operator && || ! Meaning AND OR NOT
Logical operators return results as indicated in the following table. X Y X&Y X||Y T T F F T F T F T F F F 12 T T T F
SSi -Computer Education 'C'-Programming Where X,Y relational expressions T - True value F - false value Increament&Decreament operator: Three are two special operators in C to control the loops in an effective manner. These operators are called increment and decrement operators. Increment operator: + + is the Increment operator. This adds 1 to the value contained in the variable. The general form is Variable + + or + + variable
The first form (post fix) uses the variables and increments afterwards. The second form (prefix) increments the variable and then use it. Examples: 1.a+ + means 2.a-- means 3.a = b+ + means 4.a = b-- means
a = a +1 a = a-1 a = b ( b = b + 1) a =b ( b=b - 1)
decrement operator: - is the decrement operator. This subtracts 1 from value contained in the variable. The general form is variable- or - - variable
the first form (post fix) uses the variable and decrements afterwards. The second form (post fix) decrement the variable and then uses it. Example: 1.- -a 2.a - 3.a = b -4.a = - - b means means means means a = a-1 a = a -1 a = b b = -1 a = b-1 b = b-1
short-hand assignment operators: short-hand assignment operators are operators which are used to simplify the coding of certain type of assignment statement. The general form is
13
SSi -Computer Education Where; Variable -valid user defined name Operator - + - * / %
'C'-Programming
Example : The table given below lists the operators with example, Operator += Meaning Value of LHS variable will be added to the RHS value and is assigned toLHS variable Example X = X+10 can be written as X+=10
-=
RHSvalue will be subtracted from LHS X = X -10 can be written as X - = 10 variable and is assigned to LHS variable Value of LHS variable will be multiplied by the RHS value and is assigned to LHS variable Value of LHS variable will be divided by the RHS value and is assigned to LHS variable Value of LHS variable will be divided by RHS value and the reminder will be stored in the LHS variable X = X * 10 can be written as X * = 10
*=
/=
X = X / 10 can be written as X/ = 10
%=
Conditional operator: The conditional operators ? and : are used to build simple conditional expressions. It has three operands. So it is called ternary operator. The general form is Expression 1 ? Expression2 : Expression 3; Expression 1 is evaluated first. If it is true Expression2 is evaluated. If Expression 1 is false Expression 3 is evaluated. Example : Big = a > b ? a : b; In this condition a > b is tested first. If this is true is true big = a else big = b. Assignment statement (or) arithmetic statements: Assignment statement are used to assign values to variables. 14
SSi -Computer Education This is done with the help of assignment operator = the general form is Variable = constant or variable or expression Rules: i) ii)
'C'-Programming
only one variable is allowed on the LHS of assignment operator = . all operations must be written explicitly. Thus if we want to multiply X by Y then it should be written as X * Y and not as XY
Example: X =10 The value 10 is assigned to the variables X. Y = X + 10 * Y The value of digits hand side expressions is evaluated and assigned to the variable Y. Expression: An Expression is a linear combination of constants. Variables and operators. There are three types of expressions . they are i) ii) iii) Arithmetic expression: arithmetic expression are formed by connecting constants or variables by arithmetic operators. The general form is arithmetic expression relational expression logical expression
constant variable
or
Example: X+Z X+Y/ Z Relational expression: Relational expressions are formed by connecting constants or variables or arithmetic expressions by relational operators or expressions by relational operators. The given form is A +ZX X/(y+z) (x + y) / z (x + y) / (Z + A )
Constant Or variable
'C'-Programming or expression
The value the expression is either true or false. Example: 1. A= = 20 The answer is true if A equals 20 else false 2. A * A B > C * C D The computer first evaluates the value of A * A A B is is garter than C * C D the answer is true else false. Logical expression: Logical expressions are formed by connecting relational expressions by logical operators. The general form is Relational Expression logical operator Relational Expression
The value of the expression is either true or false Example: 1. A > 20 & & B > 25 The result of this expression is true if A is greater than 20 and B is greater than 25. 2. A > 20 || . B > 25 The result of this expression is true if A is greater than 20 or B is greater than 25. Evaluation of expression (Hierarchy of arithmetic operations) : While evaluation an expression the computer Evaluates the expression in the following order.
1. 2. 3. 4. 5. 6. Example:
it does all expressions inside the parentheses. it does all unary operations. it does all multiplication, division And modulo operation in the order. it does all addition subtraction in the order. it does all relational and logical operational. lastly it does all assignment operations.
16
'C'-Programming
Data type conversion is a process of converting one data to another data type. C language allows mixed data type operands in an expression. But while evaluating an expression the data operands are automatically to higher data type. The result will be in higher data type. Example: Float X ; X = 5 + 7.5 ; The operands 5 and 7.5 in the expression are of different data type. But during execution 5 is automatically converted to float and the operation is performed. So the result is X = 12.5 The following table lists some conversions Opr1 Int Int Int Int Float Char Char Unsigned int Char Opr 2 Float Double Long int Short int Double Double Float Float Int Opr 3 Float Double Long int Int Double Double Float Float Int
Casting Casting is a process used to convert one data type another data type. The general form is (data type ) exp Where 17
SSi -Computer Education Data type Exp Example : Float X = 10. 25; Int Y Int c; C= ( int) X + Y The result will be 1 = 30 Here the value of X is converted to int and then added with Y. Library functions: = 20 ; valid data type variable or expression
'C'-Programming
Library functions are functions not be written by the programmer. But these are available in separate files called header files. The programmer has to include it in the programs. The commonly used header files are 1.ctype.h 2. math.h 1. Ctype.h: ` the library functions in this header file are used as a character test function and are also used for character conversion . the important functions are is digit () this function is used to check whether a given character is a digit or not. The general form is int isdigit (char c) ; This function return a non-zero integer value if its argument is a digit. Else zero. Isalpha (): this function is used to check whether a given character is an alphabet or not. The general form is int isalpha (char c); 3.sting.h 4. stdio.h 5.stdlib.h
This function return a non-zero integer if its arguments is an alphabets. Else zero. Isupper (): this function is used to check whether a given alphabet is in upper case or not. The general form is int isupper (char c ); 18
'C'-Programming
This function return a non-zero integer if its arguments is in upper case . else zero Islower (): this function is used to check whether a given alphabet is in lower case or not the general form is int islower (char c);
This function return a non-zero integer if its arguments is in lower case . else zero Ispunct (): this function is used to check whether a given character is a punctuation character or not. The general form is int ispunct (char c) ; This function return a non-zero integer value if its argument is a punctuation character .else zero. math.h: the library functions in header files are all mathematical functions. The important functions are sin (): this function is used to find the sine value of the argument .the argument must be in radians. The syntax is Double sin (double X) ; Cos (): this function is used to find the cosine value of the argument .the argument must be in The syntax is Double cos (double X) ; Tan () : this function is used to find the tangent value of the argument .the argument must be in radians. The syntax is Double tan (double X) ; exp (): this function is used to find the e to the power of X (e) . The syntax is Double exp (double X) ; Ceil () : this function is used to round up a real number . The syntax is 19
radians.
'C'-Programming
Example :
X = ceil ( 93.58) X = 94
Floor(): This function is used to round down a real number. The syntax is Double floor ( double X ); Example: X = ceil ( 93.58) X = 93 abs(): This function is used to find the absolute value of an integer. The absolute value of X is the value of X is the value of X with out sign. The syntax is
Example: X = abs ( -7 ) X=7 Fabs (): This function is used to find the absolute value of a real number. The absolute value of X is the value of X is the value of X with out sign. The syntax is Float fabs(float X); Y = abs ( 7 ) Y= 7
'C'-Programming Y = 7.5
Pow (): This function used to fined the power of any value . the syntax is Double pow(double X double());
Example: X = pow (2 ,3 ) X=8 Sqrt () : This function used to fined the square root value of its argument. The general syntax is Int sqrt(int X); Y = pow ( 4, 05 ) Y = 2.0
the library functions in this header file are used to carry out string manipulations. The important functions are below. strlen(): This function is used to find out the number of characters in the given string . the syntax is N = strlen(string); Where N - is an integer variable which receives the length of the string. String - valid string variables or constant.
21
'C'-Programming
strcpy(): this function is used to copy the content of one string into another string. The syntax is
strcpy(string1,string2); Where String 1 and string 2 valid string When this function is executed the contents of the string 2 are copied into string 1, string2 remains unchanged . the size of string 1 should have enough space to receive the contents of string 2. Example: String2 = POLYTECHNIC strcpy(string 1 , string 2) the output is string1 = POLYTECHNIC strcat () : This function is used to convert a string into a floating point value. The syntax is Strcat(string1 , string 2)
Where String 1, string 2 - valid string when this function is executed the contents of the string to are joined with with string 1 and the character \ 0 is placed at the end of the new string 1. string2 remains unchanged. The size of string 1 should have enough space to keep the new string. Example : String 1 = POLYTEHNIC String 2 = college Strcat(string1, string2); The output is 22
SSi -Computer Education String 1 = POLYTECHNICCOLLEGE String2 = COLLEGE strcmp(): This function is used to compare two strings. The syntax is Srtcmp(string1, string2);
'C'-Programming
If the two strings are equal the value of the function will be zero (0) else a numeric value other than zero. That is if string 1 is greater than string2 the value will be positive else negative. strrev(): This function is used to reverse a string. The syntax is N = strrev(string); Where N String Example: string variable to hold the reserved string valid string variable or constant , which contains the string to be reserved.
String = POLYTECHNIC n = strrev(string); the output is n strupr(): this function is used to convert a string in lower case to upper case. The syntax is n = POLYTECHNIC strlwr(): this function is used to convert a string in uppercase to lowercase. The syntax is n = strlwr(string ); = CINHCECTYLOP
Where 23
SSi -Computer Education 'C'-Programming n string variable to hold the converted lowercase string String valid string variable or constant , which contains the upper case string.
Example: String = POLYTECHNIC n = strlwr(string); the output is n 4. stdio.h: the library functions in this file are used to carry out i/o manipulation. The important functions are = polytechnic
getchar() function : getchar() function is used to read a single character. The syntax is
variablename = getchar ( ); where variable name - valid C variable by using this function repeatedly string of characters can be read in to the memory. The reading is when a new line character \ n is entered. Putchar function ():
Putchar() function is used to display single character on the computer. The syntax is Putchr(character variable);
Gets function: Gets function is used to read a string of characters until a new line character \n is entered (retrun key). The syntax is Gets(variablename);
24
'C'-Programming
Puts function : Put function is a function which is used to display strings on the terminal. The syntax is Puts(variablename);
valid C variable
Scanf() function : Scanf() function is used to give data the variables using keyboard. the syntax is Scanf (control string , & variable 1, & variable2........ Printf() function : Printf function is used to output the results of the program to the user through VDU. The general form is Printf(control string , list ) ; 5.stdlib.h: the library functions in this header file are used to carry out utility manipulations. The important functions are given below. Atof(): The library functions in this header file are used to convert a string into a floating point value. The syntax is Atof(string); Example: 5. stdlib.h: the library functions in this header file are used to carry out manipulations. The important functions are given below. atof(): This function is used to convert a string into a floating point value. The syntax is 25 & variable n ) ;
'C'-Programming
= ataf (a);
The value of X = 123. 43 atoi(): this function is used to convert a numeric string into an integer value. The syntax is atoi(string); example: char a [10 ] Int X X; = atoi (a); = 12343
The value of X = 12343 rand(): This function is used to generate a random integer between 0 and 2 15-1. the syntax is rand(); this functions returns a random integer value. strand(): This function is used to initialize the random number generator. The syntax is strand(value); where value Example: Int n; scanf ( % d , & n); strand (n); 26 a valid unsigned numeric value.
'C'-Programming
randomize(): this function is similar to the strand function. Both function are used to initialize the random number generator. While strand functions uses an unsigned as value the randomize function uses the time. Hence the header the time.h should als0o be included. The general format of this function is randomize(void); input output functions: input output functions are used top transfer information between the computer and the input output devices such as keyboard and monitor. C language does not contain any input output statements. but all input ouput operations are carried through the input output functions are present in the header file <stdio.h> and it should be included in the program. scanf() function: scanf() function is used to give data to the variables using keyboard. The general form is scanf (control string , & variable 1, variable 2.. & variable n;
Where i) control string gives the format of data to the variables. The general form is %W data - type
where % W dtatype ii) conversion specification indicator width of input data (optional) conversion character or type of data given to the variables.
The ampersand symbol (&) before each variable name is called adders operator . this evaluates the address of the variable. In the case of the string data , the variable name is not preceded by the symbol &.
Rules: i) ii) iii) variable names should be separated by comma. The number of format specification contained in the control string should match with the number of variables in the order. Format specification in the control string can be continuous or can be separated by blank space. 27
SSi -Computer Education 'C'-Programming iv) Each variable name must be preceded by an ampersand symbol (&) except string.
Meaning (data item used) Single character Decimal integer Floating point value Floating point value Floating point value Short integer Decimal /hexa decimal /octal integer octal integer string unsined decimal integer hexa decimal integer string which may include white spaces
Example : 1.scanf(%d, & a); this statement reads an integer data and assigns to variable a. 2. scanf(%f, &a); this statement n reads a floating point data assigns to variable a. 3. scanf(%d %f %d, &a , &b , &c ); 4. scanf (%c, &sex); 5.scanf(%s, %c, name, & sex); 6. scanf (%4d, &a); This statement is used to read an integer data of width 4. if the number exceeds four digits the four digits will be assigned to the variable a. 7. scanf(%5f, &a); This reads a five digit floating point number and assigns to variable a. 8.scanf(20s, name); this reds a 20 characters string and assigns to variable name . if the input exceeds 20 characters, the first 20 character will be assigned. 28
'C'-Programming
Printf() function: Printf() function is used to output the result of the program to the user through VDU. The general form is Printf(control string , list); Where,
i)
control string gives the the format of data to be displayed on the VDU. The general form is %w.p data type
where, % w p data type conversion specification indicator width of output data (optional) number of digits after decimal point or number of characters to be displayed from a string type of output data or conversion character.
ii)
the lists contains the list of variables, constants, array name to be printed.
Conversion character table: Type specifier (character) c d e f i o s u x Meaning (data item used) Single character Decimal character Floating point in exponent form Floating point in ordinary form Decimal integer Octal integer String Unsigned decimal integer Hexa decimal integer
Printing integer : The general format of control string to output integer is %wd Where W - width of the data (optional) 29
'C'-Programming
Rules: i) ii) iii) iv) v) vi) Example The examples give below explains the output of a number X = 1999 under different formats Format Printf(%d,X); Printf(%3d,X); Printf(%5d,X); Printf(%-5d,X); Printf(%07d,X); Printf(%4d,X); 0 0 1 9 9 9 9 Output if there is no width then the output number will be printed as such. If the output number width is greater than the width specified then the it will printed in full irrespective of width. The number printed is right justified. This can be changed to left by placing a minus sign(_) after the % character. If the width specified is greater than the width of the output number. Then the unused portion is left blank. The unused leading blanks in the output can be made to zero by placing a zero before the width w. To print numbers with + or - sign, the sign should be placed before the variable.
1 9 9
1 9 9 9 1 9 9 9 0 1 9 9 9 9 9
- 1 9
Printing real numbers: The general format of control string to output real number is %w.p f or e where w - width of output data (optional) p - number of digits after decimal point f - conversion character for floating point e - conversion character for floating point with exponent
30
'C'-Programming
Rules: i)if no decimal place count (p) is placed, the default is 6 places. ii)if a number contains more than 5 decimal places, the result will be rounded to six places. iii)the integer part of a number is right justified and the decimal part is left justified. vi)by7 placing a sign after % character the integer part can be made to left justified v)to print a number with + or sign the sign should be placed before the variable. Example: The example given below explains the output of a number X = 123 . 4678 under different formats Format Printf(%8.4f,X); Printf(%f,X); Printf(%8.2f,X); Printf(%e,X); Printf(%-82f,X); 1 2 3 4 6 7 8 1 2 3 . 4 6 7 8 0 0 1 2 3 . 4 7 1 . 2 3 4 6 7 8 e + 0 2 1 2 3 . 4 7 Output
Priting strings: The general form, at of control string to output string is %w.p s where w - width of the string (optional) p - number of character to be printed from the beginning s - conversion character for string Rules: i) if the width of the string is greater than the width specified, the string will be printed in full 31
SSi -Computer Education ii) the output is right justified iii) by placing a sign after % character it can be changed to left justified.
'C'-Programming
Example: The example given below explains the output of a string place = Nager coil under different formats.
Statement
position
Printf(%s, place); Printf(%10s, place); Printf(%5s, place); Printf(%-10s, place); Printf(%10.5s, place); Structure of C program : The general Structure of C program is
32
'C'-Programming
Include section or header section : In this section the header files must be included. This depends on the functions used in the program statements. The include files begin with # symbol. Example- #include < stdio.h> ,# include <math.h> etc Global declaration section: In this the user has to declare the variable which are common to both main block, and function section . this is an optional section. Main (): This function must present in all programs. This gives the starting point of the program. Local declaration setion: In this section the user has to declare the variables which are solve the problem. Function section: This is an optional section .this is section is used to write sub program. Example to find the square and root of a number
# #
33
SSi -Computer Education Printf(/ enter the number) Scanf(%f, &a); S = a * a Sq = sqrt(a); Printf (/n square = % , s); Printf (/n square root = %f , sq); }
'C'-Programming
Creating and executing of a C-program: The following steps are followed for creating and exciting a C program.
Step -1 creating or editing the C program : Using any editor (tc, ne, ws, etc), we can create the program with C extension. Usually we use tc editor .for example test. C. Step-2 compiling and linking
Using Alt + F9 in tc editor , the program can be compiled and linked. This produces the executable program with extension. Exe. For example test . exe. Step-3 running: Using Ctrl + F9 we can run the exe program and produce the required result.
34
'C'-Programming
i) ii) iii)
Unconditional goto statement: goto statement is used to transfer the program control unconditionally from one point another . the general form is goto label; lable is the name given to the point where the control has to be transferred. The general form is label: statements; Example goto LO; ------------------------35
LO:
SSi -Computer Education 'C'-Programming Decision making statements: Decision making statements are used to skip or to execute a group o0f statements based on the result of condition. The decision making statements are,
I)
Logical If Statement: logical if statement is used to execute or skip one statement or group of statement for particular condition. The general form is If (test condition ) { statement block; } next statement;
Execution procedure: Step 1 check the test condition. Step 2 if it is true, execute the statement block, go to step 4. Step 3 if it is false, go to step 4. Step 4 execute next statement Example If (mark > = 35 ) { printf(PASS) } this tests the mark of the student. If it is grater than or equal to 35 it prints pass. ii) if else statement :
36
SSi -Computer Education 'C'-Programming ifelse statement is used to execute one group of statements if the test condition is true or other group if the test condition is false. The general form is If(test condition ) { statement block -1; } else { statement block 2; } next statement; Example If(mark > = 35 ) Printf(PASS) Else Printf(Fail) This tests the mark of the student. If it is grater than or equal 35 it prints fail. Nested if .. Else statement : this statement is formed by joining if .else statements either in the if block or both. The general form is
37
'C'-Programming
statement block -1; } else { statement block 2; } else { statement block 3; } next statement;
Example program to the find biggest of 3 numbers # include < stdio.h > main ( ) { in a,b,c; printf(Enter three numbers) scanf(%d %d %d , &a, &b, &C); if(a>b) { if(a > b) printf(big = % d , a); else } else { if (b>) printf(big = % d,b); else printf(big = %d,c); } } this program is used to fined out the biggest of three numbers. Here if.else statements are include in the if the block and else block. 38
'C'-Programming
Switch statemement: switch statement is an extension of if.. else statement. This permits any number of branches. The general form is Switch(expression) { case label 1; statement block 1; break; case label -2; statement block 2; break; ----------------------------------------------------------------------------------case label n ; statement block n; break; default : default statement; break; } next statement;
Example To display day depending upon the number entered #include < stdio.h > main ( ) { int day; printf(Enter a number between 1 and 7\n); scanf(%d, & day); switch (day) { case 1: printf(Monday \n); break; case 2: 39
SSi -Computer Education printf(Tuesday \n); break; case 3; printf(Wednesday \n); break; case 4; printf(Thursday \n) break; case 5; printf(Friday \n); break; case 6; printf(Saturday \n); break; case 7; printf(Sunday \n); break; default : printf( Enter a correct number \n); break; } }
'C'-Programming
Loop structure: Loop structures are used to execute a group of statements repeatedly until condition is satisfied. The looping structures are i) ii) iii) while structure do.. structure for structure
i)
40
SSi -Computer Education While (test condition) { body of the loop ; } next statement; Example # include < stiod.h > main ( ) { int i ; I=1; While ( i < 5 ) { printf(God loves you); I = 1; While ( I < 5 ) } } these program statements are used to display the message god loves you, four times.
'C'-Programming
Initially the condition I < 5 is tested. If it is false the program ends without executing the body of the loop. Is true the ody of the loop wii be executed repeatedly (four times ).
Do while statement: The general form is Do { body of the loop; } while (test condition); next statement;
41
SSi -Computer Education Example : # include , stdio.h > main ( ) { int I ; I =1; Do { printf(God loves you); I++; } while (I < 5)
'C'-Programming
} these program statement are used to display the condition I < 5 is tested . if it is false the program ends. if it is true the body of the loop is executed repeatedly ( three times ). Difference between while and do.. while statement While 1.cheks the test condition first. 2.if test condition is false the body loop will not be executed Do Checks the test condition last. Irrespective of the test condition value body of the loop will be executed at least once.
ii)
for statement: for statement is used to execute a statement or a group of statements repeatedly for a known number of times. The general form is
For (control variable ; test condition ; increment or decrement) { body of the loop ; } next statement;
Where, 42
SSi -Computer Education i) ii) control variable is used to control the loop.
'C'-Programming
Test condition is used to check the control variable . according to this the loop is used executed or not. Increment or decrement is used to change the value of the control variable.
iii)
Example : # include ,< stdio.h > main ( ) { int I, sum; sum = 0 ; for(I = 1 ; I = < 100; I ++) { sum=sum+I; } printf(Sum = %d,sum); } on seeing the for statement the computer takes the initial value 1 to the control variable I and is checked with the test condition I < = 100 . if its value is true the body of the loop sum = sum + I is executed and the control is transferred to the statement . then the value of the control variable is incremented because of I + + and the loop is executed . this process continues till the control is transferred to next statement . in our case the value of the sum of the sum is printed.
inside for the loop more than one variable can be initialized at a time.
Example int b = 1 ; int c; For ( c = 0 ; < 99 ; c + + ) ------------------------------------------the above statements can be written as int b,c; 43
'C'-Programming
the for statements consists of control variable (initial condition) test condition , increment or decrement . we can omit one or more conditions. But the semicolons separating the condition must be there.
Example: int a, count ; For(a=0;a<10&&count < = 20 ; a + + ) { ----------------} 4.we can increment or decrement more than one variable at a time. The variables should separately by comma operator (,).
Example: int a,b,c; for(c = 0, b = 25;c<=100;c+ +,b - - ) { -------------------------} Nested for loop: if one for loop is enclosed within another for loop then such loops are known as nested for loop. There is no limit on the number of for loops that can be nested. Example: 44
'C'-Programming
Break statement : Break statement is used to exit from a loop while the test condition. Is true. This statement can be used with in a for, while the general form is break ; When the statement is executed inside a loop, the execution of the loop is terminated and the program continues with the statement following the loop . If break statement is used in nested loops, it will eixt from the loop containing it.
. if(condition) { break; } 45
'C'-Programming
Continue statement: Continue statement is used to skip the remaining loop statement and control is transferred to the loop. In other words, the statements after the keyword continue will be skipped and the control is transferred to the beginning of the loop. The general format is Continue;
SSi -Computer Education if( a< 0) { printf(Error); continue; } Statements for processing positive a value
'C'-Programming
} during execution if the value of a is negative , the statements below the keyword continue are skipped and the control is transferred to the begging of the loop Arrays: in computers we store information in the memory by giving names to them. these names are called variables. for example consider the following statement. scanf(%d %d %d, &RAJA,&b,&c); if the value of the variables a,b and c are 10 , 20 , 30, these numbers are stored in the memory cells as a 10 b 20 c 30
suppose we want to store 1000 numbers for processing , it is highly difficult to name 1000 different variables. but with the help of array facility in C these 1000 numbers . a single name is given to all 1000 numbers. if a the name given to all 1000 numbers. number is referred as a [0] the second as [1] and so on. the individual variable a[0] , .. a [999] are called subscripted variables or index variables. the numbers are stored in the memory as shown below,
a[0] 10
a[1] 20
a[2] 30
--------------------------
a[1999] 1999
An array is defined as a group of related data items that share. a common name. Subscripted variables: the variables which are used to represent the individual data in memory are called subscripted variables. the general form is array name [subscript] 47
'C'-Programming
where array-name subscript Rules: i) ii) iii) iv) v) the subscript is always an integer the subscript value cannot be negative the subscript must be given within square brackets after the array name. if there are more than one subscripts each should be given in separate square brackets. subscripts can be integer variable or expressions that give integers. - valid C variable name - an integer from 0to n.
One decimal array : An array name with only one subscript is known as one decimal array. The general form is array-name[subscript]
Example: i) a[1] ii) b grade[50] where a and grade are name of the arrays. 1and 50 are subscripts which represents the data in the 1st and 5th location in the memory.
Declaration Of One Dimensional Array: arrays must be declared before it is used like other variables. the general form is datatype array name[size]; where, datatype array-name size int, flort, char etc. valid C variable name. number of contiguous location in the memory to be reserved.
SSi -Computer Education 'C'-Programming ii) the name of the array should be unique the elements in the array should be same of type . that is if an array is declared as contain elements that are not int. iii) Example: i)int mark[100] this declares an integer type array named as mark having 100 memory locations to store 100 integer data. ii)float salary[100] this declares a floating point type array named as salary having 100 memory location to store 100 floating point data. iii)char name[200] This declares a character type array named as name having 200 memory location to store 200 characters data. Array Initialization: The process of assigning initial values to 1-Kavi .prbu. arrays during declaration is called array initialization . The general from is static datatype array-name[size] = {list of value} where static data type keyword type of data found in the array such as int, float, char etc. valid C variable name. number of contiguous locations in the memory to be reserved. initial values to be given to the array . this separated by commas
this declares age as an integer array having three locations and assign initial value as given below, age[0] 10 age[1] 20 age[2] 30
ii)static int age[5] = {10, 20 , 30 } if the size of array is greater than the number of values in the list. then the unused locations are filled with zero s as given below,
49
'C'-Programming
iii) static float salary [] = { 10.50, 20.75,30.80}; This declares salary as a array and the size of the array is automatically allocated by counting the number of values. here computer counts the value as three and assigns the size as 3. iv) static char a[9] = computer
This declares name as a character array having 9 characters and assign initial values as
a[0] C
a[4] a[5] u t
a[6] e
a[7] a[8] r \0
Even though the character string has 8 characters , we have defined the array with 9 elements. this is to store \o character as the string terminator. 1-D array processing (reading and writing): Looping statement are used for 1-D array processing. the important operations on the arrays are i)storing values arrays (reading) ii)retrieving the stored values (writing) the most commonly used looping statement for array processing is for loop. this needs one for loop. because 1- D array has only one subscript
Example: i) Storing value to an 1- D array (Reading) int a[10]; for(I = 0;i< 10 ;I + +) { scanf("%d",&a[1]); } The above statements are used to store 10 integer value to an array named a.
50
SSi -Computer Education ii) Retrieving the stored values (Writing) int [10]; for(I = 0;i< 10; i+ +) { printf("%d,a[i]); } Multidimensional arrays:
'C'-Programming
'C' language provides the facility for multidimensional arrays . Multidimensional array are arrays with three or more dimensions. the exact limit by the compiler . the general form is type array name[s1] [s2] [s3] .[si]; where type array- name s1 Example: int mark[5] [0] [6]; This declares mark as a three dimensional integer array containing 1500 elements of integer type. structures: array is a power full tools to represent group of data items of same data type with a single name. however if we want to represent a group of data items of different data types with a, single name ,the array is inadequate to the task. but C language provides am data type named as structures to do this task. this structure is defined as a type to represent several different type of data with a single name . difference between arrays and structures: i) ii) All data in an array should be of same data type. but in structures data can be different data types. Individual entries in array are called elements. but in structures individual entries are called members. An integer variable I in C is defined as int i : We don't have to tell C what an int is because C already knows it. but while defining a structure variable we have to tell C about i) how the structure looks like 51 data type valid 'C' name size of the ith dimension
'C'-Programming
A structure definition contains a key word struct and a user defined tag-filed followed by the members of the structure with in braces. the general from is struct tag-filed { datatype member1; datatype member2; --------------------------------------------datatype member n; }; where, strut keyword to define structure name of the structure - valid C name valid datatypes such as int, float etc tag-field datatype Rules: i) ii) iii) iv) tag field is the name given to the structure each member definition should be terminated with semicolon since structure definition has compound statements, it should have its own opening and closing braces. the semicolon after the closing brace is a must. The structure definition tells C exactly what our structure looks like (format of the structure) as shown below.
struct
tag-field member 1
member 2
member n Example: 52
SSi -Computer Education 'C'-Programming Consider a student information consisting of number , age , sex. the structure definition can be done as follows struct student { int number; int age; char sex; }; This defines structure with members namely number, age and sex of different datatypes. The name of the structure is student The figure given below shows how this structure format looks like number age sex
Note: The members of the structure definition are not variables. So they do not occupy any memory space. Structure Declaration: Structure declaration means defining variables to the already defined structure. The general form is
struct tag-filed variable1,variable2, .. variable n; where variable1, variable2.. variable n are valid C variables names each having nmembers.(i.e.,member1,member2,.member n ) tag-field Example: Struct student1,student2,student3; This declares student 1 ,student2, student3 as structure variables each having three members number, age, sex 53 - name of the define structure
'C'-Programming
Dot operator ' .' is used to give data to the structure variables individual members. The general form is Structure variable member _name. The variable name with a period and the member name is used like any ordinary variables individual members. the general form is structure variable member_name the variable name with a period and the member name is used any ordinary variable. Example: Write a program to find the sum of two complex numbers #include < stdio.h > main ( ) { struct complex { float rp; float ip; }; struct complex x, y,z; printf("\n enter the first complex real part and imaginary part"); scanf("%f %f", &x.rp , &x.ip); printf("\n enter the second complex number real part and imaginary part"); scanf("%f %f", &y.rp , &y.ip); z.rp = x.rp + y.rp; z.ip = x.ip + y.ip; printf("\n z = % 6.2f + 6.2f I", z.rp,z.rp);
Structure initialization: the members of the structure variable can be assigned initial values. for this the structure should be declared as static . the general form is static struct tag-field structure variable = { value1, value2..value n}; where, static - storage class struct - keyword example: 54
SSi -Computer Education i) struct student { int number ; int age; char sex; } static student1 = {100, 21, 'm'};
'C'-Programming
this assigns the value 100 to student 1 number 21 to student 1.age m to student 1. sex ii) struct student { int number ; int age; char sex; static student1 = {100, 21, 'm'}; } This assigns the value 100 to student 1 number 21 to student 1.age m to student 1. sex 101 to student 2number 21 to student 2.age F to student2.sex iii) struct student { int number ; int age; char sex; }static student 1 = { 100, 21, 'M'}; ---------------------------------------------------------------------------------------------------------------------55
SSi -Computer Education static struct student student2 = { 101, 21, 'F'}; ------------------------------------------------------------------------------this declaration will do the same assignment as in example (ii) iv) struct student { int number ; int age; char sex; } static student1 = {100};
'C'-Programming
initial value will be assigned to the first member only. automatically assigns zero to the rest of the members. arrays of structures: array of structure is defined as a group of different data types stored in a consecutive memory location common variable name called an array structures example i) struct student { int number ; int age; }; struct student student1[2];
this declares student as a array of structures having two elements student[0], student[1]and each having two members . the figure given shows the memory occupation.
student1[0]no ii) {
student[0].age
student 1[1] no
student 1 [1].age
'C'-Programming
This declares students 1 as a array of structures having two elements student[0] and student[1] and initialize their numbers as student1[0]. number =100 student1[0]. age =21 student1[1].number = 101 student 1[1].age = 21 structure within structures (Nested structure ): When a structure is declared as a member of another structure then it is called structure within structure or nested structure. the figure given below shows the format of the nested structure. example : i) struct student { char name[20]; int number; char branch[5]; struct hostel -detail } int hostel_room_number; char food; int deposit amount; }hostel; }student1[10]; this declares a structure having four members namely. name ,number, branch and a structure hostel- detail the outer structure struct student student1 [10] gives the information about the students college detail and hostel detail. the inner structure sruct hostel-detail gives the information about the hostel detail of a student. the members of the structure are accessed as student1[0].hostel_room_number-gives the first student hostel room number student1[7].hostel. food -gives the 8th student type of food in the hostel . student1[7].number-gives the 8th student number and so on . 57
SSi -Computer Education ii) the following declaration is also valid struct hostel-detail { int hostel -room-number; char food; int deposit-amount; }; struct student { char name[20]; int number; char branch[5]; struct hostel-detail hostel; inner structure } student1[10];
'C'-Programming
Functions
Introduction: in C language , all program must be called "main ( ) ) " to indicate the starting point of the execution. if we write all the codes with in the main function the program becomes to big . so, it is difficult to under stand and debug the program. to overcome\e the above problems, the codes are divided into independent modules called function. there independent function are combined through main function to produce the original program. there are two types of function in C . they are i) Library functions 58
library functions are functions which are not required to be written by the programmer. but these are available in separate files and the programmer has include it in the appropriate places. Example - printf ,scanf etc. A user defined function or a has to be written by programmer to carry out some specific well defied task. All C- programs consists of one or more functions. Out of this one function shows shows from where the program execution begins. All other functions will be controlled by the function main. Functions : A function should be defined before it is used . RAJA function. has two parts i) function header ii) statement body The general form is function-type function-name(list of arguments) argument_declaration; { local variable declaration; executable statements-1; -----------------------------------------------------------------return(expression); }
where, function type function-name list of arguments represents the data of the value returned by the function valid C- variable name formal arguments declaration of formal arguments such as int , char etc. key word to the value
59
SSi -Computer Education i) function header should not terminate with semicolon. ii) iii) iv) v) list of argument and argument declaration are optional if the function has no list of argument an empty parenthesis is a must
'C'-Programming
the expression in the return statement is (blank)optional. if there is no expression the return statement acts as a closing brace and return the value of the expression the parenthesis around the expression in the return statement is optional
Return statement : return statement is used to return a value to the calling function . the general is return [OR] return (expression); if there is no expression , the statement acts as a closing brace and return back the control to the calling function. if there is expression , it returns the value of the expression . the parenthes's around the expression is optical. example: i) return ; no return value . but the control is transferred to calling function . the value of the expression a+b is calculated and returned to the calling ii) return (a+b); function. iii) return a + b -
valid statement .
Declaring function type: the function type in the header is optional. if there is no function type in the function header the return statement by default returns an integer value.
example: i) ii) iii) function-name (list of arguments) this function returns integer value int function-name (list of arguments) this function returns integer value float function - name (list of arguments) this function returns floating point value. Function retuning nothing : 60
SSi -Computer Education 'C'-Programming if the function is not to return any value , we can declare the function of type void. this tells C not to save any temporary space for a value to be sent by the function. The general form is void function-name(list of argument) Example of function: acb(I,j) inti,j; { intk; k = I + j; return(k); }
abc is the home of the function . it has two format parameters I, j . the statement body has another variable k and we are finding the value of k by adding the values of the formal parameters I and j . the return statement returns the value of k to other function. Calling a function : A defined function can be called from other functions by specifying its name followed by a list of arguments enclosed within parentheses. the general form is function-name (list of arguments); Where function-name list of arguments name of a already defined function. actual arguments
Rules: i)function - name should be the name used in the function definition (called function) ii)list of arguments is optical iii)if the function call has no arguments, an empty pair of parentheses is a must. vi)data type of the arguments should match with the already defined (called function) arguments. v)the called function returns only one value per call. Function declaration: 61
SSi -Computer Education 'C'-Programming Function declaration means , declaring the defined function in the main program. the general form is datatype function name (); Where, data type function name it should be same as in the function definition. name of the defined function.
If the defined function return data type (function) is void or int , then there is no need to declare the defined function in should be declared in the function main. Example # include < stdio.h > main( ) { float X,Y; floata,b,c( ); scanf("%f %f " , & X , &Y ); printf("%f", abc (x,y)); } float abc (I,j) float I,j; { float k; k = i+ j ; return (k); }
Note: If the function is used before main function , then there is no need for function declaration. Types of call function call: A function call may appear by itself or may be one of the operands within a more complex expression . the following are all valid calls
i)
sum(10.5); 62
'C'-Programming
The arguments present in the function are called formal arguments. these are also called as dummy arguments because it receives value only from the calling function . for example consider the function definition. abc (I,j) int I,j ; { int k; k = I + j; return(k); } In the function I and j are called formal or dummy arguments because it receives values only from the calling function. for example consider the function definition.
Actual arguments or parameter passing: The argument present in the function calling are called actual arguments. through these arguments only the arguments in the function definition (dummy argument ) receive values. this principle is called parameter passing. for example consider the program main( ) { int a,b,z; 63
'C'-Programming
Here a and b are called actual arguments because only through this the called function abc receives the values of the formal arguments I and j as 105. now the function is executed and the result 15 returned to the calling and it is printed. types of Function: There are four types of functions. They are
i) ii)
functions with arguments and no return vales . iii) functions with no arguments and return vales .
vi)
Functions with no arguments and no return vales : this is the simplest function. this does not receive any arguments(data) from the calling function and does not return any value to the calling function.
Example: main () { int a,b; ----------------message( ); /*no actual arguments to send*/ } void message ( ) /*no formal arguments to receive*/ { 64
SSi -Computer Education ------------------retrun;/*no return value to the called function main*/ } Functions with arguments and no return vales .
'C'-Programming
This function receives arguments (data) from the calling function and does not return any value to the calling function. Example: main ( ) { int a,b; --------------message( a,b); /*actual arguments to sent */ --------------} void message (x,y) /*formal arguments to receive */ int x,y; /*formal arguments declaration */ { ----------------------return ; /* no return value to the called function main
Functions with no arguments and return vales: this function receives arguments (data) from the calling function and does not return any value to the calling function. Example: main ( ) { int a,b; 65
SSi -Computer Education --------------message( ); --------------} message ( ); { int x,y value ; /*local variable declaration */ -----------value = x + y return (value);/*this statement returns the value to the calling
'C'-Programming
Functions with arguments and return vales : These function receive arguments (data) from the calling function and return the back to the calling function. Example: main ( ) { 66
SSi -Computer Education int a,b; --------------message(a,b );/*actual arguments to send * / --------------} message (x,y); /*formal arguments to receive*/ int x,y; /*formal arguments declaration*/ {
'C'-Programming
int x,y value ; /*local variable declaration */ -----------value = x + y return (value);/*this statement returns the value to the calling function */ }
Recursive function: a recursive function is one that calls itself again and again the difference between the normal function and recursive function is ,the normal function will be called by other function by its name. but the recursive function will be called by itself as long as the is satisfied.
Example program to find the factorial of a given number. factorial of a number can be got by repeated multiplication as shown below. n! = n* (n-1) * (n-2) * (n-3) .. * 1 therefore 5! = 5x4x3x2x1 = 120 in general n! = 1 if n = 0 = (n(n-1)!m if n>0 67
SSi -Computer Education #include < stdio.h > main ( ) { int fact (int); int I, a; scanf ("%d",& i); a = fact (i); printf ("%d", a); } int fact (int n) } int f; if (n = = 0 ) return (1); else f = n * fact (n-1); return (f); } Explanation :
'C'-Programming
let us assume n = 4. since the value of n is not equal to 0. the statement , fact = n* fractional (3) will be executed with n =4 call -1 fact = 4*factorial (3) call-2 fact = 4*3*factorial (2) call-3 fact = 4*3*2*factorial(1) call-4 fact = 4*3*2*1*factorial (0) call -5 fact = 4*3*2*1*1 factorial of 4 = 24 Passing one dimensional as parameters : Passing an 1-D array to a function like variable is called passing 1-D parameters. the calling function uses the array name and the size of the array as actual arguments. the called function uses the array name and size of the array as formal arguments to receive the actual arguments. 68
'C'-Programming
The general from are i) the function call takes the from function -name (array_name , size of the array); ii)the function definition takes the from data type function name(array_ name, size of the array )formal argument declaration; Rules: i) The function name in the call and in function definition should be same ii) Type of the actual and formal arguments should be same iii) The array name in the formal argument is declared with empty brackets. Example: let 'a' be the name of the having n elements and it should be passed to a function named as big. the program segment is main ( ) { int a [100] int n; printf("Enter the value of n \n") scanf("%",&n); ------------------------------------------------------big (a, n ); ------------------------------------------------------} big(x, n1) intx[],n1; int n1; { ------------------------------------------------------} where the function call big (a,n) is made , the values in the array a are passed to the corresponding location of the array x in the called function. passing multiplication arrays as parameter: passing a 2-d array to a function like variables is called passing 2-D array as parameter . in the function definition , while declaring the formal arguments, the first dimension of the array must be and all other must be given value. Example: main ( ) 69
SSi -Computer Education { int a [10] [10] ,b[10] [10] , m,n, ------------------------------------------------------frame(a,b,m,n) ------------------------------------------------------} frame(x,y,P,Q) int x[] [10] ,y[][10],P,Q; { ------------------------------------------------------}
'C'-Programming
Passing structure : passing the entire structure to a function like variable is called passing structure as parameters.the general from is I)Called Function: functionname (structurevariablename); where functionname structurevariablename argument). name of the called function. variablename of the defined structure(actual
70
SSi -Computer Education datatype functionname(variable name) struct tag-field variablename; { -----------------------------------------------------------}
'C'-Programming
Where, functionname struct tag-field variablename name of the function keyword name of the structure to be passed formal argument which receives the actual argument and it should be of struct type.
Example: Program to pass the entire structure to a function and to print it #include <stdio.h> struct student { char name [20]; int number; char branch [5]; }; main( ) { void output ( ); static struct student a= {"raju", 101, "CT"}; output (a);/* a- actual argument structure variable */ } viod output(b)/* b-formal argument to receive a*/ struct student b; { printf ("%s,%d,%S,b.name,b.number,b.branch); } } The output will be 71
'C'-Programming
Raju 101 CT Note: the structure variable used as the actual argument and the corresponding formal argument in the called function must be of same type i.e. . struct type. Files: the output is given to the computer through keyboard and the output is displayed on the VDU. these are carried out using the functions available in stdio.h .the problems with this are,
i) ii) iii)
the data are not permanent it is a difficult to deal large amount of data. modification of data is difficult.
using files structures we can slove the above problem. File is a special data structure used to give input and get output using input and output devices such as floppy disk, hard disk etc. The basic data file operations are naming , opening ,reading, writing and closing. To carry out the above operations the following types of data files are used.
i)
system oriented(low level i/o).in this method the operations are performed in unix mode. C'
ii) steam oriented (high level i/o) .in this method the operations are performed using standard i/o library. File Access: There types of file access. they are; i) ii) iii) Opening File : reading writing executing
before we read a from a file or write to a file, we must open the file . opening establishes a link between the program and the operating system. the general form is int open("filename",mode); Where 72
'C'-Programming return type function name valid 'C' name to specify the access mode of the file The different mode are: 0 1 2 read mode wrote mode both read and write mode
open function returns an integer value called file descriptor. if there is an error it returns 1. Normally 15 to 20 files can be opened at a time. Example: int; fd is the file descriptor fd = open ("mydata.dat",o); the file mydata.dat is opened for reading. Closing a file: All opened files must be closed after all operations are completed . the general form is close(fd); Where, close fd Example: int fd1, fd2; fd1 = open ("test",o); fd2 = open ("mydata",1); --------------------------------------------cose (fd1); --------------------------------------------cose (fd2); Creating a file: 73 - function name - name of the descriptor used while opening the file
SSi -Computer Education 'C'-Programming creat ( ) function is used to create a new file or to rewrite old files. the general form is int create ("file name", mode); Where, int creat filename mode return type functionname valid 'c' name octal control digit to specify the access rights of a file.
Creat function returns an integer called file descriptor. note:if the filename specified in the creat ( ) function already exists, it erases the existing file and recreates it. Example: int fd; fd = creat ("mydata",0754); Reading a file: reading a file means reading data from the opened or created file in read or read/write mode. the general form is int read(fd,buf,n); Where, - return type. Number of bytes read -function name. - name of the already created or opened file descriptor. -name of temporary memory area. through this only the computer read data. - size of the data to read in terms of bytes. The actual data to read can be less than n. while reading this function returns the value of n or less than n (transferred data size in bytes) . if it return the of n or less than n(transferred data size in bytes). if it return 0 then reading is over (that is end of file). if it return -1 then an error occurs. int read fd but n
Example: 74
SSi -Computer Education char buf [100]; int I , fd 1; fd 1 = open ("mydata",0); 1 = read (fd1, buf,100);
'C'-Programming
here the buffer size is 100 byte . that means at a time a maximum of 100 bytes data can be read from the fie descriptor fd1 and can be stored in buffer buf. Writing a file: writing a file means, writing data to a file opened or created in write or read/write mode. the general from is int write(fd,buf,n); Where, int read fd but n - return type. Number of bytes written. -function name. - name of the already created or opened file descriptor. -name of temporary memory area. through this only the computer read data. - size of the data to write in terms of bytes. while writing , this function returns the value of n. if it retruns-1 then an error occurs. Example: char buf [100]; int I , fd 1; fd 1 = open ("mydata",1); 1 = write (fd1, buf,1000); Here the buffer size is 100 byte . that means at a time a maximum of 100 bytes data can be written to the file descriptor fd1 and can be stored in buffer buf.
Program: 75
SSi -Computer Education write a program to create a text file and to display its contents. # include < stdio.h > # include < string.h> main ( ) { int fd1,fd2; char buf[10]; char str[250];z int n, l p; if(I = open ("mydata",0)) = = -1) } printf("Error opening file.\n"); exit(1); } printf("\n enter the text to write "); gets(str); I = strlen(str); n = I; if ((p = write (fd1,str,n)) ! = 1) { printf("error writing to the file. \n"); exit(1); } printf("wrote %d bytes to the file. \n",p); closed(fd1); }
'C'-Programming
76