The greatest mistake you can make in life is to be continually fearing you will make one

Sunday 19 December 2010

Multifile Program in C

1.What is a Multifile program?
  • If a program contains many functions then it is difficult to read and maintain because when the number of functions increases the size of the program/file will also increase. To avoid this some functions can be written in separate file 
  • The individual files will be compiled separetely and then linked together to form one executable object program.
  • This will help to editing and debugging because each file can be maintained at a manageable size.

2.How functions are defined in Multifile Program?
  • Within a multi file program a function definition may be either external (or) static
  • An external function will be recognized throughout the entire program(ie all the files)
  • Static function will be recognized only with in the file in which it is defined.
  • The default storage class for the function is external
  • Syntax for Function definition
    Storage class datatype name(type1 arg1......typen,argn)
    {
    }
  • Example:
    extern int calculate(int x)
    {
    }

3.How functions are declared in Multifile Program?
  • When a function is defined in one file and accessed in another one file, the 2nd file must include a function declaration.
  • This declaration identifies the function as an external function whose definition appears else where. 
  • The function declarations are usually placed at the beginning of the file before any function definition.
  • Syntax for external function declaration is same as function definition with additional one semicolon at the end
    Storage class datatype name(type1 arg1...typen,argn);
  • Example:
    extern int calculate(int x);
  • To execute a multifile program, each individual file must be compiled separetely then the main program file is compiled and executed.

4.A simple Multifile program in c

/****************File1*********/
#include<stdio.h>
//Include file test.c
#include "test.c"
//function declaration
extern void result(void);

int main()
{

    printf("In file1 main function\n");
    result();
    return;
}

/*****************File2*********/
extern void result(void)
{
    printf("Welcome to file2\n");
    return;
}
output:
./a.out
In file1 main function
Welcome to file2

5.Accessing external variables in Multifile function:
  • Within a multifile program, external variables defined in one file and accessed in another file.
  • An external variable definition can appear in only one file. 
  • Its location within the file must be external to any function definition. Usually it will appear at the beginning of the file.
  • External variable may include initial values.
  • If no initial value is assigned then it will automatically initialized to zero.
  • To access an external variable in another file,the variable must first be declared within that file .This declaration may appear anywhere within the file usually at the beginning of the file.
  • The declaration must begin with the storage class specifier extern. Initial values cannot be included in external variable declaration
  • Example:
     /*********file1**********/
    #include<stdio.h>
    //Include file test.c
    #include "test.c"
    //External variable definition
    int x=1,y=2,z=3;
    //function declaration
    extern void result(void);
    int main()
    {
        printf("In file1 main function\n");
        x=y+z;
        printf("x=%d y=%d z=%d\n",x,y,z);
        result();
        return;
    }
    /*****************File2*********/
    extern int x,y,z;/*external var declaration*/
    extern void result(void)
    {
        printf("Welcome to file2\n");
        printf("x=%d y=%d z=%d\n",x,y,z);
        return;
    }

    Output:./a.out
    In file1 main function
    x=5 y=2 z=3
    Welcome to file2
    x=5 y=2 z=3
  • The value assigned to an external variable can be altered within any file in which the variable is recognized
  • The changes will be recognized in all other files. Thus external variables provide a convenient means of transferring information between files.
  • Example:
     /*********file1**********/
    #include<stdio.h>
    //Include file test.c
    #include "test.c"
    //External variable 
    definition
    int x=10,y=20,z=30;
    //function declaration
    extern void result(void);
    int main()
    {
        printf("In file1 main 
    function\n");
        x=y+z;
        printf("x=%d y=%d z=%d\n",x,y,z);
        result();
        return;
    }
    /*****************File2*********/
    extern int x,y,z;/*external 
    var declaration*/
    extern void result(void)
    {
        printf("Welcome to file2\n");
    
        y=y+10;
        z=z+10;
        printf("x=%d y=%d z=%d\n",x,y,z);
        return;
    }

    Output:./a.out
    In file1 main function
    x=50 y=20 z=30
    Welcome to file2
    x=50 y=30 z=40

Sunday 12 December 2010

Static Variables in C

  • Static variable use the keyword static.
  • In a single file program static variable is similar to auto variables.
  • Like auto variables, static variables are also local to the block in which they are declared.It cannot be accessed outside of their defining function.
  • The difference between auto and static variable is that static variables dont disappear when the function is no longer active. their values persist.
  • If the control comes back to the same function again the static variables have the same values they had last time.
  • Example
    #include<stdio.h>
    void fun1();
    
    int main()
    {
        fun1();
        fun1();
        fun1();
        return;
    }
    
    void fun1()
    {
        int x=1;
        printf("X=%d\n",x);
        x=x+1;    
    }
    The output of the above program is ./a.out
    X=1
    X=1
    X=1
    If the variable is static then
    #include<stdio.h>
    void fun1();
    
    int main()
    {
        fun1();
        fun1();
        fun1();
        return;
    }
    
    void fun1()
    {
        static int x=1;
        printf("X=%d\n",x);
        x=x+1;    
    }
    The output of the above program is ./a.out
    X=1
    X=2
    X=3
  • If the automatic or static variables having the same names as external variables then the local variables will take precedence over the external variable and the changes done to the local variable will not affect the external variable.
    #include<stdio.h>void fun1();
    int x=1,y=2,z=3;
    int main()
    {
        static float x=5.0;
    
        printf("float x=%f\n",x);
        x=x+1;
        printf("float x=%f\n",x);
        fun1();
        printf("x=%d\n",x); //try to print external var
        printf("x=%f y=%d z=%d\n",x,y,z);    
        return;
    }
    void fun1()
    {
        char z;
        z='A';
        printf("int z=%d char z=%c\n",z,z);
        x=x+10;
        printf("x=%d\n",x);    
    }
    Output
    float x=5.000000
    float x=6.000000
    int z=65 char z=A
    x=11
    x=-1  //This will show an warning
    x=6.000000 y=2 z=3
    Here x,y,z are external integer variable. But x is redefined as a static floating point variable within main. so in main the external variable x will not be recognized. In function fun1() ,z is redefined as a char variable so the external variable z will not be recognized in fun1().
    Example 2
    #include< stdio.h>
    int x=1;
    int main()
    {
        static int x=5;
        printf("x=%d\n",x);
        x=x+1;
        printf("x=%d\n",x);
        return;
    }
    Output:
    x=5
    x=6
Initializing Static Variable:
  • Initial values can be included in the static variable declaration. 
  • Example: static int x=10;
  • The initial values must be constants not expressions.
    Example
    #include<stdio.h>
    int main()
    {
        static int x=5,y=10;
        static int a=x;
        static int z=x+y;
        printf("a=%d\n",a);
        printf("z=%d\n",z);
       return;
    }

    While compiling it shows error as " initializer is not a constant"

  • The initial values are assigned at the beginning of program execution. The variables retain these values throughout the life of the program unless different values are assigned.
  • The default initial value is zero.

Thursday 9 December 2010

Some Questions about Arrays

  1. How will you define an array?
  2. Is it necessary to specify the storage class in array definition? what is the default storage class for arrays?
  3. If the array elements are not initialized then what is the default initial value?for example: int x[5]; what is the value of x[1]?
  4. Consider we have a 10 element array what happen if we try to access the 12th element?
  5. Can I declare the array without specifying the size? int a[]; is it allowed?
  6. int a[]={1,2,3,4,5}; Is it allowed?
  7. Consider int a[5]={1,2,3,4,5}; printf("a=%d",*a); what is the output?
  8. Consider int a[5]={10,20,30,40,50}; printf("a=%d",a); what is the output?
  9. The last character in a array must be a NULL(\0) character what happen if I missed the '\0' character? char vowels[6]={'a','e','i','o','u'}; Is it correct?
  10. What happen If I am not giving space for '\0' character? char flag[4]={'T','R','U','E'}; is it correct?
  11. What happen If I am not giving space for '\0' character in string? char str[5]="Welco"; is it correct?
  12. x is a array pointer. what is the value for *x++; 
  13. Is there any way to find the size of the array?
  14. Can I print the characters given in single quotes as string?
  15. What is the output for the following program?
    #include<stdio.h>
    int main()
    
    {
    
        char x[]={'a','e','i','o','u'};
    
        printf("ans=%s",x);
        return;
    }
  16. What is the output for the following program?
    #include <stdio.h>
    int main()
    {     int x[5]={10,20,30,40,50};
        printf("ans=%d",(*x)++);
        return;
    }
  17. What is the output for the following program?
    #include <stdio.h>
    int main()
    {
        int x[5]={10,20,30,40,50};
        printf("ans=%d",++*x);
        return;
    }
  18. Do we have any minimum or maximum size restrictions in array index?
  19. What is the maximum index(sixe) number an array can have?
  20. Why array index is starting from zero? (or) Why arrays not store values from 1?
  21. Can I declare an array with 0 size? int a[0]; is it allowed?
  22. Can I declare an array with negative size? int a[-5]; is it allowed?
  23. Can I compare 2 arrays with single operator?
  24. Can I have comma(,) alone in the array list? int x[5]={,,,,}; Is it allowed?
  25. What happen if the array size is less than the number of initialized values?int a[5]={1,2,3,4,5,6,7,8,9,}; is it allowed?
  26. How to pass and access the array values to the function using call by value method?
  27. How to pass and access the array values to the function using call by reference method?
  28. Array name is a pointer. If an array is passed to a function and several of its elements are altered with in the function, are these changes recognized in the calling portion of the program?
  29. Can an array can be passed from a function to the calling portion of the program via return statement?
  30. Is there is any difference in storing 1 dimensional array and multi dimensional array?
  31. How the elements of a 2 dimensional array is stored? row major form (or) column major form?
  32. what is the size of a  2 dimensional array, 3 dimensional array?
  33. In 2 dimensional array number of rows specified first or number of columns specified first?
  34. Is it necessary to specify both  number of rows and number of columns in 2 dimensional array?
  35. Can I leave the number of columns in 2 dimensional array? int a[5][]; is it allowed?
  36. Can I initialize a[][]={1,2,3,4,5,6,7,8,9}; (or) a[5][]={1,2,3,4,5,6,7,8,9}; 
For Answers, Click here

      Thursday 2 December 2010

      Storage Classes in C(Extern)

      External Variables (or) Global Variables

      • The scope of a external variables remains from the point of the definition through the remainder of the program.
      • External variables are recognized globally, that can be accessed from any function 
      • Using external variables we can transfer information in to a function without using arguments.
      • The key word for external variable is extern.
      External Variable definition:
      • External variable definition is written in the same manner as an ordinary variable declaration.
      • It must appear outside of ,and usually before the functions that access the external variables
      • Example:
        int x;     //External variable definitions
        fun1(){}
        fun2(){}
      • An external variable definition will automatically allocate the required storage space for the external variables with in the computer memory.
      • The assignment of initial values can be included.
        Example:
        int x=10;     //initializing external variable in definition
        fun1(){}
        fun2(){}
      • The keyword extern is not required in external variable definition.
      • If a function requires an external variable, that has been defined earlier in the program, then the function may access the external variable freely.
        Example:
        #include<stdio.h>
        int x=10;
        fun1
        {
        }
        fun2
        {
            int a,b=10;
            a=b+x; //no need to declare x here
        }
      External variable Declaration:
      • If the program is a multi file program  then the external variable must be declared where ever its needed.
      • An external variable declaration begins with the keyword extern.
      • The name and the datatype of the external variable must agree with the corresponding external variable definition that appear outside of the function.
      • Example:
        file1
        #include<stdio.h>
        int x=10; //external var   defined here
        fun1()
        {
        }
        fun2()
        {
        }
        file2
        #include<stdio.h>


        fun3()
        {
            extern int x; //declaration               
        }
        In file 2,x should be of type integer because in file 1, x is defined as integer.
      • The storage space for external variables will not be allocated because the value is already defined.
      • External variable declaration cannot include the assignment of initial value. 

      Initialization of External variable:
      • External variables can be assigned initial value during variable definition.
      • The initial values will be assigned only once, at the beginning of the program.
      • The initial values must be expressed as constants not expressions or statements
        Example:
        #include<stdio.h>
        #define z 10
        /*definition of external variable x and Y
        int x=z;
        int y=z+x;       //error
        fun1()
        {
        }
        fun2()
        {
            int a,b=10;
            a=b+x;
            printf("x=%d y=%d\n",x,y);
        }
        int main()
        {
        fun1();
        fun2();
        return;
        }
        while compiling this program It shows an error   "error: initializer element is not constant"
                  
      • The external variables will then retain these values, unless they are altered during the execution of the program.
      • If the value of the external variable is changed with in a function, then the changed value will be carried over in to other parts of the program.
        Example
        #include<stdio.h>
        #define z 10
        int x=z;

        fun1()
        {
           x=30;
           printf("In fun1, x=%d \n",x);
        }
        fun2()
        {
            x=20;
            printf("In fun2, x=%d \n",x);
        }
        int main()
        {
            printf("In main, x=%d \n",x);
            fun1();
            fun2();
            return;
        }
        The output of the above program is
        In main, x=10
        In fun1, x=30
        In fun2, x=20
      • If the initial value is not assigned , the variable will automatically be assigned a value of zero.
        Example
        #include<stdio.h>

        int x; //Not initialized

        fun1()
        {
           x=30;
           printf("In fun1, x=%d \n",x);
        }
        fun2()
        {
            x=20;
            printf("In fun2, x=%d \n",x);
        }
        int main()
        {
            printf("In main, x=%d \n",x);
            fun1();
            fun2();
            return;
        }

        The output of the above program is
        In main, x=0
        In fun1, x=30
        In fun2, x=20

      Sunday 21 November 2010

      C programs

      1. Write a c program to get the system time and date?
        Solution:
        #include<stdio.h>
        #include<time.h>
        int main()
        {
            char *date;
            time_t timer;
            timer=time(NULL);
            date=asctime(localtime(&timer));
            printf("date:%s",date);
            return;
        }
        Output:
        ./a.out
        date:Fri Nov 19 18:30:21 2010
      2. Write a c program to reverse a line of text (or) reverse a string without using string fucnctions
        #include<stdio.h>
        void display(void);
        int main()
        {
            printf("Enter the line of text\n" );
            display();
            return 0;
        }
        void display()
        {
            char c;
            if((c=getchar())!='\n')
                display();
            putchar(c);
            return;
        }
        sunitha@sunitha-laptop:~/cpgm$ ./a.out
        Enter the line of text
        Welcome to c World

        dlroW c ot emocleW

      Thursday 21 October 2010

      Storage Classes in C

      What is a Local Variable?
      • Local variable is  a variable which is recognized only with in a single function.
      • Normally local variables does not retain its value once control has been transferrd out of the function.
      What is a global variable?
      • Global variaables can be recognized in two or more functions.
      • Global variables retain its value until the program terminated.
      Storage Classes:
      • Storage class are used to define the scope (visability) and life time of variables and/or functions in a program.
      • Scope refers to the portion of the program over which the variable is recognized.
      • There are 4 different storage classes in C
        1. Automatic Variable
        2. External Variable.
        3. Static Variable+
        4. Register Variable
      1.Automatic Variable:
      • Always declared with in a function and are local to the function in which they are declared .
      • The keyword is auto.
      • Example:
        auto int a,b,c;
      • The default storage class is auto. So if we declare int x;. It refers to auto int x;
      • Automatic variables defined in different functions will be independent of one another eventhough they have the same name
        Automatic Variable Example
        main()
        {
               auto int a,b,c;
               -----------------
               -----------------
               fun1();
               -------------------
        }

        fun1()
        {
             int a,b;
             -----------------
        }


        In the above example the variables a,b,c declared in the main function is available only to the main function and the variables declared in the function fun1() is local to the function
      • Automatic variables can be initialized during the variable declaration or explicit assignment statement
        Example:
        auto int x=10; is same as auto int x;
        x=10;
      • If the variable is not initialized its initial value will be unpredictable.
      • The assigned value will be reassigned each time the function is reentered
      • An automatic variable does not retain its value once control is transferred out of its defining function.

      Tuesday 21 September 2010

      Questions on Data Input and Output

      1. What are the commonly used input and output functions in c? How are they accessed?Solution


        * C has 6 popular data input and output library functions. They are getchar, putchar, printf, scanf, gets and puts.
        * These functions handle data transfer between computer and the input/output device (keyboard,monitor)
        * The functions getchar and putchar allow single characters to be transferred into and out of the computer.
        * The functions printf and scanf allow the transfer of single characters, numerical values and strings
        * The functions gets and puts handle input and output of strings.
        * To use these functions in a program the standard input output header file stdio.h must be included in the program.
      2. What is the header file needed to include the input and output functions?
        Solution



        To include the standard c input and output functions getchar, putchar, printf, scanf, gets and puts the header file #include< stdio.h > must be included in the program
      3. What happens when an end of file condition is encountered when reading characters using getchar() function?Solution



        If an end of file condition is encountered when reading a character using getchar() function , the value of the symbolic constant EOF will  automatically returned . The value of EOF is -1
      4. When entering data via the scanf function must octal data be preceded by 0 and must hexadecimal data be preceded by 0x?Solution



        Octal values need not be preceded by a 0 and hexadecimal values need not be preceded by 0x or 0X in scanf function
      5. How are unrecognized characters within the control string of a scanf function interpreted?Solution


        Un recognized characters within the control string are expected to be matched by the same characters in the input data. The unrecognized characters will be read into the computer but not assigned to an identifier. Execution of the scanf function will terminate if a match is not found
        Example:     scanf("%d * %d",&a,&b);
        the accepted  input is 5 * 4. If you give a and b as 5 and 4 then the program will stop executing as the expected character * is not found. so a is assigned to 5 and bis assigned to 0
      6. What is the difference between f-type conversion,e-tye conversion and g-type conversion when outputting floating point data with a printf function?
      7. What is the conversion character i represent in scanf and printf function?Solution



        "i" represent the dataitem is a decimal,hexadecimal or octal integer


      8. What is the minimum field width specifies and Where is it located?
        Solution


        It specifies the smallest field in which a value is to be printed. It is used in a conversion specification, and if present, it is placed immediately following the % sign.
      9. When the conversion specification is %, what is its minimum secification?
        Solution


        The size of the number being printed (including a minus sign, if the number is negative.)
      10. What is the meaning of 'f' in printf statement?
        Solution



        "f" stand for either formated or function

      11. In printf() function what is the output of printf("%d")?
        Solution
        When we write printf("%d",a); the compiler will print the value of a. But here nothing after "%d% so compiler will print garbage value

      Tuesday 7 September 2010

      Data Input and Output-III

      Little More about printf

      Flags in printf function:
      • We can place flags in the printf statement with in the control string which will affect the appearance of the output.
      • The flag must be placed immediately after the percent sign(%).
      • Two or flags can be combined for a single output.
      • Table shows the commonly used flags


        FlagMeaning
        -Data item is left justified(ie)Blanks added after the data item
        +A sign(+(or)-) will precede with each signed numerical data item
        0Place leading zeros to appear instead of leading blanks
        #(with 0- & x- type conversion)Causes octal and hexadecimal data items to be processed by 0 and 0x respectively
        #(with e-,f- & g- type conversion)Causes a decimal point to be present in all floating point numbers even if the data item is a whole number.Also prevents the truncation of trailing zeros in g-type conversion
      • Example:



         
         
        #include<stdio.h>
        int main()
        {
            int x=1234;
            float y=15.5,z=-5.5;
            printf("%d %f %e\n",x,y,z);
            printf("%6d %7.0f %10.1e\n",x,y,z);
            printf("%-6d %-7.0f %-10.1e\n",x,y,z);
            printf("%+6d %+7.0f %+10.1e\n",x,y,z);
            printf("%-+6d %-+7.0f %-+10.1e\n",x,y,z);
            printf("%7.0f %#7.0f %7g %#7g\n",y,y,z,z);
            return 0;
        }

        OutPut:


        1234 15.500000 -5.500000e+00
          1234      16   -5.5e+00
        1234   16      -5.5e+00 
         +1234     +16   -5.5e+00
        +1234  +16     -5.5e+00 
             16     16.    -5.5 -5.50000
      Prefixes in printf function: 
      • Prefixes within the control string to indicate the length of the corresponding argument.
      • Example: i indicates a signed or unsigned integer argument or a double precision argument. h indicates signed or unsigned short integer.

        #include<stdio.h>
        int main()
        {
            short x,y;
            long a,b;
            printf("%5hd %6hx %8lo %lu\n",x,y,a,b);
            return(0);
        }
        hd->short decimal integer
        hx->short hexadecimal integer
        lo->Long octal integer
        lu->Long unsigned integer
      • It is also possible to write the conversion characters x,e,g in uppercase as X,E,G. These uppercase conversion characters cause any letters with in the output data to be displayed in uppercase
        Example:

        #include<stdio.h>
        int main()
        {
            int x=0x10ab,y=0777;
            float z=0.3e-12;
            printf("|%8x %10.2e|\n",x,z);
            printf("|%8X %10.2E|\n",x,z);
            printf("|%8x %8o|\n",x,y);
            printf("|%#8x %#8o|\n",x,y);
            return(0);
        }
        Output:

        | 10ab 3.00e-13|
        | 10AB 3.00E-13|
        | 10ab 777|
        | 0x10ab 0777|
      gets() and puts() Function:
      • gets and puts function used to read and write string(character array terminate with a newline character)
      • The string may include whitespace characters
      • Example:

        #include<stdio.h>
        int main()
        {
            char text[100];
            gets(text);
            puts(text);
            return(0);
        }

        Output:
        ./a.out
        helo welcome
        helo welcome

      Tuesday 31 August 2010

      Data Input and Output-II

      4.Printf function

      • Printf function prints data from the computers memory to the standard output device.
      • Syntax:
        printf("%converion character",Argument list);

        Argument->It can be constants,single variable, array names (or) complex expressions
      • Example:

        #include<stdio.h>
        int main()
        {
            int i=10,j=20;
            char text[20];
            printf("%d %d %s\n",i,j,text);
            return 0;
        }
      • printf allow us to include labels and message with the output data. The extra labels in the double quotes in the printf will be displayed in the screen.
        Example:
        #include &lt; stdio.h&gt;
        int main()
        {
        int avg=80;
        printf("Average=%d%\n",avg);
        return 0;
        }

        Output
        Average=80%
      • The f-type conversion and the e-type conversions are both used to output floating point values.  In e-type conversion an exponent to be included in the output.
        Example


        #include&lt; stdio.h &gt;
        int main()
        {
            float x=100.0,y=25.25;
            printf("%f %f \n",x,y);
            printf("%e %e\n",x,y);
            return 0;
        }

        Output
        100.000000 25.2500001.000000e+02 2.525000e+01
      •  In the printf, s-type conversion is used to output a string that is terminatedd by the null character(\0). Whitespace characters may be included with in the string.
        Example: Reading and writing a line of text.
        #include&lt; stdio.h &gt;
        int main()
        {
            char text[100];
            scanf("%[^\n]",text);
            printf("%s",text);
            return 0;
        }
      Minimum field width specification
      • We can restrict the number of characters or numbers displayed in the screen by specifying a fieldwidth. A minimum field width can be specified by preceding the conversion character by an unsigned integer.
      • Syntax:
        %fieldwidth conversioncharacter
      • If the number of characters in the corresponding data item is less than the specified field width then the data item will be preceded by enough leading blanks to fill the specified field.
      • If the number of characters in the data item exceeds the specified field width then additional space will be allocated to the data item so that the entire data item will be displayed.
        Rule1: Number of digits > field width=Add additional space
        Rule2: Number of digits < field width=Add leading blankspace
      • Example:

        #include<stdio.h>
        int main()
        {
            int x=12345;
            float y=123.456;
            printf("%3d %5d %7d\n",x,x,x);
            printf("%3f %10f %13f\n",y,y,y);
            printf("%3e %10e %13e\n",y,y,y);
            return 0;
        }
        Output
        12345 12345   12345
        123.456000 123.456000    123.456000
        1.234560e+02 1.234560e+02  1.234560e+02
        x has 5 digits
        %3d->no of digits(5) < fieldwidth(3) so additional space added and all  the digits are displayed.
        %7d-> no of digits(5) > fieldwidth(7)=>12345
         
      • g-type conversion:
           In g-type conversion no extra trailing zeros are added in the floating point number.
        Example:
        #include<stdio.h>
        int main()
        {
            float x=123.456;
            printf("%3g %10g %13g\n",x,x,x);
            printf("%3g %13g %16g\n",x,x,x);
            return 0;
        }

        Output
        123.456    123.456       123.456
        123.456       123.456          123.456
      Floating point precision specification
      • It is also possible to specify the maximum number of decimal places for a floating point value or the maximum number of characters displayed for a string. This specification is known as precision.
      • The precision is an unsigned integer. Precision is always preceded by a decimal point.
      • A floating point number will be rounded if the number of digits exceeds the precision.
      • Example:
        #include<stdio.h>
        int main()
        {
            float x=123.456,y=1.5,z=4575.255;
            printf("%5f %7f %7.1f %7.2f %7.3f\n",x,x,x,x,x);
            printf("%5f %7f %7.1f %7.2f %7.3f\n",y,y,y,y,y);
            printf("%5f %7f %7.1f %7.2f %7.3f\n",z,z,z,z,z);
            printf("%5g %7g %7.1g %7.2g %7.3g\n",x,x,x,x,x);
            printf("12e %12.3e %12.5e\n",x,x,x);
            //only precision no field width
            printf("%f %0.1f %0.3f\n",x,x,x);
            printf("%e %0.3e %0.5e\n",x,x,x);
            return 0;
        }

        Output
        123.456000 123.456000   123.5  123.46 123.456
        1.500000 1.500000     1.5    1.50   1.500
        4575.254883 4575.254883  4575.3 4575.25 4575.255
        123.456 123.456   1e+02 1.2e+02     123
        12e    1.235e+02  1.23456e+02
        123.456000 123.5 123.456
        1.234560e+02 1.235e+02 1.23456e+02
      Minimum field width and precision specification for character data
      • The specification for a string is same as numerical data. (ie) leading blanks will be added if the string is shorter than the specified field width and additional space will be allocatedd if the string is longer than the specified field width.
      1. string characters < field width=add leading blanks
      2. string characters > field width=add additional space
      • The precision specification will determine the maximum number of characters that can be displayed.

        Precision < string characters=excess right most characters will not be displayed
      • This rule is applied even if the minimum field width is larger than the entire string but additional blanks will be added to the truncated string.
      • Example:

        #include<stdio.h>
        int main()
        {
            char text[20]="Welcome";
            printf("%5s\n %7s\n %10s\n %15s\n %0.5s\n %15.5s\n",text,text,text,text,text,text);
            return 0;
        }

        Output:
        Welcome
         Welcome
            Welcome
                 Welcome
         Welco
                   Welcome
        %0.5s=Welco [no field width but the maximum precision is 5. so only 5 characters displayed.
        %15.5s= < 10 blankspace > Welco [maximum precision is 5 so the string trimmed to Welco but the field width is 15 so 10 leading blanks added.]

      Friday 13 August 2010

      Data Input and Output-I

      • C has 6 popular data input and output library functions. They are getchar, putchar, printf, scanf, gets and puts.
      • These functions handle data transfer between computer and the input/output device (keyboard,monitor)
      • The functions getchar and putchar allow single characters to be transferred into and out of the computer.
      • The functions printf and scanf allow the transfer of single characters, numerical values and strings
      • The functions gets and puts handle input and output of strings.
      • To use these functions in a program the standard input output header file stdio.h must be included in the program.
      1.Single Character Input-getchar() function:
      •  The getchar() function reads a single character from the input device(keyboard)
      • Syntax:


          char variable=getchar();
      • Example:

            char c;
            c=getchar();

        The character entered on the keyboard is read by the getchar function and assigned to the character variable c.
      • If an end of file condition is found when reading a character using getchar, the value of symbolic constant(-1) will be returned.
      2.Single Character Output-putchar() function:
      • The putchar() function display a single c character on the standard output device.
      • Syntax:


          putchar(variable);
      • Example:


            char c;
            putchar(c);

        The character stored in the variable c is displayed in the monitor.
      Scanf function
      • scanf function used to read any numerical values, single characters or strings.
      • The function returns the number of data items that have been entered successfully.
      • Syntax:


            scanf("control string",argument list);
               control string=%conversion character.
      • Table shows the conversion character and the data item meaning



        Conversion characterMeaning
        cSingle character
        ddecimal integer
        e,f,gFloating point value
        hShort integer
        idecimal, hexa decimal or octal integer
        ooctal integer
        uunsigned decimal integer
        xHexadecimal integer
        sString
        [...]String include whitespace characters
      • The arguments may be variables or array.
      • Each variable name must be preceded by an ampersand(&). Array name should not begin with &.
      • Example

        #include<stdio.h>
        int main()
        {
            int no;
            float f;
            char text[50];
            scanf("%d %f %s",&no,&f,text);
        }
      • If 2 or more data items are entered they must be separeted by whitespace characters[blank space (or) new line (or) tab].
      • While reading a string that include whitespace characters use []. specify the whitespace characters inside the []
      • Example: Read a string which contains only capital letters and blank space

        #include<stdio.h>
        int main()
        {
            char text[50];
            scanf("%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]",text);}
        here if the input is given as WELCOME TO C then text contain WELCOME TO C. If the input is given as Welcome To C then only the single letter W would be assigned to text
      • If the characters with in the brackets are given after circumflex(^) operator then the scanf will read all the characters except the characters in the []

            scanf("%[^\n]",text);
        The program will read any characters(maximum 49 characters) until the newline is pressed.
      Little More about scanf function:
      • It is possible to limit the number of characters read by specifying a maximum field width for that data item. To do that an unsigned integer integer indicating the field width is placed with in the control string between the percent sign(%) and the conversion character.
      • Syntax:
        %fieldwidth conversioncharacter
      • Example:
            %4d -->The decimal number can contain maximum of 4 digits
           %5f -->The float number can contain 5 digits including the dot(20.20,200.1)
      • The data item may contain fewer characters than the specified field width but cannot exceed the specified field width. If we give more characters than the specified field width the leftover characters are incorrectly interpreted as a next data item
      • Example1:
        {

            int a,b,c;

            scanf("%2d %2d %2d",a,b,c);
        }

        1. If the input is given as 12 34 56 then a=12 b=34 c=56.
        2. If the input is given as 123456789 then a=12 b=34 c=56
        3. If the input is 123 4 5678  then a=12 b=3 c=4
      • Example 2:
            float f;
            scanf("%5f",&f);

        1. if the input is 555.55 then f=555.500000
        2. If the input is 456789.555 then f=45678.000000
        3. if the input is 55555.555 then f=55555.00000
      • If there is no whitespace present between the conversion characters in the scanf function then the whitespace characters with in the input data will be interpreted as a data item.
      • Example:
            char a,b,c;
            scanf("%c%c%c",&a,&b,&c);
        If x y z is given as input then a=x b= (blankspace) c=y
      • To avoid reading the blankspace use %1s instead of %c
            char a,b,c;
            scanf("%c%1s%1s",a,b,c);
        If x y z is given as input then a=x b=y c=z or we can write the scanf as scanf("%c %c %c",&a,&b,&c);
      • Unrecognized characters within the control string are expected to be matched by the same characters in the input data. The unrecognized characters are read but not assigned to any variable but if the characters are not present then the scanf function will terminate.
      • Example:
            char a,b;
            scanf("%c * %c",&a,&b);
        If the input is given as a *  b then only a=a b=b. if the input is given as a b then the function is stop executing as * is not given as input. so a is assigned to a . b is Null

      Saturday 31 July 2010

      Questions on Functions

      1. Difference between pass by value and pass by reference?
      2. Can you write function similar to printf()?
      3. How can called function determine number of arguments that have been passed to it?
      4. What is the purpose of main() function?
      5. What are the advantages of functions?
      6. Define function and built-in function?
      7. Can the sizeof operator used to tell the size of an array passed to a function?
      8. Is it possible to execute a code even after the program exits the main() function?
      9. What is a static function?
      10. Why should I prototype a function?
      11. Is it better to use a function or a macro?
      12. How do you determine whether to use a stream function or a low level function?

      Friday 30 July 2010

      Airline Reservation System in C


        Description

        Develop a software using C for the case given below.


        Write a program to assign seats on each fligh of the airlines only place ( capacity : 20 seats ). Your program should display the following menu alternatives.

        Please type 1 for business class
        please type 2 for economy class

        If person types 1, the program should assign a seat in business class ( seat 1 to 5). if the person types 2, then it should assign economy class ( seat 6 to 20). Your program then should bring a boarding pass indicating the persons' seat number and whether it is in the business or economy class of the place . use a single-scripted array to represent the seating chart of plane. Initialize all the elements of array to 0 to indicate that all seats are empty. As each seat is assigned, set the corresponding elements of array to 1 to indicate that seat is no longer available. program should never assign a seat which is already assigned. When the business class in full, your program should ask the person if it is acceptable to be placed in economy class ( and vice versa). if yes, then make the appropriate seat assignment. If no, then print the message " next flight leaves in 3 hours "

        Basic Requirements :
        assign a seat either in the business or economy class.
        display a boarding pass
        display seating chart with indication of assigned or not assigned.
        validation - no seat that has been assigned can be re-assigned
        re-assign seat if the class is full

        You may design the system in any way you feel that meets systems requirements. you may include menus that you feel are relevant to navigate around the system. Eventually there should be an end to the system. Use quit to exit the system.

        You may use structures, arrays, loops, and decision structures in your program. you may include any extra feature eg. sorting the boarding passes by name, which you may feel relevant and that adds value to the system

        Monday 21 June 2010

        String

        String:
        • Strings are character array.
        • Character array are stored in contiguous memory location.
        String Constant:
        • A string constant is a one-Dimensional array of characters terminated by a null character('\0').
        • Each character in the array occupies one byte of memory and the last character is always '\0'
          Example:
              char str[]={'C','P','U','\0'};
        • The terminating null character('\0') is very important in a string because its the only way for the compiler to know where the string ends.
        Null Character('\0'):
        • '\0' is called null character.
        • '\0' and 0 are not same because both has different ASCII value. ASCII value of '\0' is 0 but ASCII value of 0 is 48.
        String Initialization:
        • A string can be initialized without adding the terminating null character as,

              char str[]="WELCOME";

          Here C inserts the NULL character automatically.
        Accessing Character array elements:
        • Similar to integer array we can access array elements  
          #include< stdio.h >
          int main()
          {
              int i=0;
              char str[]="WELCOME";
              while(str[i]!='\0')
              {
                  printf("%c",str[i]);
                  i++;
              }
              return;
          }
        • This can be done by using pointer also. Mentioning th name of the array we get the base address(zeroth element) of the array.
          #include< stdio.h >
          int main()
          {
              char str[]="WELCOME",*ptr;
              ptr=str;
              while(*ptr!='\0')
              {
                  printf("%c",*ptr);
                  ptr++;
              }
              return;
          }
        Reading a string from a keyboard:
        • For reading and writting a string the format specifier is %s and no & is needed
          #include< stdio.h >
          int main()
          {
              char str[30];
              printf("Enter the string\n");
              scanf("%s",str);
              printf("String=%s",str);
              return;
          }

          The scanf() function fills in the character typed at keyboard into the str[] array until the blank space or enter key is hit. If blank space or enter key is hit scanf() automatically place a '\0' in the array.
        • Normally the %s will read a string upto a blank space. To read a muti word string untill the end of line including blank space use %[^\n]s
          #include< stdio.h >
          int main()
          {
              char str[100];
              printf("ENter the string\n");
              scanf("%[^\n]s", str);
              printf("String=%s",str);
              return;
          }

          Output:
          Enter the string
          welcome honey
          String=Welcome honey
        • Other way of reading multiword string is gets() and puts(). But it is dangerous to use gets() in programs so try to avoid gets()
          #include< stdio.h >
          int main()
          {
              char str[30];
              printf("Enter the string\n");
              gets(str);
              puts(str);
              return;
          }
        Pointer and String:
        • A string can be stored in 2 forms

          1. char str[]="Welcome"; //here Welcome is stored in a location called str
          2. char *str="Welcome"; //here Welcome is stored in some other location i memory and assign the address of the string in a char pointer
        • The advantage of pointing a string using a character pointer is we cannot assign a string to another string but we can assign a char pointer to another char pointer
          #include< stdio.h >
          int main()
          {
              char str1[]="Welcome",str2[30];
              char *ptr1="Welcome",*ptr2;
              //str2=str1; //error
              ptr2=ptr1;
              printf("ptr2=%s",ptr2);
              return;
          }
        • Once a string has been defined it cannot be initialized to another set of characters but using char pointer we can redefine the string.
          #include< stdio.h >
          int main()
          {
              char str1[]="Welcome";
              char *ptr1="Welcome";
          //  str1="Good";//error
              ptr1="Good";
              printf("ptr1=%s",ptr1);
              return;
          }

           
        Points to consider in Strings:
        1. The size of the string depends on the size of declaration not the number of characters in the string
          #include < stdio.h>
          void main()
          {
              char str[30]="Network programming";
              printf("%d",sizeof(str));
          }

          The output here is 30 not 1

        Tuesday 1 June 2010

        Interview Questions

        1. Difference between arrays and pointers?
        2. What is the purpose of realloc( )?
        3. What is static memory allocation and dynamic memory allocation?
        4. How are pointer variables initialized?
        5. Are pointers integers?
        6. What is a pointer variable?
        7. What is a pointer value and address?
        8. What is a method?
        9. What are the advantages of the functions?
        10. What is the purpose of main( ) function?
        11. What is an argument ? differentiate between formal arguments and actual arguments?
        12. What is a function and built-in function?
        13. What is modular programming?
        14. When does the compiler not implicitly generate the address of the first element of an array?
        15. What are the characteristics of arrays in C?
        16. Differentiate between a linker and linkage?
        17. What are advantages and disadvantages of external storage class?
        18. Diffenentiate between an internal static and external static variable?
        19. What are the advantages of auto variables?
        20. What is storage class and what are storage variable ?
        21. Which expression always return true? Which always return false?
        22. Write the equivalent expression for x%8?
        23. why n++ executes faster than n+1?
        24. what is a modulus operator? What are the restrictions of a modulus operator?
        25. What is the difference between a string and an array?
        26. Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name?
        27. Can the sizeof operator be used to tell the size of an array passed to a function?
        28. Is using exit() the same as using return?
        29. Is it possible to execute code even after the program exits the main() function?
        30. What is a static function?
        31. Why should I prototype a function?
        32. How do you print an address?
        33. Can math operations be performed on a void pointer?
        34. How can you determine the size of an allocated portion of memory?
        35. What is a “null pointer assignment” error? What are bus errors, memory faults, and core dumps?
        36. What is the difference between NULL and NUL?
        37. What is the heap?
        38. Can the size of an array be declared at runtime?
        39. What is the stack?
        40. When should a far pointer be used?
        41. What is the difference between far and near?
        42. Is it better to use malloc() or calloc()?
        43. Why should we assign NULL to the elements (pointer) after freeing them?
        44. When would you use a pointer to a function?
        45. How do you use a pointer to a function?
        46. Can you add pointers together? Why would you?
        47. What does it mean when a pointer is used in an if statement?
        48. Is NULL always defined as 0?
        49. What is a void pointer?
        50. What is a null pointer?
        51. How many levels of pointers can you have?
        52. What is indirection?
        53. How do you print only part of a string?
        54. How can I convert a string to a number?
        55. How can I convert a number to a string?
        56. What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
        57. How can you check to see whether a symbol is defined?
        58. How do you override a defined macro?
        59. What is #line used for?
        60. What is a pragma?
        61. What are the standard predefined macros?
        62. How can type-insensitive macros be created?
        63. How many levels deep can include files be nested?
        64. Can include files be nested?
        65. Can you define which header file to include at compile time?
        66. What is the difference between #include and #include “file”?
        67. Is it better to use a macro or a function?
        68. How are portions of a program disabled in demo versions?
        69. What is the benefit of using an enum rather than a #define constant?
        70. What is the benefit of using #define to declare a constant?
        71. Can a file other than a .h file be included with #include?
        72. How can you avoid including a header more than once?
        73. What will the preprocessor do for a program?
        74. What is a macro, and how do you use it?
        75. What is Preprocessor?
        76. How can I make sure that my program is the only one accessing a file?
        77. How can I open a file so that other programs can update it at the same time?
        78. How do you determine whether to use a stream function or a low-level function?
        79. What is the difference between text and binary modes?
        80. How can you restore a redirected standard stream?
        81. How do you redirect a standard stream?
        82. How can I search for data in a linked list?
        83. How can I sort a linked list?
        84. What is hashing?
        85. What is the quickest searching method to use?
        86. What is the easiest searching method to use?
        87. How can I sort things that are too large to bring into memory?
        88. What is the quickest sorting method to use?
        89. What is the easiest sorting method to use?
        90. What is the benefit of using const for declaring constants?
        91. Can static variables be declared in a header file?
        92. What is the difference between declaring a variable and defining a variable?
        93. Is it acceptable to declare/define a variable in a C header?
        94. When should a type cast not be used?
        95. When should a type cast be used?
        96. How can you determine the maximum value that a numeric variable can hold?
        97. How reliable are floating-point comparisons?
        98. Can a variable be both const and volatile?
        99. when should the volatile modifier be used?
        100. When should the register modifier be used? Does it really help?