Unit‐II
DATA INPUT AND OUTPUT
              Reading processing and writing of data are the three essential functions of a
computer program all input and output operations are carried out through a function such as
scanf and printf these function are known as the standard I/o library
                       #include <studio.h>
The file name studio.h is an abberivation for standard input – output header file the header
file tells the compiler to search for a file named stdio.h and places its contents at his poits in
the program the content of the header file become part of the source code when it is complied
Reading a charcter :
                The simplest input/output operations is reading a charcter from the standard
input (keyword) and weritting is to be the standard output unit (screen) reading a single
charcter can be done by using getchar function
Syntax : variable name = getchar();
Variable name is a valid C that has been described as char data type
When its statement is encounted complier waits until a key is pressed and then assigns a
charcter as a value to getchar function
     EX
                 Char course;
                 Course =getchar ();
Writng a charctrer :
Putchar() functions is used for writing one charcter at a time to the terminal
Syntax : putchar (variables name);
When variables name is atype char variable containg a charcter
Ex
     Ans=’y’;
     Putchar( ans );
2 formatted input
It refer to an input data that has been arranged in a particular format
Syntax :
Scanf (“control strings” ,&arg1,&arg2…………..,&argn);
      Controls string specifies the field format in which the data is to be entered
      Argunments arg1, arg2….argn specify the address of location where the data is stored
      Control strings and argunments are seprated by commas
      Controls srring may include
       *field specification consisting of conversion charcters % a data type charcter (or)type
       specified and an optional number , specifying field with
       * blanks tabs ot newline
      Blanks and new lines are ignored
      The field width specified is optional
   A) INPUTING INTERGER NUMBER:
    The field specification for reading on integer number is
      %WD
    The percentage sign indication that is a conversion specification follows
    W is a integer number that specifies the field width of the number to be read
    D is known as data type charcter
      EX scanf (“%d”,d”&num );
       Data; 100
      The value is 100 is assigned to num
      Input data items must be seprated by spaces tabs or newline
      Puinctuation marks do not count as separator
      As input field may be skipped by specifying ‘*’in the place of field with
       Ex :
       Scanf(“%d%*d%d”,&a,&B):
        Will assign the data 123 456 738
       A=123
       456 is skipped because of*;
       B=738
      If we enter floating point value instead of an integer the fraction part may be skipped
       away and also scanf may skip further input reading
       INPUTING REAL NUMBERS
      Field width of real numbers need not be specified
      Scanf reads real number using simple specification % for both decimal point notation
       and expontential notation
       Ex
       Scanf (%f%f%”,&x&y.&z):
       With the input data
       475.89                    48.2 e-1           678
       Will assign the value 475.89 to x .4821` to y , 678 0to z
      Input fields specifications may be separators by any arbitrary blank spaces
      If the number to be read is of double of then the specification should be % 1f
      A number may be skipped using %*f specification
Inputting charcter string
      Scanf function can input stringd containing more than one charcter
      The field specification for reading a charcter strings
         %ws or %wc
      %c way be used to read a single charcter when the charcter when the argunments is a
       pointer to a char variable
       Commonly used scanf format codes
       Formatted output
       General form of printf statement
       Printf ( “control strings”,args1 , args2,…..argn);
      Control string consists of three types
       *charcters will be printed on the screen as they appear
       * format specification
       * escape sequences
* control string indicates how may argunments follows and what their types are
    Format
                %w.p type_ specifier
      Where w is an interger number that specifies the total number of columns for output
       value
      P is an integer number that specifies the number of digits to the right of the decimal
       point
      Both p and w are optional
       Output of integer number :
        The syntax for an integer number
                              %WD
      Where w specifies the minimum field with for the output
      If a number is greater than the specifies field width it will be printed in full
      D specifies that the value to be printed is an integer
       Ex
       Format                               output
       1. Printf(“%d”,9876);                 9876
       2. Printf(“%6d”.9876);                9876
       3. Printf(“%6d”,8976);                9876
      Left justified can be achived by piecing a minus sign directly after the % charcter
      It is also possible to pad with zeros the leading blanks by placing a zero before thr
       field width specified
                  Printf(“%06d”.9876);               009876
      Long integer may be printed by specified id the place of d where 1 denotes the long
       qualifier
       OUTPUT OF REAL NUMBER
      Output of real number may be displayed in decimal function
                         %w.pf
      W-> indicates the minimum number of positions that are to be used for the display of
       the value
      P-> the number of digit to be displayed after the decimal point
      The value .when displayed is rounded to p decimals and printed right justified in the
       first of w columns
      The negative numbers will be printed with a minus sign
      The default precisions is 6 decimal places
                %w.p.c
      It takes the form [-] m .nnnne{+/-}xx
      Padding the loading blanks with zeros and printed with left-justified is done by
       introducing a zero or minus before the field width specifier
      Some system supports runtime field specification
               Printf (“%*.*f”,width ,percioucs ,number );
      Both field width and percious are given as argunments
                Printf (“%*.*f”.7,2 number);
      Both field width and percious are given as argunments
         Printf (“%*.*f”,7.2 number);
         Is equivanlent to printf (%7.2f”number);
   Format                             output
   Printf(:%7.4 f”,y)                  98.7654
   Printf(“% 7.2 f”,y)                   98.77
   Printf (“%72”,y)                      98.77
   Printing a single charcter
      A single charcter can be displayed in a desired position by using the format
                %wc
      Charcter will be displayed right justification in the field w columns
      The default value for w is 1 (one)
PRINTING OF STRING
   Syntax
              %w.ps
Where w specifies the field width for display and p instructs that only the first p charcter of
strings are displayed the display is right justified
CONTROL STATEMENT:
C language processes some decision making capabilities and support the following statement
knowns as control or decision making statement
      If statement
      Switch statement
      Conditional operartor
      Goto statement
DECISION MAKING WITH IF STATEMENT
      The if statement is a powerful decision making statement
      It is used to control the flow of execution of statement
      If it is two ways decision making statement and it is used in conjunction with an
       expression
       SYNTAX
                 If (test.expression)
      It allows the computer to calculate the first once then depending on the value of the
       expression it transfer the control to a particular statement
      Test expression has two parts to follow one true condition and the other for the false
       condition
    SIMPLE IF STATEMENT
    SYNTAX
                  If (test expression)
                  {
                               Statement_blocks:
                   }
                      Statement _x ;
   Statement_ block may be a single statement or a group of statement
   If the test expression is true the statement blocks will be executed
   If the test expression is false the statement block will be skipped and the execution
    jump into to the statement x
   When the condition is true both the statement blocks and the statement—x are
    executed is sequence
    The program tests the type of category of the student if the student belongs to the
    sports category then additional bonus marks are added to the marks
    IF..ELSE STATEMENT
    Syntax
             If test (expression)
    {
           True-block statement
    }
    Else
    {
           False-block statement
    }
    Statement -x;
   If the test expression is true ,then the statement are executed
   Otherwise,false blocks statements are expressed
   In either case,either true -blocks or false -blocks will be executed not both
   In both cases the control is transferred subsequently to statement -x
    Ex:
          Counting the number of girls and boys in the class
          For boys code=1
          For girls code=2
    If (code==1)
            Boy=boy+1;
     Else
            Girl =girl+1;
         Statement -x ;
   If the code is equal to 1,the statement boy=boy+1 is executed and the control is
    transferred to statement -x after skipping the else part
   If the code is not equal to 1 the statement boy= boy+1 is skipped and the else part
    girls =girls in 1+1 is executed before the control reaches the statement
    NESTED IF-ELSE STATEMENT
   When a series of decisions are involved more than one if else statement is used
   If the condition 1 is false the statement -3 will be executed ;otherwise it continues to
    perform the second test
   If the condtion-2 is true the statement-1 will be evaluated otherwise the statement -2
    will be evaluated and then the control is transferred to the statement x
EX :
       If (gender==”f”
{
If (bal>5000)
        Bonus=0.05*sal;
    Else
       Bonus =0.02*sal;
}
Else
{
       Bonus =0.02*sal;
}
Sal=sal =bonus :
ELSE IF LADDER
             C also permits decisions statements a multiple decisions is a chain of its in
which the statement associated with each else is an if
SYNTAX
        If (condition-1)
              Statement -1;
    Else if (condition-2)
          Statement -2
         Else if (condition 3)
               Statement-3;
    Else if (condition )
              Statement -n;
       Else
                Default statement
          Statement-x;
This is known as else if ladder the condition are evaluated from the top to down if say one
conditions is true the statement asscicated with its executed and then the control is transferred
to the statement x remaining statement is skipped when all the condition becomes false then
the final else containing default statement will be executed
SWITCH STATEMENT
     C has a built in multi way decision statement known as switch
     Switch statement tests the value of a given variable against a list of case values and
      when a match is found a block of statement associcated with that case is executed
      Syntax
           Switch (expression)
      {
          Case value -1;
               Block-1;
               Break ;
         Case value -2 ;
              Block -2;
                Break;
          Default
                     Default- block
                      Break;
      }
     The expression is an interger expression or charcter
     Value -1,value-2 are constants or contants expression are known as case labels
     Each of these labels should be unique
     Block-1 ,block-2 , are statement lists and contains zero or more statement
     Case labels ended with a color (:)
     When the switch is executed value of expression is successively compared against
      values value – 1 value – 2
     If the case is found whose value matches with value of the expreesion then the block
      of statement follows the case are executed
     The blocks statement at the end blocks signals at the end of a particular case and an
      exit from the switch statement transferring the control to the statement following the
      switch
     The default is an optional case when it is will be executed if the value of the
      expression does not match with any of the case values
     If it is not present no action takes of all the matches fail and the control the
      transfeered statement -x
     The selection process of switch statement is shown in the figure
         Ex
               Switch( index)
         {
         Case a:
                    Grade=’A’;
                    Break;
        Case b:
                  Grade=’B’;
                  Break;
         Case c:
                   Grade =’C’;
                   Break ;
        Default :
                    Grade=”fail”;
                    Break;
}
Printf(“%s\n”,grade);
GOTO STATEMENT
        C support the goto statement to branch unconditionally from one point tp another in
         the pogram
        The goto requires a label in order to identify the place where the branch is to be made
        A label in any valid variable name and must followed by colon
        The label is placed immediartely before the statement where the control is to be
         transferred
        The label can be placed anywhere in the program either before or after the goto label
         statement
        Two types if goto statement
              *forward jump
              * backward jump
    Syntax for forward jump
  goto label;
  ----
  -----
  Label:
  Statement ;
  Syntax for backward jump
  Label:
             Statement;
             --
             --
             --
  Goto label;
        Go to breaks the normal sequential execution of the program
        If the label is before the statement goto label;a loop will be formed and some
         statement will be executed repeadtly this is known as a backward jump
        If the label : is placed after the goto label; some statement will be skipped one the
         jump is known as a forward jump
         Ex
                  Main()
         {
                    Double x,y;
                     Read;
                    Scanf(“%f”,&x);
                    If (x<0)goto read;
                              Y=sqrt(x);
                     Printf (“%f%f”,x,y);
                     Goto read;
         }
         This program uses two goto statement
        The(2) goto statement after printing the x to transfer the control back to the input
         statement and the other to skip any futjer compound when the number is negative
        Due to unconditional goto the statement at the end the control is always transferred
         back to the input statement
ITERATION STATEMENT
   Iteration statement are also known an loops allows a set of instruction to be performed
    until a certain condition becomes false
   The condition may be predefined or open ended
   The loop strcture avaible in ‘C’one
         .. the while loop
         .. the do.. while loop
         .. the for loop
   In looping a sequences of statement are executed until sources condition for
    terminiation of the loop are stasified
   A program loop consist of two segements one known as the body of the loop and the
    other known ad the control statement
   The control statement tests certain condition and then directs the repeated executions
    of the statement contained in the body of the loop
   Depending upon the position of the control statement in the loop a control strcture
    may be classified as the entry- controllec loop or exit – controlled loop
    ENTRY CONTROLLED LOOP :
   The control statement are test before the starts of the loop execution
   If the condition are not satisfied then the body of the loop will be executed
    EXIT CONTROLLED LOOP:
   The test is performed at the end of the loop and therefore the body is executed
    uncodtionally for the first time
    WHILE STATEMENT
   While statement is used to carry out looping operations in which a group is statement
    is executed repeadtly until some condition has been stasfied
    Syntax
           While (test condtion)
          {
              Body of the loop
           }
   While is an entry – controlled loop statement
   The process of repeated executions of the body contuines until the test = condition
    finally becomes false and the control is transferred of the loop
   On exit the program continue with the statement immedieatly after the body of the
    loop
   The body of the loop may have one or more statement
   Braces are needed only if the body contains two or more statement
    Ex
       Main()
        {
    Int digit =0;
    While digit =0;
    While (digit <=9)
    {
          Printf (“%d\n”.digit );
          ++ digit :
    }
    }
     Output
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    THE DO WHILE STATEMENT
    The do.. while loop is sometimes refreed as do ..loop in c
   This loop checks its conditions at the end of the loop
   This means that do.. while loop will be execute at least onceeven if is the condition is
    false intialltly
    SYNTAX
     Do
    {
         Body of the loop
    } while ( test – condition);
   At the end of the loop tge test condition in the while statement is evaluated
   If the condition is true the program continues to evaluates the body of the loop once
    again
   This process continues as long as the condition is true
   When the condition between false the loop will be terminated and the control goes to
    the statement that appears immediatetly after the while statement
   Since the test -condition is evaluated at the bottom of the loop the do while constructs
    provide an exit – controlled loop
    Ex
          Main()
    {
         Int digit =0;
    D0
    {
                Printf ( “%d\n”,digit );
                 ++ digit ;
    }
              While ( digit <=9);
    }
   The printf statement is executed first among the value of the digit is incremented by
    value
   The body of the loop is always executed at least once
FOR LOOP STATEMENT
   For loop is entry controlled loop provides a more concise loop control strcture
    Syntax
    For (initialization – condition increment )
    {
         Body of fhe loop
    }
    The execution of for statement is as follows
   Intiallization of the control variables is done first using assignment statement
   A values of the control variable is tested using the text condition the test condition is a
    relational expressions determines when the loop will exit
   If the condition is true the body of the loop is executed otherwise the loop is
    terminated and the execution continues with the statement that the immediuatetly
    follows the loop
   When the body of the loop is executed the control is transferred back to the foe
    statement after the evaluating the last statement in the loop if the conition
    Is stasified the body of the loop is again executed this process continues till the value
    of the control variable fails to satisfy the test condition
    Ex:1(incrementing)
       For (x=0<=9 ;x-x+1 )
    {
          Printf (“%d”,x);
    }
     This loop allows negative increments this above loop will be executed for 10 times
    and prints value 9to 0 in one line
    Additional features of for loop
    1) More than one variable can be initialized at a time in the for statement
       Ex
       P==1;
       For(n=0;n<17;++n)
       Can be rewritten as
       For (p=1 n=0 ;<17 ;++n)
       2 the increment section may also have more one part
       Ex
       For (n=1;m=50;n=<17;++n)
       2 the increment section may also have more one part
       Ex
          For ( n=1 ;,m=50 ;<m;n+1,m=m+1)
       {
            P=m/n;
       Printf (“%d%d%d”,n,m,p);
       }
       Note
            Multiple argunments in the increment section and intiallization section will
       be seprated by comma
       3 the last condition in the loop may be compound relation
       Ex
       Sum =0;
       For(i=I;<20&&sum <100;++i)
       {
          Sum=sum +1;
          Printf (“%d%d “,sum ,i);
       }
       NESTING OF FOR LOOPS
   One for statement with in another for statement is allowed in c
   The nesting may contains up to 15 levels many compliers allow more than 15
    Ex
     M=5 :
    For(i=1;i<=16;i++)
    {
              Sum=i*m;
              Printf (“%d%d%d”I”*”m”=”sum);
    }
    UNCONDITIONAL TRANSFER STATEMENT
   C performs as unconditional branch
        Goto
        Break
        Continue
   Unconditional branching means “transfer control from the point where it is specified
    statement
   Go to can be used anywhere in the program where break and continue statements are
    conjunctions with any of the loop statement
    BREAK STATEMENT
   The break statement can be used to terminate a case in the switch statement and to
    foree immediate of loop bypassing normal loop condtional test
   When the break statement is encourtred inside a loop the loop immediately terminated
    and the program control passive to the statement following the loop
    Syntax
             Break
        Ex
                For (i=1<=5;i++)
                {
                   ----
                    ----
                   Break ;
    }
    CONTINUE STATEMENT :
   The contitune statement causes the next iteration of the enclosing loop to begin
   When this statement is encourted in the program the remaining statement in thebody
    of the loop are skipped and the control is passed to the re – initialization stop
   Continue directs the loop to increments portion of the loop and then condtional test
    Syntax
              Continue
    EXIT () FUNCTIONS
   Used to terminates a program just break statement is used to terminate a loop a return
    statement is used to terminates a function
   Exit () function is used to terminate the program and return control to the operating
   Exit function is of two types
    Exit (0)
    Exit(1)
    Exit(0) is called by the user for a successful termination of an instruction
    Exit(1)is called terminate a program in case of an error