Prgramming in C.pdf

download Prgramming in C.pdf

of 70

Transcript of Prgramming in C.pdf

  • 8/10/2019 Prgramming in C.pdf

    1/70

    Structured Programming in C

    Cyryx Coll ege Page 1 of 70

    Diploma in Information Technology

    Structured Programming in C

    Semester - 3

  • 8/10/2019 Prgramming in C.pdf

    2/70

    Structured Programming in C

    Cyryx Coll ege Page 2 of 70

    Structured Programming in C

    What is C?C is a programming language developed at AT&Ts Bell laboratories of USA in 1972 byDennis Ritchie.C is so popular, because it is reliable and easy to use.

    Historical development of C:-

    By 1960 computer language had come to existence, almost each for a specific purpose.

    E.g.: COBOL -> used for commercial applications.FORTRAN -> used for Engineering & Scientific applications.

    At this stage people started thinking that learning and using so many languages. Each for adifferent purpose. So international committee setup to develop a language called ALGOL60. But it was not popular, because that was too abstractand too general.

    To reduce this abstractness and generality, a new language called CPL (CombinedProgramming Language) by Cambridge University. But it was also not popular, because itwas so bigand hard to learn (So many features)

    BCPL (Basic Combined Programming Language) by Martin Richard at CambridgeUniversity aimed to solve the problems. But it was too less powerful and too specific.

    At the same time Ken Thompson atAT&T Bell lab introduced a language called B ButB also turned out to be very specific.

    Ritchie, B&BCPL, added some of his own and developed C

    RITCHIES main achievement is the restoration of the lost generality in BCPLand Bandstill keeping it powerful.

    C is a one-man language.Various Stages in evolution of C language:

    Year Language Developed by Remarks

    1960 ALGOL

    International

    Committee

    (i) Too general.

    (ii) Too abstract.

    1963 CPLCambridgeUniversity

    Hard to learn

    1967 BCPLMartin Richard at

    CambridgeCould deal only with

    specific problem.

    1970 B Ken ThompsonCould deal with only

    specific Problem1972 C Dennis Ritchie Lost generality of

  • 8/10/2019 Prgramming in C.pdf

    3/70

    Structured Programming in C

    Cyryx Coll ege Page 3 of 70

    BCPL and Brestored.

    Where C Stands:All programs are divided into two categories.

    1.

    Problem Oriented Language(Or)High Level language (Helps to design to give better programming

    efficiency,(i.e.) faster program development.)E.G. FORTRAN, BASIC, PASCAL

    2. Machine Oriented Language(Or)

    Low Level Language (Design to better machine efficiency).E.G. Assembly language & Machine Language

    C is having these two categories. Both

    Machine Oriented&

    Problem Oriented Language.So C isa MIDDLE LEVEL LANGUAGE.

    Steps to learn C

    Alphabets: - A, B, CZA, b, c z

    Digits:- 0,1,2,.9

    SpecialSymbols:- ~ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; < > , . ? /

    Constants: a=20 (here 20 is the constant value for a)

    AlphabetsDigitsSpecial Symbols

    ConstantsVariablesKeywords

    Instructions Program

    Type of Constant

    Primary Constant Secondary Constant

    Integer ConstantReal ConstantCharacter Constant

    Array, PointerStructure, UNION,Etc.

  • 8/10/2019 Prgramming in C.pdf

    4/70

    Structured Programming in C

    Cyryx Coll ege Page 4 of 70

    Rules for Integer Constant:-

    At least one digit

    Must have a decimal point Either positive or negative, default is +ve

    No commas, blanks.

    Range is32768 to +32767.

    E.G. 426+ 782- 800- 7605

    Rules for Real Constants/Floating Points

    At least one digit. Must have a decimal point.

    Either positive or negative, default is +ve. No Commas, Blanks.

    Eg: +325.34426.0-32.76-48.5798.

    Rules for Character Constant

    Single Alphabet or a single special symbol enclosed within single invertedcommas.

    Maximum length can be 1 character.

    Declaration of the character constantsChar x;Char x, y, z;

    The char stands for the character data for declaring the character constants. The declarationformat of character data type is same as that of the declaration of integer, floating or stringconstants.

    We use the backslash \ to denote nor-graphic characters and other special characters forspecific operations. The following characters are used as a non-graphic character:

    \n new line (line feed)\n horizontal tab\b backspace\r carriage return\f form feed

  • 8/10/2019 Prgramming in C.pdf

    5/70

    Structured Programming in C

    Cyryx Coll ege Page 5 of 70

    \\ back slashes\ single quote\0 null character (an important special case of this is null character \0 to be

    distinguished from 0.(Zero, not the alphabetic letter o)

    C Variables:-A quantity which may vary during program execution is called a variable.

    Rules:-

    1 to 8 alphabets, digits or underscores. 1stcharacter must be a character

    No commas, blanks within a variable name No special symbol, other than _ (underscore).

    E.G: st_intm_hrspop_e_sqt.

    Keywords /Reserved WordsWhose meaning has already been explained to a compiler

    The keywords are also identifiers but cannot be user defined since they are reserved words.The following words are reserved for use as keywords. We must not choose them asvariables or identifiers.

    The Following words are keywords:-

    auto double if staticbreak else int structcase enum long switchchar extern near typedefconst float register unioncontinue far return unsigneddefault for short voiddo goto signed while

    Some compilers also regard asm and fortran as keywords. These above said reservedwords have already been declared in the c compiler as standard words to perform predefined

    operations. For example, goto is a keyword and it cannot be used as an ordinary variable.

    C Operators:-The following sections explain he different types of C operators and their usage. In c,there are some unusual operators used to perform the tasks of logical decision making unlikeother higher level languages.

  • 8/10/2019 Prgramming in C.pdf

    6/70

    Structured Programming in C

    Cyryx Coll ege Page 6 of 70

    C- Operators

    Arithmetic OperatorsArithmetic operators are the basic and common operations in a computer programminglanguage. Normally these operators are considered as basic operators known as binaryoperator since they require two variables to be evaluated. For example, if we want tomultiply any two numbers, one has to enter or feed the multiplicand and multiplier. That iswhy it is considered as a binary operator. In C the arithmetic operators are as follows:

    Operator Meaning+ Addition

    - Subtraction* Multiplication/ Division% modulo (remainder of integer division)

    The operator /(slash) for division deserves a special attention. If we divide an integer byanother integer, we obtain an integer value.

    Arithmetic operators

    Assignment operators

    Comparison & logicaloperators

    Bitwise logicaloperators

    Special operators

    Relational

    Equality

    Logical

    Unary Operators

    Ternary Operators

    Comma Operator

    Other operators

  • 8/10/2019 Prgramming in C.pdf

    7/70

    Structured Programming in C

    Cyryx Coll ege Page 7 of 70

    39/5=7In the x/y at least one of the operands x and y has floating point type, if the result will befloating point type. Incidentally, this also applies to addition, subtraction and multiplication.For the latter operations the type of operands does not seriously affect the value of theresult.

    Assignment OperatorsAn assignment operator is used to assign a value to a variable.

    Operator Meaning= Assign right hand (RH) value to the left hand (LH) side

    the symbol = is used as an assignment operator, and it is evaluated last. Remember thatequal to(=) is an operator and not an equation marker, so it can appear anywhere in place ofanother operator. The following are legal C Statements.

    a=b =c+4;c=3*(d=12.0/x);

    for Example,x+=y is equal to x=x+y;x-=y is equal to x=x-y;

    Comparison and logical operators

    For program flow, the comparison operators as well as logical operators are required. Thecomparison and logical operators can be grouped into three. There are relational operators,equality operators and logical operators.

    Operator meaning< Less than> Greater than= Greater than or equal to== equal to!= not equal to&& Logical AND|| Logical OR! Not

    Relational operatorsRelational operators compare the values to see if they are equal or if one of them is greaterthan the other and so on. For program flow, the comparators and the logical operators areessential.

    Relational operators in C produce only a one or a zero result. These are often specified of astrue or false respectively, since there are only two values possible. The followingoperators are used to perform the relational operations of the two variables or expressions.

  • 8/10/2019 Prgramming in C.pdf

    8/70

    Structured Programming in C

    Cyryx Coll ege Page 8 of 70

    Operator Meaning< Less than

    > Greater than= Greater than or equal to

    The relational operators are represented in the following syntax

    expression relational operator expression 2

    The expression 1 will be compared with expression 2 and depending upon the relation likegreater than, greater than equal to and so on, the result will be either true or false.

    For example,

    Expression result3>4 false6-32 true(23*7)>=(-67+89) true

    Equality operatorsThe following operators are used to check the equality of the given expression or astatement. These operators are normally represented by using the two keys like equal to willbe the operator == and not equal to will be != and note that the single equal to sign isconsidered as an assignment operator in C. Proper care must be taken while using these

    operators.

    Operator Meaning== Equal to!= Not equal to

    Like the relational operators, the equality operators also produce the result of either true orfalse, depending upon the condition used in a program. The following examples show theequality operators usages

    For example, a=4, b=6, and c=8

    Expression resulta==b false(a*b) !=c trues==y false

    Logical operatorsThe logical operators && and || are lower in precedence than the relational operators < and> which are lower than + and -. The operator && is higher than the operator ||. Some

  • 8/10/2019 Prgramming in C.pdf

    9/70

    Structured Programming in C

    Cyryx Coll ege Page 9 of 70

    other languages place the logical operators higher than the relational operators, whichrequire parenthesis.

    Operator Meaning

    && Logical and|| Logical or! Logical Not.

    Logical ANDThe compound expression is true when two conditions (expressions) are true. To write bothconditions, use the operator && in this manner.

    expression 1 && expression 2

    The two expressions must be integer data types. The char data are converted to integer andare thus allowed in the expression.

    Example,

    a=4, b=5, and c=6(a

  • 8/10/2019 Prgramming in C.pdf

    10/70

    Structured Programming in C

    Cyryx Coll ege Page 10 of 70

    operands such as incrementer and decrementer. The most common unary operation is unaryminus. Where a minus sign precedes a numerical constant, a variable or an expression. Thefollowing operators are the unary operators in C.

    Operators Meaning

    + Contents of the storage field to which a pointer is pointing& Address of a variable- Negative value (minus sign)! Negation (0, if value #0, and 1, if value =0)

    ++ Incrementer- - Decrementer

    type forced tyoe of conversionsizeof Size of the subsequent data type or type in byte.

    Pointer Operator(*)The pointer operator is used to get the content of the address operator pointing to theparticular memory element or cell.

    Address operator (&)The address operator & is used to get the address of the other variable in an indirectmanner.

    Sizeof operatorThe sizeof operator is used to give the direction to the C compiler to reserve the memorysize or block to the particular data type which is defined in the structure type of data in thelinked list.

    Incrementer and decrementer

    In the C language there are two special operators used : incrementer decrementer. Theseoperators are used to control the loops in an effective method.

    IncrementerThe ++ symbol or notation is used for incrementing by 1.For Example,

    ++i; equal to i=i+1;i++; equal to i=i+1;

    There are two types of incrementers: prefix incrementer (++i), postfix incrementer (i++).In prefix incrementer, first increment and do the operation . On the other hand in the post

    fix incrementer first do the operation and then increment but the result of the incrementedvalue will be the same for both cases.

    For example,i=7;x=++i;x=i++;

    After execution, the value of x will be set to 8.

  • 8/10/2019 Prgramming in C.pdf

    11/70

    Structured Programming in C

    Cyryx Coll ege Page 11 of 70

    DecrementerThe decrementer is also similar to the incrementer. The symbol or notation is used fordecrementing by 1.

    For example,

    - -i equal to i=i-1;i- - equal to i=i-1;

    Here also there are two types of decrementer :prefix decrementer (- -i), post decrementer (i- -).

    WRITING A PROGRAM IN CVariable declaration

    All variables must be declared before it can be used as an executable statement in ourprogram. A declaration is a process of naming of the variables and their corresponding datatype in C. Usually the declaration part will be placed after the begin statement and sometimesome of the global variables are defined or declared outside of the program.

    A declaration consists of a data type, followed by one or more variable names, ending with asemicolon. A variable is an object that may take on values of the specified type. Variablemust be declared by specifying the data type and the identifier.

    The general format of the variable declaration is

    data_type identifiers 1,2.n;

    For example,

    1.char ch;

    Where ch is a character data type

    2.short int x,y;

    Where x,y are short integer data type and it holds the data size of 1 bits.Long.

    3.long int x1;

    Where x1 is a long integer data type whose maximum size is 32 bits long.

    StatementsA statement is a computer program is to carry out some action. There are three types ofstatements used in C, and they are expression statement, compound statement, and controlstatement.

  • 8/10/2019 Prgramming in C.pdf

    12/70

    Structured Programming in C

    Cyryx Coll ege Page 12 of 70

    Expression statementAn expression statement consists of any valid C expression and followed by a semicolon.The expression statement is used to evaluate the group expressions.For example,

    x=y; /* the value of y is copies to variable x */a=x+y /* the value of x is added with the value of y and then assigned to the

    variable a */

    Compound Statement:A group of valid C expressions placed within a { and } statement is called a compoundstatement. The individual statement may be of expression statement, compound statementor even a control statement. Note that the compound statement is not completed with asemicolon.

    For example

    {a=b+c;x=x*x;y=a+x;}

    Control StatementThe control statement is used for the programming flow and to check the conditions of thegiven expression or a variable or a constant. The keywords of the control statements arenormally predefined or a reserved word and the programmer may not use as a ordinaryvariable.

    For example,

    1. if (a>b)else

    2. while (condition is becoming true)

    SIMPLE C PROGRAMSuppose we would like to display the message Welcome to CYRYX on the displaymonitor.

    main ( ) /* program heading */{ /* begin */printf(Welcome to CYRYX);} /* end */

    the function main( ) must be placed before the begin statement. It invokes other functionsto perform its job. The {symbol or notation is used as the begin statement. The declaration

  • 8/10/2019 Prgramming in C.pdf

    13/70

    Structured Programming in C

    Cyryx Coll ege Page 13 of 70

    of variables and the type of operations are placed after the begin statement. The endstatement is denoted by the symbol }. In C, the semicolon (;) serves the purpose of astatement terminator rather that a separator.

    The remarks are specified in the following way. Any statement or function is not executable.

    They are ignored by the compiler.

    The declaration for the remark statement:/* this is test */

    type any alphanumeric character or any statements or functions inside the backslashfollowed by the symbol * (multiple operator) and should be repeated for termination.

    /* this is a testprogram byCyryx Computers */

    The above said alpha numeric characters will be ignored by the compiler and this is treated

    as a comment line or remark statement.

    /* main( ){printf(this is a simple test\n); ;}*/

    Any executable statements will also be treated as a remark statement if these statements arefollowed by /* and terminated by the characters */

    There are two advantages of using the remark statement one is easy to understand the

    variable which is used in the source program, the second is easy to debug the variables ortracing the variables by other users.

    The following illustration is the skeleton of a C program structure.program headingbegin

    type of variable declarationstatement of operationresults

    end

    The symbol backslash(\) followed by the lower case n is used for line feed or new line. In C,it is considered as a single character.\n New line or line feed

    We will modify the above program to display the message in two lines.The display should be like this.

    Welcome to CYRYXThe Republic of Maldives

  • 8/10/2019 Prgramming in C.pdf

    14/70

    Structured Programming in C

    Cyryx Coll ege Page 14 of 70

    Modified version of program

    main( ){printf(Welcome to CYRYX);printf(\n);printf(The Republic of Maldives);

    }

    Simple Input StatementIn order to write an interactive C program, we require certain input and output functions orroutines. scanf and printf are two functions used for this purpose.

    SCANF:

    The scanf( ) function is used to read the formatted data items from the keyboard. Theformat is a user defined data items. It can be read or written as defined by a programmer.

    The general form of the scanf() function is

    scanf(control string,argument list);

    The control string is a specified format code to be read from the keyboard and the argumentlist is a user defined variable list. Usually, the argument list of the user defined variable mustinclude the address operator (&) as a prefix to the variable.

    For Example,1. int x,y;

    scanf(%d %d,&x,&y);

    2. float a,b,c;scanf(%f %f %f,&a,&b,&c);

    3. char c, i;scanf(%c %c,&c,&i)

    The complete format code used the scanf( ) function for the various data variables is shown

    below

    Code Meaning%c read a single character%d read a integer%i read a integer%e read a floating point number%f read a floating point number%s read a string

  • 8/10/2019 Prgramming in C.pdf

    15/70

    Structured Programming in C

    Cyryx Coll ege Page 15 of 70

    All the variables used to receive values through scanf( ) must be passed by their addresses.

    This means that all arguments must be pointed to the variables used as arguments.

    scanf(%d,&count);

    Strings are read into character arrays, and the array name without any index is the address ofthe first element of the array. So to read a string into a character array address, use

    scanf(%s ,address)In this case, address is already a pointer and need not be preceded by the & operator.

    The input data items must be separated by spaces, tabs, or nextlines. Punctuations such ascomma, semicolon and the like, do not count as separators. This means that

    scanf(%d %d,&a,&b);can accept 10 20 as input, but fails with 10,20.

    Simple Output Statmentprintf( )

    The printf( ) function is one of the most important useful function to display the formattedoutput data items on the standard output device.

    The general form of printf( ) function is as,

    printf(control strings, argument list)

    Where the control strings are the user defined format code and the argument list is a set ofdata items to be displayed in a proper format as defined by the control strings.

    The complete format code used in the printf( ) function for the various data variables isshown below.

    Code Format%c a single character%d integer value

    %f floating point value%s string of characters%% print a percent sign.

    For exampleprintf(%10.4f\n,value)

    Which displays a number atleast ten character wide with four decimal places.

    The number following the period specifies the maximum field length

  • 8/10/2019 Prgramming in C.pdf

    16/70

    Structured Programming in C

    Cyryx Coll ege Page 16 of 70

    printf(%5.7s\n,name);which displays a string that will be atleast five characters long and does not exceed sevencharacters, If the string is longer the maximum field width, the characters are truncated offthe end.A program to demonstrate the printf( ) function.

    /* using printf function */main ( ){

    char lett;int num;lett=a;num=1234;printf(the letter =%c, the number is %d\n,lett,num);

    }

    Output of the above program

    The letter =a, the number =1234

    A program to demonstrate the assignment of variables.

    main( ){

    int x,y,z; /* x,y,z are integer type of data */x=10; /* assigning the value 10 to the variable x */y=20; /* assigning the value 20 to the variable y */z=x+y; /* ontents of x will be added to y and assigned to z */

    printf(sum of %d and %d is = %d,x,y,z);}

    A program to demonstrate the preincrementer and postincrementer operation inc

    main ( ){int i,j;int x,y;j=I=6;printf(Initial value i=%d\n,i);

    x=i++;printf(x=i++,value of x=%d, and value of i=%d\n,x,i);i=j;y=++i;printf(initial valueI=%d\n,j);printf(y=++I, value of y=%d, and value of i=%d\n,y,i);}

    output of the above program

  • 8/10/2019 Prgramming in C.pdf

    17/70

    Structured Programming in C

    Cyryx Coll ege Page 17 of 70

    initial value i =6x++, value of x =6, and value of i=7initial value i =6y=++i, value of y =7, and value of i=7

    getchar( )

    the getchar ( ) is a function to use as an input statement to read any alphanumeric characterfrom the standard input device usually by the keyboard. Normally C reads character asintegers and to accept a character as a value for a variable of type int.

    Syntax:#include main( ){int ch;________________ch=getchar( );

    ________________}

    putchar( )The putchar( ) is a complementary function of the getchar ( ). It is used to display anyalphanumeric character on the standard output device normally on the screen. Normally, acharacter argument should be placed inside the putchar function. The usual format of theputchar function is shown below.

    The syntax are:#include

    main( ){

    int ch;____________________putchar (ch);____________________

    }

    A program to read a character from the keyboard and display it on the video screen.

    #include main ( ){

    int ch;printf(Enter a character);ch=getchar( );printf(typed character is =);putchar(ch);

  • 8/10/2019 Prgramming in C.pdf

    18/70

    Structured Programming in C

    Cyryx Coll ege Page 18 of 70

    }

    CONTROL STATEMENTSConditional expressionsThe conditional expressions are mainly used for decision making purpose. In the subsequent

    sections, the various structure of the control statements and the expressions are explained.The following statements are used to perform the task of the conditional operations.

    1. if statement2.

    if-else statement3. switch-case statement

    if StatementThe if statement is used to express the conditional expressions. If the given condition is truethen it will execute the statements otherwise it will execute the optional statements. Thebraces { and } are used to group declaration and statements together into a compoundstatement or block. These compound statements or blocks are always considered as a single

    statement. The basic simple structure of the IF statement is shown below:If (expression){statement1;statement ;________________}

    the expression is evaluated and if it is true the statement following the if is executed. Incase the given expression is false, the statement is skipped a nd execution continues with the

    next statement. The expression in c, is any valid expression which is examined to a numericvalue.

    For example,a=20;b=10;if (a>b)printf(largest value = %d,a);

    if the given condition is satisfied, then the computerwill print the message largest value =20 and if not, it will simply skip this statement.

    If-Else StatementHowever, If structure is more commonly used with the following format.if(expression)

    statement1else

    statement2where the else part is optional.

  • 8/10/2019 Prgramming in C.pdf

    19/70

    Structured Programming in C

    Cyryx Coll ege Page 19 of 70

    In this case either of the two statements are executed depending upon the value of theexpression. Statement 1 is executed if the expression returns a true, else statement 2 isexecuted.

    The else part is optional in the if-else structure it sometimes leads to confusion especially

    when an else is omitted from a nested if-else sequence

    For exampleif (i>j) /* wrong */if(a>b)temp =a;elsetemp=b;

    Note that the else statement without braces, leads to confusion like whether it belongs to theinner if statement or outer if. To avoid this ambiguity, always the braces are used torepresent the compound statements.

    if (i>j) /* right */{if(a>b)

    temp =a;}elsetemp=b;

    Normally the braces must be used to clearly indicate the proper association.

    A program to read any two numbers from the keyboard and to display the largest value ofthese two numbers.

    main( ){int x,y;printf(Enter any two numbers \n);scanf(%d %d,&x, &y);if (x>y)printf(largest Value is =%d,a);elseprintf(largest Value is =%d,b);}

    Switch statementThe switch statement is a special multiway decision maker that tests whether an expressionmatches one of the number of constant values, and braces accordingly. The syntax of thesuitable statement is as follows.

  • 8/10/2019 Prgramming in C.pdf

    20/70

    Structured Programming in C

    Cyryx Coll ege Page 20 of 70

    switch (expression)case constant1:

    statement;case constant2:

    statement;

    ____________________________________________case constant n;

    statement;default:

    statement;

    Execution of the switch constant in c follows a different logic. No statements are executeduntil a case has been matched or the default case has been encountered. However. Itcontinues to execute all statements once a case has been matched: irrespective of the fact

    whether those statements belong to the case that has been matched or not.

    As an example consider some program segment written in C.

    switch (input_ch)case R:printf(Red\n);case W:printf(White\n);case B:printf(Blue\n);

    Due to the fall through effect when input_ch is R the Red, white and B lue will be printed,when choice is W, then the white and blue will be printed and when choice is B only Bluewill be printed.

    C offers a method of overcoming this side effect with the help of the BREAK statement.The break statement causes and immediate exit from the switch construct. Because thedefault case include a break statement there. However in general it is advisable to use thebreak statement explicitly whenever exclusion of case statements is required. Thus, thegeneral format of the mutually exclusive switch constant.

    switch (expression)case constant 1:{statement1________________}break;

  • 8/10/2019 Prgramming in C.pdf

    21/70

    Structured Programming in C

    Cyryx Coll ege Page 21 of 70

    case constant 2:{statement1__________________

    }break;case constant n;

    statement 1__________________}break;

    A program to display the name of the day, depending upon the number entered from thekeyboard using swich-case loop.

    main( ){

    int day ;printf(Enter a number between 1 to 3\n);scanf(%d,&day);switch(day){case 1:

    printf (Monday\n);case 2:

    printf(Tuesday\n);

    case 3:printf(Wednesday\n);

    default:printf(Enter the number between 1 to 3\n);

    }}

    Loop StatementsThe loop statements are essential to construct systematic block styled programming. In C,there are multiple ways one may use the control structures using the different types of loopoperations.

    Sometimes the other high level languages may not support all the features of the C controlstructures. The following loop structures are Supported by C,

    1. for loop2. while loop3. do-while loop

  • 8/10/2019 Prgramming in C.pdf

    22/70

    Structured Programming in C

    Cyryx Coll ege Page 22 of 70

    For LoopThe for loop is most commonly used statement in c. This loop consists of three expressions.The first expression is used to initialize the index value, the second expression is used tocheck whether or not the loop is to be continued again and the third expression is used tochange the index value for further iteration.

    The Syntax of the for loop:for (expression1;expression2;expression3)

    Statement;

    In other wordsfor (initial condition;test condition;incrementer or decrementer)

    {statement1statement2---------------------------

    }Where expression 1 is the initialization of the expression or the condition, expression 2 is thecondition checked as long as the given expression is true the loop statement will be repeatedand expression 3 is the incrementer or decrementer to change the index value of the for loopvariable.

    Thus consider a simple example shown below

    sum=0;for (i=1;i

  • 8/10/2019 Prgramming in C.pdf

    23/70

    Structured Programming in C

    Cyryx Coll ege Page 23 of 70

    While LoopThe second type of loop, the while loop, is used when we are not certain that the loop willbe executed. After checking whether the initial condition is true or false and finding it to betrue. Then only while loop will enter into the loop operations.

    The general for of the while loop isFor a single statementWhile (condition)Statement;

    For a block of statementsWhile (condition){

    statement1;statement2;--------------------------

    }

    ExampleA Program to find the sum of the first 100 natural numbers

    main( ){int sum,digit;sum=0;digit=1;while(digit

  • 8/10/2019 Prgramming in C.pdf

    24/70

    Structured Programming in C

    Cyryx Coll ege Page 24 of 70

    The syntax of the do loop:do {

    statement 1;statement 2;

    ---------------;--------------;}while (expression);

    Example:A program to display the numbers from 1 to 100 in steps of 3 by using the do loop.

    main ( ){

    int x;printf(Numbers between 1 to 100 steps of 3 \n);

    x=1;do{printf(%d\t,x);x=x+3;}while (x

  • 8/10/2019 Prgramming in C.pdf

    25/70

    Structured Programming in C

    Cyryx Coll ege Page 25 of 70

    break;case 2:

    printf(Tuesday);break;

    default :

    --------------------------------}

    Break statement using in the for loopfor (i=0;i

  • 8/10/2019 Prgramming in C.pdf

    26/70

    Structured Programming in C

    Cyryx Coll ege Page 26 of 70

    THE GOTO STATEMENTThe goto statement is used to alter the program execution sequence by transfer of control tosome other part of the program.

    The Normal syntax for the goto statement isGoto label;

    Where label is a valid C identifier used to label the destination such that control could betransferred.

    Two ways of using the goto statements in the program are conditional goto anfunconditional goro.

    Unconditional gotoThe unconditional goto statement is used just to transfer the control from one part of theprogram to the other part of without checking any conditions. Normally a good programmer

    wiil not prefer to use the unconditional goto statements in his program because sometimes itmay lead to very complicated problems like never ending process.

    main( ){200;printf(Unconditional goto\n);goto 200;}

    Conditional goto

    The conditional goto is used to transfer the control of execution from one part of theprogram to the other oart under certain conditional cases.

    The following sample program explains the usage of conditional goto statements.

    main( ){int a,b;if (a>b)

    goto output2;else

    goto output 2;output1:printf(largest value =%d\n,a)goto end;

    output2:printf(largest value =%d\n,b);end:

    }

  • 8/10/2019 Prgramming in C.pdf

    27/70

    Structured Programming in C

    Cyryx Coll ege Page 27 of 70

    The goto statement used in for loopThe following program segment shows the use of goto statement in the for loop.

    for (I=0;I

  • 8/10/2019 Prgramming in C.pdf

    28/70

    Structured Programming in C

    Cyryx Coll ege Page 28 of 70

    The general format of the function definition is given below.functiontype functionname(argument1, argument2,..argument n)

    Datatype argument1, argument2;Datatype argument n;

    { body of function-----------------------------------------return something

    }Declaring the type of functionThe function refers to the type of value that the function will return to the calling portion ofthe program. Any of the basic data types such as int, float, char etc. may appear in thefunction declaration.In many compilers, when a function is not to rturn any value it may be declared as type void,which tells C not to save any temporaty space for a value to be sent back to the calling

    program.For example,

    void functionname(.)int functionname(.)float functionname(.)char functionname(.)functionname()

    Function nameThe function name can be anything and the syntax rules to form a function name is same asthe rules of the variables. Normally a function is named to be relevant of the operation, as itis easy to us to keep track of function whenever a transfer of similar functions is used in the

    main program.For example,

    counter( );square( );display_value( );output( );

    Formal argumentsAny variable declared in the body of a function are said to be local to that function. Othervariables not declared either as arguments or in the function body are considered global tothe function and must be defined externally. The storage classes or scope of variables arediscussed subsequently in this chapter.

    For Example, void square(a,b)int a,b; /* a,b are formal arguments */{__________________________}

  • 8/10/2019 Prgramming in C.pdf

    29/70

    Structured Programming in C

    Cyryx Coll ege Page 29 of 70

    A program to display a message Welcome to CYRYX using a functionmain ( ){message( );

    }void message( ) /*function*/{printf(Welcome to CYRYX);}

    the main function invokes the message( ) function, In C, each function is almost like aseparate program. So th formal declaration such as type, begin and end must be used in thefunction also. The controls will be transferred from the main function to the called functionafter it has executed all the statements in the function and the control will be back to thecalling portion of the program.

    RETURN STATEMENT

    The keyword return is used to terminate function and return value to its caller. The returnstatement also be used to exit a function without returning a value. The return statementmay or may not include an expression.

    The general syntax of the return statement are as follows;return;return(expression);

    Return is a full-fledged C statement that can appear anywhere within a function body. Afunction can also have more than one return although it is generally considered better stylefor a function to have a single entrance and a single exit.

    The following are the valid return statements.return;return (54);return(x+y);return(++y);return(++i);return ++j; /* correct but not good style*/

    The return statement terminates the execution of the function and passed control back tothe calling environment.

    For example, the following function declarations are valid.1.

    sum(x,y)int x,y;{

    return(x+y);}

    2 maximum(a,b)float a,b;{

  • 8/10/2019 Prgramming in C.pdf

    30/70

    Structured Programming in C

    Cyryx Coll ege Page 30 of 70

    if (a>b)return (a);elsereturn (b);

    }

    Types of functionsThe user defined functions may be classified into three ways based on the passing of theformal arguments and the usage of the return statement.

    A function is called without taking any formal arguments from calling portion of aprogram and also there is no return statement from the called function.

    A function is called with passing of some formal arguments to the function fromcalling portion of the program but the function does not return back any values tothe calling portion.

    A function is called with passing of some formal arguments to the function fromcalling a portion of a program and returned back some values to the callingenvironment.

    Type 1It is the simplest way of writing a user defined function in C. There is no datacommunication between a calling portion of a program and a called function block. Thefunction is invoked by a calling environment by not feeding any formal arguments and thefunction also does not return back anything to the caller.

    For example,main ( ){

    int x,y;------------------------------message(); /* function is invoked */}message( ){/* body of the function */}

    Type 2

    The second type of writing a user defined function is passing some formal arguments to afunction but the function does not return back any value to the caller. It is a one way datacommunication between a calling portion of the program and the function block.For example,

    main ( ){int x,y;power(x,y); /* function declaration */

  • 8/10/2019 Prgramming in C.pdf

    31/70

    Structured Programming in C

    Cyryx Coll ege Page 31 of 70

    ------------------------}power (x,y)int x,y;

    { /* body of the function *//* no values will be transferred back to the caller*/

    }

    A program to find the square of its number using a function declaration without using thereturn statement.

    /* passing formal arguments and no return statement */

    # include main()

    {int i,max;printf(enter a value for n?\n);scanf(%d,&max);printf(Number Square\n)printf(--------------- -------------\n);for (i=1; i

  • 8/10/2019 Prgramming in C.pdf

    32/70

    Structured Programming in C

    Cyryx Coll ege Page 32 of 70

    temp=output(x,y,ch);}output(a,b,s)int a,b;char s;

    { int value;/* body of the function */return (something);

    }

    A program to find the square of its number us aing a function declaration using the returnstatement.

    /* passing formal argument and return statement */

    #include

    main( ){

    int i,max,temp;printf(enter a value for n?\n);scanf(%d,&max);printf(Number Square \n);printf(------------- ------------);for (i=1 ;i

  • 8/10/2019 Prgramming in C.pdf

    33/70

    Structured Programming in C

    Cyryx Coll ege Page 33 of 70

    ARRAYSArray NotationArray is a collection of identical data objects which are stored in consecutive memorylocations in a common heading or a variable name. In other words, an array is a group or

    table of values referred to by the same variable name. The individual values in an arrayare called elements. Array elements are variables also.

    Arrays are sets of values of the same type, which have a single name followed by anindex, in C, square brackets appear around the index right after the name, with the firstelement referred to by the number. Whenever an array name with an index appears in anexpression, the C compiler assumes that element is an array type.

    Array declarationDeclaring the name and type of an array and setting the number of elements in the arrayis known as dimensional array.

    The array must be declared before one uses it in a C program like other variables. Thearray declaration is defining the type of the array, name of the array, number ofsubscripts in the array and the total number of memory locations to be allocated.

    In general, one dimensional array may be expressed as

    storage_class data_type, array _name[expression]

    Where storage_class referes to the scope of the array variable such as external, static, oran automatic and data_type is used to declare the nature of the data elements stord inthe array like character type, integer and floating point. Array_name is the name of thearray, and expression is used to declare the size of the memory locations to be requiredfor further processing in the program.The storage class is optional, default value are automatic for arrays defined within afunction or a block, and extended for arrays defined outside the function.

    Some valid one dimensional array declaration are shown below:

    int marks[300];char line[90];float coordinate[400];

    The first one has been declared as a mark of 300 integers, the second is a line of 90

    characters, the third is a floating point where numbers of 400 is stores in the array ofcoordinate.

    Array initializationAutomatic arrays cannot be initialized, unlike a automatic variable. However, the externaland a static array can be initialized if desired. The initial values must appear in the orderin which they will be assigned to the individual array elements, enclosed in braces andseparated by commas.

  • 8/10/2019 Prgramming in C.pdf

    34/70

    Structured Programming in C

    Cyryx Coll ege Page 34 of 70

    The general format of the array initialization is shown below:

    Storage_class data_type array_name [expression]={element1, element2,element n};

    Where the storage class is used to declare the scope of the array like static, automctic orexternal data, data_type is a nature o the data elements such as integer, floating, or characteretc. the array_name is used to declare the name of the array, and the elements are placed oneafter another within the braces and finally ends with the semicolon.For example,

    int values[7]={10,11,12,13,14,15,16};float coordinate[5]={0,0.45,-4.0,5.0};char se[2]={M ,F};char name[6] ={S, T, A, L, I, N};

    The results of each array elements are as follows

    values [0] =10values [1] =11values [2] =12values [3] =13values [4] =14values [5] =15values [6] =16

    coordinate[0]=0coordinate[1]=0.45

    coordinate[2]=-0.50coordinate[3]=-4.0coordinate[4]= 5.0

    sex[0]=Msex[1]=F

    name[0]=Sname[1]=Tname[2]=Aname[3]=L

    name[4]=Iname[5]=N

    Note that in C, first element is always placed in 0thplace, it means that the array index startsfrom 0 to n-1, where n is the maximum size of the array declared by the programmer.

    Some un usual way of initializing the array elements are discussed below.For example, if the array elements are not assigned explicitly, initial values will automaticallybe set Zero. Consider the following array declaration.

  • 8/10/2019 Prgramming in C.pdf

    35/70

    Structured Programming in C

    Cyryx Coll ege Page 35 of 70

    int number[5]={1,2,3};The following way the elements will be assigned to the array.

    number[0] =1number[1] =2

    number[2] =3number[3] =0number[4] =0

    A program to initialize a set of numbers in the array and displays onto the standard outputdevice.

    main ( ){

    int a[7]={ 11,12,13,14,15,16,17}int i;printf(Contents of the array \n);for ( i=0; i

  • 8/10/2019 Prgramming in C.pdf

    36/70

  • 8/10/2019 Prgramming in C.pdf

    37/70

    Structured Programming in C

    Cyryx Coll ege Page 37 of 70

    int A[3][3] ={{1,2,3),{4,5,6},{7,8,9}};

    The three values in the first inner pair of braces are assigned to the array elements in the firstrow, the values in the second pair of braces are assigned to the array element in the thesecond row, and so on.

    The elements of the above A array will be assigned as follows.

    A[0][0]=1 A[0][1]=2 A[0][2]=3A[1][0]=4 A[1][1]=5 A[1][2]=6A[2][0]=7 A[2][1]=8 A[2][2]=9

    A program to initialize a set of numbers into a two dimensional array and to display thecontents of the array onto the screen.

    #define r 3#define c 4main ( ){

    int i , j;int a[ r] [c] ={

    {1,2,3,4},{5,6,7,8},{9,10,11,12}

    };

    printf(Contents of the array \n);for (i=0; i

  • 8/10/2019 Prgramming in C.pdf

    38/70

    Structured Programming in C

    Cyryx Coll ege Page 38 of 70

    storage_class character data_type array_name [expression];

    The array name is any valid c identifier, and the expression is a positive integer constant.

    For example,

    char page[40]char sentence[300];

    The basic structure of the character array

    C Y R Y X \0

    Each element of the array is placed in the definite memory space and each element can be

    accessed separately. The array element should end with the NULL character as a referencefor termination of a character array.

    Initializing the character arrayLike integer or floating point array, the character array also can be initialized

    For example,char colour[3]=RED;

    The following way the elements would be assigned to each of the character array position.

    colour[0]=R;

    colour[1]=E;colour[2]=D;

    The character arrays always terminate with the NULL character that is a back slash followedby a letter zero (not lettero or O) andthe computer will treat as a single character.

    The null character will be added automatically by the C compiler provided that enough roomshould be there to accommodate this character

    For example,char name[5]=CYRYX; /* wrong*/

    The following assignment would be for each cell

    name[0]=C;name[1]=Y;name[2]=R;name[3]=Y;name[4]=X;

  • 8/10/2019 Prgramming in C.pdf

    39/70

    Structured Programming in C

    Cyryx Coll ege Page 39 of 70

    The above declaration is wrong because there is no space to keep the null character to thearray as a terminate character and it can be corrected by redefining the above said array like

    char name[6]=CYRYX; /* right*/The following assignment would be for each cell

    name[0]=C;

    name[1]=Y;name[2]=R;name[3]=Y;name[4]=X;name[5]=\0;

    A program to initialize a set of characters in the one dimensional character array and todisplay the contents of the given array.

    #include main( ){

    int i;char names[6]={C, Y, R, Y, X};clrscr( );printf(contents of the array\n);for (i=0; i

  • 8/10/2019 Prgramming in C.pdf

    40/70

    Structured Programming in C

    Cyryx Coll ege Page 40 of 70

    }s[i++] =\0;printf(output from the array\n);for (i=o; s[i] !=\0; i++){

    putchar(s[ i]);}getch( );}

    POINTERSPointer declarationA pointer is a variable which holds the memory address of an another variable. Sometimes,only with the pointer the complex data type can be declared and accessed in an easy way.The pointer has the following advantages.

    - Provides functions which can modify their calling arguments

    - Supports dynamic allocation routines- Improves the efficiency of certain routines

    A pointer contains a memory address. Most commonly, this address is the location ofanother variable where it has been stored in memory. If one variable contains the address ofanother variable, then the first variable is said to point to the second.

    Sometimes, the pointer is the only technique to represent and to access the complex datastructures in an easy way. In C, the pointers are distinct such as integer pointer, floatingpoint number pointer, character pointer etc. The pointer variable consists of two parts suchas the pointer operator and the address operator.

    Pointer operatorA pointer operator can be represented by the combination of * (asterisk) with a variable. Forexample, if the variable is an integer type and also declared * (asterisk) with variable thatmeans the variable is of type pointer to integer . In other words it will be used in theprogram indirectly to access the value of one or more integer variables.

    For example,int *ptr;

    Where ptr is a pointer variable which holds the address of an integer data type.

    The general format of the pointer declaration

    data_type *pointer variable;Where data_type is a type of pointer variable such as integer, character and floating pointnumber variable etc. the pointer variables are any valid C identifiers and the astrisk must bepreceded by the pointer variable.

    The following declarations are all valid

  • 8/10/2019 Prgramming in C.pdf

    41/70

    Structured Programming in C

    Cyryx Coll ege Page 41 of 70

    float * fpointer;double *dpoint;char *mpoint1;

    The base type of the pointer defines which type of variables the pointer is pointing to.Technically, any type of pointer can point anywhere in memory. All pointer arithmetic is

    done relative to its base type. So it is important to declare the pointers correctly. Forexample, a character data items may require to store only a byte(8 bits), and integer mayrequire to store a two bytes(16 bits) , a floating point number may require to store four bytes(32 bits), a double precision number may require eight byte(64 bits). The number of bytes tobe required to store particular data items will vary from machine to machine.

    Address OperatorAn address operator can be represented by the combination of & (Ampersand) with apointer variable. For example, if the pointer variable is an integer type and also declared &with pointer variable that means the variable is of type address of. In other words, it willbe used in the program to indirectly access the value of one or more integer variables. The &is a unary operator that returns the memory address of its operand. A unary operator only

    requires one operand.

    For example,m=&ptr;

    Note that the pointer operator & as on operator that returns the address of the variablefollowing it. Therefore, the preceding assignment statement could be verbalized as mreceives the address of ptr.

    Pointer ExpressionsA pointer is a variable data type, so the general rule to assign its value to pointer is same asany other variable data type. For example,

    int x,y;int *ptr1, *ptr2;

    1. ptr1=&x;The memory address of variable x is assigned to a pointer variable ptr1.2. y= *ptr1;The contents of the pointer variable ptr1 is assigned to the variable y, not the memoryaddress.3. ptr1=&x;

    ptr2=ptr1; /*address of ptr1 is assigned to ptr2*/The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both

    ptr1 and ptr2 will be same because these two pointer variables hold the same address.

    Some invalid pointer declarationint x;int x_pointer;x_pointer=&x;

    Error: pointer declaration must have the prefix of *(unary operator)

  • 8/10/2019 Prgramming in C.pdf

    42/70

    Structured Programming in C

    Cyryx Coll ege Page 42 of 70

    A program to display the contents of the pointer.main( ){

    int x;

    int *ptr;x=10;ptr=&x;printf(x=%d and ptr =%x\n,x,ptr);printf(x=%d andptr=%d\n,x,ptr);

    }In the above program, x is an integer variable and the ptr is declared as the pointer to aninteger. Initially, value 10 is assigned to the integer variable x. the address of the variable x isassigned to the ptr.

    ptr=&x /* address of x is assigned to the variable pointer */ptr=&x /value of x is assigned to the ptr */

    A program to assign a character variable to the pointer and to display the contents of thepointer.

    main( ){

    char x,y;char *pointer;x=c; /*assign character */pointer &x;y=*pointer;

    printf(Value of x=%c\n,x);printf(pointer value=%c\n,y);

    }

    Output of the above programValue of x=cPointer value =c

    A program to display the address and the contents of a pointer variable.#include main( )

    { int x;int *ptr;x=10;ptr=&x;printf(Value of x=%d\n,x);printf(Contents of ptr=%d\n,*ptr);printf(Address of ptr=%d\n,ptr);

    }

  • 8/10/2019 Prgramming in C.pdf

    43/70

    Structured Programming in C

    Cyryx Coll ege Page 43 of 70

    Output of the above programValue of x=10Contents of ptr =10Address of ptr =65488

    MORE ON FUNCTIONSHeader filesA header file contains the definition, global variable declarations and initialization by all thefile in a program. Header files are not compiled separately. The header file can be included inthe C program using the macro definition #include command. The header file can bedeclared as a first line of any c program. For example, the standard input/output (stdio.h)header file contains the macro definitions and the functions needed by the programinput/output statements. The header file can be declared in one of the following ways

    #include or#include stdio.h

    Many C compilers mostly support the following header files.

    Header file name Purposeconio.h console (keyboard and screen) input and outputctype.h character testingdir.h user in working with directoriesfloat.h floating point type characteristicsmath.h math functions

    stdio.h standard i/o macros and functionsstring.h string functionstime.h data and time utilities

    Standard functionsThe standard libraries are used to perform some predefined operations on characters, stringslibraries are called in many different names such as library functions, built in function orpredefined functions. As the term library function indicates, there are a great many of them,and actually they are not a part of the language. Many facilities that are used in C programsare not part of the c language. Most of the C compilers support the following standardlibrary facilities.

    - operations on characters- operations on strings- mathematical operations- storage allocations procedures- input/output operations

  • 8/10/2019 Prgramming in C.pdf

    44/70

    Structured Programming in C

    Cyryx Coll ege Page 44 of 70

    only selected libraries such as character processing, string processing and mathematicaloperations are discussed in this book. These selected libraries are widely available andparticularly useful.

    abs()

    The abs( ) function is used to get the absolute of its arguments. The arguments and the resultare both type int. more precisely, if the argument is nonnegative, then the argument itself isreturned. The abs( ) function cannot be used to get the absolute of long integer data typeand its argument must be of type int.

    # include int abs(x)int x;

    /* using abs(x) */#include #include

    main( ){int i,n,ai;n=10;printf(Number and its absolute value \n);for (i=0;i

  • 8/10/2019 Prgramming in C.pdf

    45/70

    Structured Programming in C

    Cyryx Coll ege Page 45 of 70

    puts (line1);printf(Length of the string =%d\n,nch);

    isalpha( )The isalpha( ) function is used to check whether a given character belongs to an alphabetic

    character, if it is true, it returns non zero otherwise the returned value is zero.

    The alphabetic character : that is, one of the following.

    A.Zaz

    the declaration of the isalpha( ) function is as follows

    #include int isalpha(ch)char ch;

    /* using isalpha( ) */

    #include #include main( ){

    char ch;printf(Enter a character \n);ch=getchar();if (isalpha(ch)>0

    printf(it is an alphabetic character \n);else

    printf(it is a special character \n);}

    islower( )The islower( ) function is used to check whether a given character belongs to a lowercasealphabetic character or not. If it is true, it returns nonzero otherwise the returned value iszero.

    /* using islower */

    #include

    #include main( ){

    char ch;printf(Enter a character \n);ch=getchar( );if (islower (ch>0)

    printf(it is a lowercase alphabetic character\n)else

  • 8/10/2019 Prgramming in C.pdf

    46/70

    Structured Programming in C

    Cyryx Coll ege Page 46 of 70

    printf(It is not a lowercase alphabetic character \n);}

    _tolower ( )

    The _tolower function is used to convert a given uppercase letter into correspondinglowercase letter. The result of _tolower ( ) function is undefined for all other arguments. The_tolower ( ) function is much faster if the programmer can guarantee that the given characteris in fact an uppercase letter.

    The declaration of the _tolower ( ) function is as follows

    #include int _tolower(ch)char ch;

    /* using _tolower ( )*/

    #include #include main( ){

    char ch;printf(enter a character \n);ch=getchar( );ch-_tolower(ch);putchar(ch);

    }

  • 8/10/2019 Prgramming in C.pdf

    47/70

    Structured Programming in C

    Cyryx Coll ege Page 47 of 70

    STRUCTURES AND UNIONS

    The declaration of StructureIn C, collection of heterogeneous (different) types of data can be grouped to form astructure. When this is done, the entire collection can be referred to by a structure name. In

    addition, the individual components which are called fields or members can be accessed andprocessed separately.

    The structure can be represented graphically as follows

    Structure

    There are two important distinction between arrays and structures. To start with, theelements of an array must all have the same type. In a structure, the components or fieldsmay have different data types, Next, a component of an array is referred to by its position inthe array whereas each component of a structure has a unique name. Structures and arraysare similar in that both must be defined with a finite number of components.

    The symbolic representation of the structure is as follows:

    struct user_defined_name{

    member 1;member 2;--------------------------member n;};

    name

    member 1

    member 2

    member 3

    member n

  • 8/10/2019 Prgramming in C.pdf

    48/70

    Structured Programming in C

    Cyryx Coll ege Page 48 of 70

    A Structure definition is specified by the keyword struct. This is followed by a user definedname surrounded by braces, which describes the members of the structure. A member of astructure is

    The general format of a structure declaration is

    storage_class struct user_defined_name{data_type member1;data_type member 2;________________________________data_type member n;};

    The storage class is an optional. The keyword struct and the braces are required. The userdefined name is usually used, but there are situations in which it is not required. The datatypw and members are any valid C data objects such as short integer, float, char. Once the

    structure has been declared, it may be used.

    For example, todays data can be arranged in the following formint day;int month;int year;

    The date is a structure consisting of three members and all the members are of same datatype.

    struct date {

    int day;int month;int year;};

    the structure can be represented symbolically as follows:struct

    date

    day

    month

    year

  • 8/10/2019 Prgramming in C.pdf

    49/70

    Structured Programming in C

    Cyryx Coll ege Page 49 of 70

    The students particulars can be placed like this Roll no, age,sex,height and weight thestructure declaration can be done as follows

    struct student

    {int rollno;int age;int sex;int height;int weight;};

    Each member of a structure variable is specified by the following variable name with aperiod and the member name. The period is structure member operator, which we shallhereafter to simply as the period operator. For example, the date is a structure and consistsof three members and it would be referred to in a program as

    struct date{

    int day ;int month ;int year;

    };

    struct date today;today.day;today.month;today.year;

    Assigning values to the member of the structure

    The todays date may be assigned as followstoday.day=20;today.month=10;today.year=2002;

    When a structure member is named using the period operator, the variable name andmember name are still separate identifiers. For example,

    The variable today.year exceeds more than eight characters but in the structure, each one is aseparate identifier so the truncation will not take place for both.

    The C compiler will not read or write an entire structure as a single command like this

    scanf(%s,today); /* wrong */printf(%s,today); /* wrong */

  • 8/10/2019 Prgramming in C.pdf

    50/70

    Structured Programming in C

    Cyryx Coll ege Page 50 of 70

    It will read or write the members of a structure separately as follows

    /* reading a structure */

    scanf(%d, &today.day);

    scanf(%d, &today.month);scanf(%d, &today.year);

    /*displaying on the screen */

    printf(%d,today.day);printf(%d,today.month);printf(%d,today.year);

    A program to assign some values to the member of a structure and to display the structureon the screen.

    #include main ( ){

    struct sample{int x;float y;};

    struct sample a;a.x=10;

    a.y=20.20;printf(Contents of X and Y \n);printf(%d\t %0.2f\n,a.x,a.y);

    }

    The structure tagIt is possible to define a structure variable name in the structure type declaration itself.

    The general format of the structure tag declaration isstorage_class struct user_defined_name

    {data_type member 1;data_type member 2;____________________________data_type member n;

  • 8/10/2019 Prgramming in C.pdf

    51/70

    Structured Programming in C

    Cyryx Coll ege Page 51 of 70

    For example, the following structure declaration of a,b could be written as

    struct student{int rollno;

    int age;char sex;float height;float weight;} a,b;

    Now a, b are the two structure variables to be of a type struct student.A program to assign some values to the member of a structure and to display the structureon to the screen the structure tag.

    # include main( ){

    struct sample{int x;float y;} a;

    a.x=10;a.y=20.20;printf (Contents of X and ya \n);printf(%d\t %0.2f\t,a.x,a.y);}

    Initializing a StructureA structure can be initialized as the way of another data type in C. In keeping with the arrayanalogy, a structure must be either static or external.

    For example,Students particularsrollno,ageaexheightweight

    student ={91001,25,M,180.67,50.30};

    The C compiler will assign the following ways to each of the fieldsroll no = 91001age = 25sex =Mheight =180.67weight =20.30

  • 8/10/2019 Prgramming in C.pdf

    52/70

    Structured Programming in C

    Cyryx Coll ege Page 52 of 70

    A program to initialize the member of a structure and to display the contents of the structureon to a screen.

    #include main ( )

    { struct student{int rollno;int age;char sex;float height;float weight;};

    static struct student class={9100,24,M,167.8,40.0};printf(Contents of structure \n);printf(Rollno:%d\n,class.rollno);

    printf(Age :%d\n,class.age);printf(Sex:%c\n,class.sex);printf(Height:0.2f\n,class.height);printf(weight:0.2f\n,class.weight);

    }

    Other declarationA field or member of a structure is a unique name fot the particulars structure. The samefield or member name may be given particular structures with different data types. The ccompiler will treat each structure member as a separate variable reserves the memory spaceaccording to their data type of the member.

    For example, the following declaration is valid

    struct first{int a;float b;char c;};

    stctuc second{

    char a;int b;float c;};

    In the above two structures, namely, the first and second have three members and all threehave different data types. But as the names of the members are same, it is advisable to usedifferent structures so that no confusion arises while using them in the program. Here, it isexplained the different usages and declaration of the C compiler. In a practical situation, thenames of members should be distinct.

  • 8/10/2019 Prgramming in C.pdf

    53/70

    Structured Programming in C

    Cyryx Coll ege Page 53 of 70

    A program to declare the same for the different data types in the two structures and toassign some values into the corresponding fields and to display the contents of thestructures.

    #includemain ( ){

    struct first{

    int a;float b;float c;

    };struct second{

    char a;

    int b;float c;

    };

    struct first one;struct second two;one.a=23;one.b=11.89;one.c=F;two.a=Mtwo.b=5;

    two.c=-45.78;printf(First structure\n);printf(%d\t %0.2f\t%2c\n,one.a,one.b,one.c);printf(Second structure \n);printf(%2c\t %d\t %0.2f\n,two.a,two.b,two.c);

    }

    Output of the above programFirst structure23 11.89 FSecond structure

    M 5 -45.78

  • 8/10/2019 Prgramming in C.pdf

    54/70

    Structured Programming in C

    Cyryx Coll ege Page 54 of 70

    UnionsIt is well known that a structure is a heterogeneous data type, which allows to pack togetherdifferent types of data values as a single unit. Union is also similar to a structure data typebut the way the data are stored and retrieved is different.

    Union stores values of different types in a single location. A union may contain one of manyvalues (as long as only one is stored at a time). The declaration and the usage of the union isthe same as its structures. The union only holds a value for one data type. If a newassignment is made, the previous value is forgotten.

    The symbolic representation of a union declaration is as follows:

    union user_defined_name{

    member 1;member 2;

    ________;________;member n:};

    The keyword union is used to declare the union data type. This is followed by a user-definedname surrounded by braces which describes the member of the union.

    The general format of the union is :storage_class union user_defined_name{

    data type member 1;data type member 2;_______________;_______________;data type member n;};

    The storage class is an optional. The keyword union and the braces are required. The datatype and members are any valid C data objects such as short integer, float, char.

    A union may be a member of structure, and the structure may be a member of a union.Moreover structures and unions may be freely mixed with arrays.

    The union tagIt is permissible in C to define a union data type without declaring a variable. This is called asa union tag. The general format of the union tag declaration is a sfollows.

  • 8/10/2019 Prgramming in C.pdf

    55/70

    Structured Programming in C

    Cyryx Coll ege Page 55 of 70

    union user_defined_name{data_type member 1;data_type member 2;_________________

    _________________data_type member n;} variable1, variable2,. Variable n;

    For example,union sample {int first;float second;char third;} one, two;

    Where one and two are the union variables similar data size of the sample.

    Processing with unionThe period operator is used to in between the union variable name and the field name. Oncewe have declared a union type, one can declare variables with that type.

    union value{int c;double d;};union value x;

    As with structures we use the dot operator to access a unions individual fields. To assign tothe integer field of x we use

    x.c;y.d;

    For example, the individual fields of a union can be assigned as follows.x.c=12;y.d=-123.456;

    A program to initialize the member of a union and to display the contents of the uion.

    #includemain( ){

    union value{

    int i;float f;};

    union value x;x.i=10;x.f=-1456.45;

    printf(First member %d\n,x.i);printf(Second member %0.2f\n,x.f);

    }

  • 8/10/2019 Prgramming in C.pdf

    56/70

    Structured Programming in C

    Cyryx Coll ege Page 56 of 70

    Output of the above programFirst member 3686Second member1456.45

    In the above program, the union is declared to consist two members such as an int and afloat. Only the float values are stored and displayed correctly and the integer values aredisplayed wrongly. The union only holds a value for one data type of the larger storage oftheir members.

    A program to declare a member of a union as a structure data type and to display thecontents of the union.

    #include main( ){

    struct date{

    int day;int month;int year;};

    union value{int i;float f;struct date bdate;};

    union value x;x.i=10;

    x.f=-1456.45x.bdate .day =12;x.bdate.month=7;x.bdate.year=2002;

    printf(First Member %d\n,x.i);printf(Second member %0.2f\n,x.f);printf(structure\n);printf(%d /%d /%d\n,x.bdate.day,x.bdate.month,x.bdate.year);

    }

    Output of the above program

    First member 12Second member 0.00Structure:12/07/2002

  • 8/10/2019 Prgramming in C.pdf

    57/70

    Structured Programming in C

    Cyryx Coll ege Page 57 of 70

    DATA FILE OPERATIONSFile is a collection of data or set of characters may be a text or program. Basically there atetwo types of files used in the C languages; sequential file and random access file. Thesequential files are very easy to create then random access files. The data or text will bestored or read back sequentially. In the random access file, the data can be accessed and

    processed randomly.

    REVIEW OF INPUT/OUTPUT FUNCTIONSThe C language supports very good portable features through it does not have manyinternally built input/output facilities because the standard library gives all the salientfeatures such as character I/O, string I/, and file I/O. The features of the standardfunctions may differ from one C compiler version to the other.

    Character I/Ogetchar( )putchar( )getch( )putch( )

    getchar( )The getchar ( ) is a function to use as an input statement to read any alphanumeric characterfrom the standard input device usually by the keyboard. Normally C reads character asinteger and to accept a character as a value for a variable of type integer.

    putchar( )The putchar( ) is a complementary function of the getchar( ). It is used to display anyalphanumeric character on the standard output device normally on the screen. Normally, acharacter argument should be placed inside the puthar( ) function.

    A Program to read a character from the keyboard and to display in on the screen.

    /* using getchar() and putchar()*/#includemain( ){

    int ch;printf(Enter a character);ch=getchar( ); /* to get input character */putchar(ch); /* to display it on the standard output */

    }

    Whenever single characters are to be read or written in a C program, getchar( ) and putchar() are used most ofter. These functions actually dont exist on the library. Instead, calls togetchar( ) and putchar( ) are replaced by calls to getc( ) from stdin and to putc( ) to stdout bythe preprocessor.

  • 8/10/2019 Prgramming in C.pdf

    58/70

    Structured Programming in C

    Cyryx Coll ege Page 58 of 70

    getch( )The getch( ) is a function stdio.h library to read any alphanumeric character from thestandard device. There are two important differences betweer getchar( ) and getch( ). First,when getchar( ) is used, it continues to access the keyboard until the carriage return key is

    pressed, even though only the first character typed is returned to the program while getch( )stops accessing the keyboard as soon as any key is pressed. Second, getchar( ) echoes thecharacter typed on to the screen while getch( ) does not. These differences contribute tomaking interactions using getch( ) much faster than those using getchar( ).

    putch( )The putch( ) is a function of stdio.h library to display any alphanumeric character on to thestandard device normally on the screen.

    A program to read a character from the keyboard and to display it on to the screen using thegetchar( ), getch( ),putchar( ), putch().

    /* using getch() and putch() */

    main( ){

    int ch;printf(Enter a character and press carriage return \n);ch=getchar( );printf(Typed character is : );putchar(ch);printf(\n Now type a character \n);ch=getch( );

    pintf(Typed character is :);putch(ch);printf(\n);

    }

    The above program illustrates character I/O using getchar( ), putchar( ), getch( ), and putch(). The standard input/output library must be included in the program wheneverone uses these input and output functions.

    String I/Ogets( )

    puts( )sscanf( )sprintf( )

    In the above section, we discussed about the character input/output facilities of the stdio.h.In this section, we will see the string handling features of the C language. It is easy to read orwrite strings of characters with gets( ) and puts( ).

  • 8/10/2019 Prgramming in C.pdf

    59/70

    Structured Programming in C

    Cyryx Coll ege Page 59 of 70

    gets( )The gets( ) function is used to read a set of alphanumeric characters from stdin until acarriage return key is pressed and places a NULL in memory and rturns.

    The general format of the gets ( ) function is :gets(variable name);

    The following program segment illustrates the usage of gets( )

    #include main( ){

    char name[20];gets(name);

    }

    puts( )The puts( ) function continues to send characters to the stdout from memory that is fromthe array we declare until it run into the NULL when it sends a newline and returns. Each ofthese functions require the address of a character array as an argument. When a characterarray for a string is declared it must be having space to accommodate for the NULLcharacter.

    The general format of the puts( ) function is:puts(variable name);

    The following program segment illustrates the usage of gets( )

    # include main( ){

    char name[20];gets(name);puts(name);

    }

    sscanf( )The sscanf( ) function is used to read the formatted data like scanf function and the onlydifference is that instead of keyboard, it reads from memory that is from he array we declare.

    The general format of the sscanf function is:

    sscanf(memory name, control charaters, variable names);

  • 8/10/2019 Prgramming in C.pdf

    60/70

    Structured Programming in C

    Cyryx Coll ege Page 60 of 70

    The following program illustrates the usage of the sscanf( ) function.

    #include main( )

    { char name[80];int i,j;float a,b;gets(name);sscanf(name, %d %d %f %f\n,I,j,a,b);

    }

    sprintf( )The sprintf( ) function is used to write the formatted data like printf( ) function and thedifference is that it writes to an array in memory instead of screen. Each of these functionsrequires the address of a character array as an argument.

    The general format of the sprintf function is:sprintf(memory name, control characters, variable names);

    The following program segment illustrates the usage of the sprintf( ) function.

    #include {

    char name[80];int i.j;float a,b;

    gets(name);sprintf(name, %d %d %f %f\n, i, j,a,b);

    }

    A program to illustrate the usage of gets( ),puts( ), sscanf( ) and sprintf( ) for string input andoutput operations./* using gets, puts, sscanf, sprintf () */# include main( ){

    int x;

    float y;char a[40], line1[40], line 2[40];printf(Type an integer, floating point value \n);printf(and a string\n);gets(line 1);printf(typed characters \n);puts (line 1);sscanf(line 2,%d %f %s,&x.&y,&a);printf(reading from the array line 1 \n);

  • 8/10/2019 Prgramming in C.pdf

    61/70

    Structured Programming in C

    Cyryx Coll ege Page 61 of 70

    printf(%d %6.2f %s \n,x,y,a);sprintf(line2, typed:[%6d][%6.2f][%s]\n,x,y,a);printf(Reading from the array line 2\n);puts (line2);

    }

    Out put of the above program

    type an integer, floating point valueand a string12 44.667 cyryx

    typed characters12 44.667 cyryxreading from the array line 112 44.67 cyryxreading from the array line 2

    typed :[12] [44.67] [cyryx]

    The above program performs sting i/o using several functions. First a string is read andwritten using gets( ) and puts( ), after which the string is scanned for input using sscanf( )and results are output another string using sprintf( ), finally, the output string is printed usingputs( ).

    Opening and closing filesfopen( )fclose( )

    fopen( )The fopen( ) function is used to open a specified file on the diskette. It has two stringarguments, which represent the name of the file and the type of I/O to be performed. Thereare three- read, write and append represented by the strings r, w, and a respectively.Some C compilers may include rb and wb types of I/O where the normal way of readingand writing characters in ASCII rather than binary. The rb means read binary file andwb means write into the binary file.

    The general format of the file open command is as follows

    fptr=fopen (filename,mode);

    Where fptr is a pointer to a type FILE, filename is the system file name and is acharacter string and mode is the type of operations to be performed.

    The mode can be one of the types shown in the following.

  • 8/10/2019 Prgramming in C.pdf

    62/70

    Structured Programming in C

    Cyryx Coll ege Page 62 of 70

    File names

    Mode Descriptionw means write to the file, if the file name exists already on the diskette, then it

    deleted and a new fill will be created.

    r means read from a file. If the file does not exist, error is returned,.ie. NULLis returned as the value of fopen.

    a means append a file. New data are added to the end of the file.

    r+ means open an existing file for updating

    w+ means create new file for reading and writing

    a+ means open for append, create if does not already exists.

    fclose ( )The fclose( ) function is used to close the file for re usage and the file pointer will be unlikedfrom the system name. Note that the argument for fclose is a file pointer not a file name.

    fclose (fptr);

    The fclose( ) function returns 0 if the close operation is successful, otherwise, it returns1. itis good practice to check for successful close operation because portion of a file can be lostif it is not closed properly.

    SIMPLE FILE OPERATIONS

    File I/O1. Character I/O2. String I/O3. Word I/O4. Formatted I/O

    Character I/OSimilar to ordinary way of character I/O handling in C, the file also can access to read andwrite a character data type. The data elements such as characters are stored in Ascii format.

    Sometimes, it is called the stream file processing; for the data elements are stored insequential format and the characters are sent, while reading one by one. The followingfunctions are used to handle the character I/O data types.

    getch( fptr)putc(ch,fptr)fgetc(fptr)fputc(ch,fptr)

  • 8/10/2019 Prgramming in C.pdf

    63/70

    Structured Programming in C

    Cyryx Coll ege Page 63 of 70

    getc( )The getc( ) function is used to read a single character from a given file, and returns the valueof the end of file (EOF) or an error is encountered.The general format of the getc( ) function is as follows

    ch=getc(fptr)

    where fptr is a file pointer of the file, and ch is a variable receive the character.The getc() function is normally in conditional loops to read a set of character from a file.

    The following program segment continues to read a set of characters until an end of filecharacters or an error is encountered.#include main( ){

    FILE *in_file;char name[20];int ch;printf(file name?\n);

    scanf(%s,name);in_file =open(s,r);while ((ch-getch(in_file)) !=EOF)______________________________________

    A program to read a file and display the contents of the file on to the screen using getc( )function# include main ( ){

    FILE *in_file;char s[20];int c;printf(Enter the file name :\n);scanf(%s,s);if ((in_file =fopen (s,r))=NULL)

    {printf(No such a file exists\n);exit( );}

    else

    { while ((c=getc(in_file))!=EOF){purchar;}

    }fclose (in_file)

    }

  • 8/10/2019 Prgramming in C.pdf

    64/70

    Structured Programming in C

    Cyryx Coll ege Page 64 of 70

    fgetc( )The fgetc( ) is also used to read a single character from a given file and returns the value eofthe end of the file (EOF) or an error is encountered. The getc( ) is a macro while fgetc( ) istrue function in the stdio.h library. The operations are otherwise same.

    The general format of the fgetc( ) function is as follows

    ch=fgetc( fptr)where fptr is a file pointer of the file, and ch is a variable receive the character.

    A program to read a file and to display the contents of the file on to the screen using fgetc( )function.

    #include main( ){

    FILE *in_file;char s[20];int c;printf(Enter the file name ?\n);scanf(%s,s);if ((in_file=fopen (s,r))==NULL){

    printf(No such a file exists);exit( );

    }else

    {while ((c-fgetc(in_file))!=EOF){putchar ( c );}

    }fclose (in_file);}

    Formatted I/OThe stdio.h library provides all types data handling features for the requirement of a

    programmer. Sometimes one may be required to store and retrieve only formatted data. Theformatted that can also be processed with a file handling. The following functions are usedto access and process the formatted data.

    fscanf( )fprintf( )

  • 8/10/2019 Prgramming in C.pdf

    65/70

    Structured Programming in C

    Cyryx Coll ege Page 65 of 70

    fscanf( )The fscanf( ) function is used to read a formatted data from a specified file. The controlstring to read a format data is same as the scanf( ) function. The scanf( ) function reads fromthe keyboard while fscanf( ) reads from a given file.

    The general syntax of the fscanf( ) function is as follows:

    fscanf(fptr,controlstring,&list)

    Where fptr is a file pointer to receive a formatted data, control string is a differentformat commands such as %d %f etc and list is a variable parameter list to be readfrom the specified file and normally the list is used along with address operator.

    The following program segment illustrates the fscanf( ) function:

    #include main( )

    {FILE *in_file;int x,y;in_file=fopen(name,r);________________________while ((fscanf(in_file, %d %d ,&x,&y))!=EOF){________________________

    }

    fprintf( )The fprintf( ) function is used to write a formatted data into a given file. The printf( )function is used to write or display the formatted data on the screen while the fprintf( ) isused to write a specified file. The control string is same for both printf and fprintf( )functions.

    The general format of the fprintf( ) is as follows:

    fprintf(fptr,control string,list)

    where fptr is a file pointer to write a formatted data, control string is a formatcommand such as %d, %c, %f etc and list is the variable list to be written on to thefile.

  • 8/10/2019 Prgramming in C.pdf

    66/70

    Structured Programming in C

    Cyryx Coll ege Page 66 of 70

    The following program illustrates the usafe of fprintf( )#include main( ){

    FILE *in_file;int x,y;in_file=fopen(name,w);____________________________fprintf(in_file,%d %d\n,x,y);____________________________fclose(in_file)

    }

    A program to store the number and its square from 0 to 10 on a given file and to read the

    same file and to display the contents of the file on to the screen.

    /* using fprintf( ) and fscanf( ) */# include main( ){

    FILE *out_file;int i,n;int x,y;char s[20];printf(Enter a file name for writing \n);

    scanf(%s,s);if((out_file=fopen(name,w))==NULL){printf(Error in writing\n);exit( );}

    else{n=10;i=0;printf(number square \n);

    printf(_____________\n);while (i

  • 8/10/2019 Prgramming in C.pdf

    67/70

    Structured Programming in C

    Cyryx Coll ege Page 67 of 70

    }printf(Enter a file name for reading\n);scanf(%s,s);if((out_file=fopen(name,r))=NULL)

    {

    printf(No such a file exists\n);exit( );}

    else{printf(Reading from the file \n);printf(Number Square \n);printf(__________________\n);

    while ((fscanf(out_file,%d\t %d\n,&x,&y)) != EOF)printf(%d \t %d \n,x,y);fclose (out_file);

    }

    }

    Structures and file operationsThe fscanf( ) and fprintf( ) are used to read and write a structure to the file respectively.

    The following program segment illustrates the oprations of structures and fprintf( )

    #include main ( ){

    FILE *out_file;struct database{

    char name[20];int age;

    };struct database person;--------------------------------------------------fprintf(pit_file,%s\t,person.name);fprintf(out_file,%d\n,person.age);

    ______________________________fclose (out_file);

    }

  • 8/10/2019 Prgramming in C.pdf

    68/70

    Structured Programming in C

    Cyryx Coll ege Page 68 of 70

    A program to read a set of structures elements from the keyboard and to store it on aspecified file and again to read the same file and to display the contents of the file.

    /* strucurs and file operations */#include

    FILE *in_file;struct student{

    char name[20];int rollno;float weight;float height;};

    struct student a[20];int n;

    char s[20];

    main( ){

    int ch;menu( )while ((ch=getchar( ))!=q){

    menu( );switch(ch){

    case a;appending( );

    break;case r

    reading( );break

    case wsaving( );break;}

    }}

    menu( ){printf(a-appending a record\n);printf(r-reading from the file\n);printf(w-writing to the file\n);printf(q-quit\n);

    }

  • 8/10/2019 Prgramming in C.pdf

    69/70

    Structured Programming in C

    Cyryx Coll ege Page 69 of 70

    appending( ){

    int i;printf(How many students?\n);scanf(%d,&n);

    for (i=0; i

  • 8/10/2019 Prgramming in C.pdf

    70/70

    Structured Programming in C

    reading( ){

    int i;printf(File Name:\n);scanf(%s,s);

    if((in_file=fopen(s,r))==NULL){printf(No such a file exists\n);exit( );}

    else{i=0;

    while (fscanf(in_file,%s %d %f %f\n,&a[i].name, &a[i].rollno,&a[i].height,&a[i].weight );i++;}n=i;

    printf(Reading from the file \n);printf(Name Roll_No Height Weight \n);printf(_____ _______ _____ ______ \n);for (i=0; i