Array Initialization

Embed Size (px)

Citation preview

  • 7/23/2019 Array Initialization

    1/29

    1

    Array Initialization: - After array declaration you should initialize the array otherwisearray element contain Garbage. There are two types of array initialization.

    1. Compile Time or Direct initialization

    2. Run time or late initialization

    When we declare the array then compiler automatically assigns the garbage values to thearray elements.

    -as the ordinary variable. Use following syntax to initialize array directly at declaration

    datatype arrayname [size] ={list of value of same type};

    When we initialize the array directly then we can skip the size of array.

    datatype arrayname [] = {list of value of same type};

    In this case compiler will automatically count the values and will set the size of array.

    Ex1. int a[5] = {3,5,8,15,7};0 1 2 3 4

    a

    We can also write it as

    int a[] = {3,5,8,15,7};

    Ex2. int a[5] ={0};

    0 1 2 3 4a

    If we initialized any element in compile time array initialization, then compiler

    automatically assign zero to all remaining element of array.

    int a[5] = {5,7};

    0 1 2 3 4

    int b[] = {0}; b

    int d[] = {5,7}; d

    Ex3. float f[5]={0.0,15.75,-7.5};

    0 1 2 3 4

    3 5 8 15 7

    0 0 0 0 0

    5 7 0 0 0

    0

    5 7

  • 7/23/2019 Array Initialization

    2/29

    2

    f

    Ex4.At initialization, if the size of array is smaller then the count of initializes values, thenin this case compiler give us error.

    int a[3] = {5,7,10,15,9}; error

    size count =5

    Run time initialization: - If initialize the array after its declaration, then it is called runtime initialization. Basically in run time initialization we replace garbage value with new

    values.

    Ex1. int a[5]; /*Declaration */int a[0] = 5;

    int a[1] = 10;int a[2] = 11;

    int a[3] = -10;int a[4] = 20;

    0 1 2 3 4

    A

    Ex2. Using Loop

    int a[5];

    int i;

    for(i=0;i

  • 7/23/2019 Array Initialization

    3/29

    3

    Array

    Two Dimension:- It also a multi-Dimension array. It is very common in cprogramming. It is very common in c programming. It is used to store tabular data(table of

    data) like matrix.

    2 3 4

    5 4 3 It is very easy to store this matrix in two dimension array.

    1 2 3

    Use following syntax to declare two dimension array.

    datatype arrayname[size1][size2];

    The size1 and size2 must be constant integer grater then zero.

    Ex. int a[3][4];

    0 1 2 30

    1 to use this element we write a[1][3]2

    The above array has three rows and 4 columns in each row. Each

    element of this array will occupy two bytes of memory.For two or more dimension system allocates linear memory

    Memory Address

    Index no.

    Single

    Dimension

    Two

    Dimension

    Multi

    Dimension

    1001

    1002

    1003

    1004

    group of two byte[ a[0][2]

    a[0][3]

    a[1][0]

    a[1][1]

    a[1][2]

    a[1][3]

    a[2][0]

    a[2][1]

    a[2][2]

    a[2][3]

    .

    .

    a[0][0]

    a[0][1]

  • 7/23/2019 Array Initialization

    4/29

    4

    To calculate the size of whole array use following formula

    Size Of Array = rows * cols * size of datatype

    Ex. int a[3][4];

    Size = 3*4*2

    =24bytes

    * Memory contains many location of one byte each. Each memory location has an address.

    * C creates a group of locations according to the data type of array and assign an index

    number.

    Data Type Group Containsint 2 locations

    char 1float 4

    double 8long 4

    long double 10etc.

    * In the case of double dimension array C assign two-level index number to each element

    like a[0][1].

    Initialization of two dimension array:- As single dimension array the double dimensionarray can be initialized at compile time and run time.

    Compile Time/early/static initialization:- When we initialize the array at declarationthen it is called compile time initialization . In compile time initialization we can skip thesizes.

    Case 1 : int a[][] = {{2},{5,7,8},{10}};

    0 1 2

    a 0

    1

    2

    The inner curly braces represent rows. The number of columns in each row always be

    equal to length of largest row.

    Case 2: int a[2][3] ={5,8,9 , 10,20,30};row1 row 2

    2 0 0

    5 7 8

    10 0 0

    Remaining elements are set to zero

  • 7/23/2019 Array Initialization

    5/29

    5

    0 1 2a 0

    1

    C automatically creates group of values for each row.

    Note: - C uses the policy row Major for double dimension array by default.

    Policies: (1) Row Major (2) Column Major

    Case 3 : int a[][3] = {5,8,9, 10,20,30, 50,60};row1 row2 row3

    According the no. of columns, C will automatically find total rows.

    0 1 2a 0

    1

    2

    Case 4 : int a[3][] = {5,3,4, 2,4,5, 6,4};Incorrect

    In this case C unable to find number of column for each row.

    Case 6: int a[][] = { { 2 },row1

    {10}row2

    };

    Case 7: int a[4][5] = {{2}};

    0 1 2 3 4

    0

    1

    2

    3

    5 8 9

    10 20 30

    5 8 9

    10 20 30

    50 60 0

    2

    10

    2 0 0 0 0

    0 0 0 0 0

    0 0 0 0 0

    0 0 0 0 0

    Remaining element

  • 7/23/2019 Array Initialization

    6/29

    6

    MULTI-DIMENSION ARRAY :- C providesupport for N dimension array. C allocatesthe linear memory for multi-dimension array. Use following syntex to declare multi-

    dimension array

    Datatype arrayname[size1][size2]..[size n];

    Here size1,size2,..size n must be grater then zero and constant.

    2

    10

    0

    1 2

    2 13

    . 00 1

    In this example it contains 3(three) two dimension array.

    3D Array :-Group of two dimension array.2D array :- Group of one dimension array.

    1D array :- Group of elements.

    Function

    A large no of program is sub-divided into number of smaller programs or sub-programs.The each sub program specifies one or more actions to be performed for the largerprogram. Such sub-programs are called functions.

    A function is a small piece of big program that performs a particular action for program. It

    works like an independent unit. Every unit in also known as module and this kind of

    programming is called modular programming.

    A function groups together statements into a named unit. These unites can be invoked from

    other part of program like main function.

    The function main() invokes other functions. System starts the execution by calling themain() function, so other function should be linked directly or indirectly with main()

    function.

  • 7/23/2019 Array Initialization

    7/29

    7

    Every function of program can invoke or call other functions one or more times. So itreduces repetition of codeand complexity of program.

    Dividing a program into functions is one major step towords structuredprogramming.

    Types of functions: There are two types of functions C supports.

    1. Library function.

    2. User Defined Function.The above categories may contain following types of functions

    a) Function with some return type and one or more arguments/parameters.

    Arguments

    b) Function with return type and zero arguments/ parameters.

    It does not take argument but return the result.

    c) Function with no return type and one or many arguments/parameters.

    Arguments

    It takes the value for processing but it does not return any result.

    d) Function with no return type and zero argument or parameter.

    It does not take value for processing and also it does not return any result to caller

    program.

    Note : Zero argument/parameter and no return typeare represented by keyword

    void. It is a specific type that represents Nothing.

    e) Function that return multiple value:-Well see in pointer

    Function

    Return the result

    Function

    Result

    Function

    Function

  • 7/23/2019 Array Initialization

    8/29

    8

    Library Function: -C provides a large number of function libraries. Each librarycontains very useful defined/built in functions. Using these library functions we can create

    complex programs with low efforts.The Library function have already been defined and compiled. The object code is available

    in libraries.

    The following libraries are commonly used

    etc.

    C provides around 41built-in libraries. It is very easy to use defined function of these

    libraries.

    1) :- It provide functions for standard input and output devices(keyboard andmonitor) like to take input from keyboard, display output on monitor etc.

    The following functions of this library are commonly used.

    getchar() :- It is used to take one character input from standard input device keyboard. It

    return inputted character as integer code(ASCII code).

    Ex. char ch;printf(enter the character);

    ch = getchar();

    it i s simi lar to scanf(%c,&ch);

    variable to contain

    inputted char

    putchar(ch) :- It displays the specified character on monitor. It returns code of character,

    that has displayed.

    Ex.main(){

    char ch = A;int n;n= putchar(ch);printf(\n the return value of putchar =%d,n);

    }

  • 7/23/2019 Array Initialization

    9/29

    9

    o/pA

    65(ASCII code of A)Note :- It is not necessary to hold return value of putchar in a variable.

    Ex. char ch =A;

    putchar(ch);

    I tis similar to printf(%cch);

    o/pA

    scanf(format string, &var1,&var2,.):-It takes variable number of parameters.It is used to take input from standard input device keyboard. It returns the count of

    successful inputs taken by it.

    LValue :- A variable that is used to hold return value of function.

    Ex. int a,b,c,n;

    printf(enter the three numbers);n= scanf(%d%d%d,&a,&b,&c);printf(the return value of scanf function = %d,n);

    o/penter the three numbers 10 20 30

    The return value of scanf function = 3

    We normally use scanf() directly without specifying Lvalue.

    printf(format string, var1,var2,):- It takes variable number of arguments/parameters like scanf(). It is used to display data on standard output device monitor. Itreturns total number of character has been displayed by it.

    Ex. int a=27, b = 100, c = 299, n;

    n= printf(%d\t%d\t%d\n,a,b,c);printf(return value of printf = %d, n);

    o/p

    27 100 299

    Return value of printf = 11

    27 - 2 character

    100 - 3 character299 - 3 character

    \t - 1 character\t - 1 character

    \n - 1 character

    11

    Lvalue

  • 7/23/2019 Array Initialization

    10/29

    10

    fflush(stdin) :- It is used to clear the buffer to take next successful input. When we take

    a character input after number input then system does not ask for character input.Ex. main()

    {int a;

    char ch;printf(Enter the number);

    scanf(%d,&a);printf(Enter the character);

    ch=getchar();

    printf(The number = %d and character = %d,a,ch);}

    o/pEnter the number 199 \n wil l be assigned to ch

    Enter the character

    The number = 199 and character = 10 ASCI I code of \n

    To solve above problem we use fflush(stdin) after the scanf().

    If we take character input before number then it will work properly.

    Ex. main(){

    int a;char ch;

    printf(Enter the number);scanf(%d,&a);

    fflush(stdin);printf(Enter the character);

    ch=getchar();

    printf(The number = %d and character = %d,a,ch);}

    o/pEnter the number 199

    Enter the character A

    The number = 199 and character = 65 ASCII code of A

    :- It provides predefined/ built-in functions for mathematical operations. Thecommon functions of the library

    1. sqrt(n) :- It return square root of number.

  • 7/23/2019 Array Initialization

    11/29

    11

    N square rootThe n should be grater than equal to zero.

    Ex.

    #include#include

    main(){

    float num,ans;printf(Enter the number);

    scanf(%d,&num);ans = sqrt(num);

    printf(The square root of %f = %f, num,ans);}

    O/P 1Enter the number 25

    The square root of 25.000000=5.000000

    O/P 2Enter the number 0

    The square root of 0.000000 = 0.000000

    O/P 3Enter the number -5

    The square root of -5.000000= +NAN Not available number

    2. pow(x,y):- It finds xy

    pow(2,0) = 1 (20)

    pow(-2,0)=1 (-20)

    pow(10,0)=1 (100)

    pow(2,4)= 16 (24)

    pow(-2,4)=16 (-24)

    pow(-2,3)=-8 (-23) (-2*-2*-2)

    pow(2,-2)=0.25 (2-2

    ) =1/22

    = =0.25

    pow(0,0)= 1 with errorpow(0,-1) = no result , it will display error.

    3. abs (num): It returns the absolute value of num. It works for integer only. If you

    pass floating point values then it convert value and result into integer. Basically itconverts negative into positive.

    abs(-5) = 5

    abs(5) = 5

    sqrt

  • 7/23/2019 Array Initialization

    12/29

    12

    abs(1.999) = 1abs(0) = 0

    abs(-0) = 04. pow10(x):- It finds 10

    x

    pow10 (2) = 100 102

    pow10 (3.14) = 1000 10

    3

    pow10 (3.99) = 1000 103

    It takes the power as integer and discard fractional part if exist.

    5. sin(x)

    6. cos(x)7. tan(x)

    8. asin(x) sin-1x

    9. acos(x) cos-1

    x

    10. atan(x) tan-1

    x11. sinh(x) hyperbolic sin x

    12. cosh(x)

    13. log(x) logex

    14. log10(x) log10x15. exp(x) e

    x

    16.floor(x) : it finds greatest integer that is less than equal to x.

    It return the value rounded down to next lower integer

    floor(2.99) = 2floor(2.01) = 2

    floor(2.00) = 2floor(3.9) = 3

    17.ceil(x):- It finds lowest integer that is grater than equal to x.

    It returns the value rounded up to next higher integer.ceil(3.0001) = 4

    ceil(3.999) = 4ceil(3.00) =4

    ceil (3.1) = 4

    18. also contains following constants.a) M_PI 3.141593

    b) M_E 2.718282Use these constant directly in program

    .

    :- It provides functions for character processing. The following functions thislibrary is commonly used.

    1. isalpha(ch):- It return 1(true) if ch is an alphabet otherwise it return 0(false).

  • 7/23/2019 Array Initialization

    13/29

    13

    #include

    #include#include

    main(){

    char ch;printf("enter the character");

    ch = getchar();if(isalpha(ch))

    {printf("Alphabet");

    }else

    {printf("not alphabet");

    }

    }

    O/P

    Enter the character AAlphabet

    2. isdigit(ch)

    3. isspace(ch)4. isalnum(ch)

    5.

    islower(ch)6.

    isupper(ch)

    7. ispunct(ch)

    8. isascii(ch) : 0 to 127 are ASCII

    128 to 255 are non ASCII#include

    #include#include

    main(){

    char ch=154;

    if(isascii(ch)){

    printf("ASCII");}

    else{

    printf("non ASCII");}

  • 7/23/2019 Array Initialization

    14/29

    14

    }

    O/P:- non ASCII

    9. tolower(ch): It converts the given upper case into lower case letter. It ignores the

    character if it is not an upper case letter.

    void main(){

    char ch1,ch2;printf("enter the character");

    ch1=getchar();ch2=tolower(ch1);

    printf("%c",ch2);}

    O/P 1:Enter the character A

    a

    10.

    toupper(ch):- It converts lower case into upper case letter.void main()

    {char ch1,ch2;

    printf("enter the character");ch1=getchar();

    ch2=toupper(ch1);printf("%c",ch2);

    }

    O/PEnter the character a

    A

    :- It contains functions for device like keyboard, monitor , mouse etc.

    1. clrscr() :-It is used to clear the screen.

    2. getch():-It wait for key press and return ASCII code of key

    main(){

    char ch;printf("enter the character");

    ch=getch();printf("The character = %c\t%d",ch,ch);

    }O/P :- Enter the characterA

    The character = A 65

    The getch work for all the key.

  • 7/23/2019 Array Initialization

    15/29

    15

    3. getche() : It is similar to getch but it perform echo operations.

    main(){

    char ch;printf("enter the character");

    ch=getche();printf("The character = %c\t%d",ch,ch);

    }O/P :- Enter the characterA

    AEcho

    The character = A 65

    4. gotoxy(x,y) :- It transfer the control on specified x,y coordinate on screen.

    5. cprintf( ) :- It is similar to printf( ) function but it is used for colorful output.

    6. textcolor(0 to 7) :- It is used to set the color of output to display the default color is

    7(white).

    0Black

    7 whiteEx.

    #include#include

    main()

    {textcolor(3);

    cprintf("hello world");}

    (0,0) (30,0)

    (0,25) (80,25)

  • 7/23/2019 Array Initialization

    16/29

    16

    FunctionUser Defined Function C allows us to create our own function in programThe user defined function works like a pre defined function. Every C program must

    contain user defined function main (). The other user defined function main ( ). The otheruser defined function should be called in main () function, because system executes only

    the main function.

    main()

    {------

    ------------

    fun1();-------

    -------

    fun2();--------------

    fun1();}

    Fun1()

    {

    Fun3();}

    Fun2()

    {-------

    -------}

    Fun3()

    {-------

    -------

    }

    o In this program there are three independent functions.

    o Function can call other function many times.

    o System stop the execution of program after completion of main() function.

    o The function can be placed in order in program. In simple words there is noprecedence rule for functions.

    Call

    C

    a

    l

    l

    C

    a

    l

    l

    C

    a

    ll

    R

    e

    t

    u

    r

    n

    R

    e

    t

    u

    r

    n

    R

    e

    t

    u

    r

    n

    R

    e

    tu

    r

    n

  • 7/23/2019 Array Initialization

    17/29

    17

    o When we write calling statement for function, then this call is automatically linkedwith the function definition. After the completion of function control come-back to

    the calling place.o The function definition is also known as called function.

    main(){

    -----function1();

    -----}

    Function1()

    {------

    ------------

    }

    The function can be placed either before or after the calling function.

    funciton1(){

    --------

    ----}

    main()

    {----

    ----funciton1();

    ----}

    A called function can call other functions.

    call

    Return

    Call

    Calling function

    Return

  • 7/23/2019 Array Initialization

    18/29

    18

    main(){

    ----------

    function1();----

    ----}

    function1()

    {-----

    -----Function2();

    }

    Function2(){

    ----------

    -----}

    Elements of user defined functionTo create user defined we need to establish threeelements that are related to function.

    1. Function declaration2. Function call

    3.

    Function definition

    NoteIt is necessary to define or declare the function before its first call.

    Function declaration / prototype: - It shows the following information about user definedfunction.

    1. The name of function to be used.

    2. Data types of arguments that are received by called function.

    Ret

    ur

    R

    et

    ur

    n

    call

    cal

    l

  • 7/23/2019 Array Initialization

    19/29

    19

    3. Number of arguments.4. What kind of value return by function

    5. Sequence of arguments.

    The function declaration is also known as prototype of function .We can declare a functionat both inside and outside of main function.

    Use following syntax to declare a user defined function

    returntype function_name(datatypes of arguments);

    Ex. int add(int,int);Or

    Int add(int a,int b);here argument name (a,b) are optional.

    We need to write data type of each argument separately. If function is not returning anyvalue then use void as return type.

    void add(int,int);

    optional or

    void add(int a,int b);

    If function does not have argument then we can use voidas argument to shows zero

    argument.

    int add(void);/ int add();

    void add(void);/ void add();

    The void keyword is optional. Do not use it in Linux.

    Function call :- System executes only the main function so we need to call user defined

    function in main function. Use following syntax to call a user defined function.1 If function is returning value then call it as

    variablename = functionname (arguments);

    Ex.int a=5, b=7, ans;

    ans = add(a,b);

    do not specify datatype

    Note-Argument of function call is also known as Actual arguments.

    2. If function is not returning any value then call it as -

    functionname (arguments);

  • 7/23/2019 Array Initialization

    20/29

    20

    Ex. int a=5, b= 7;

    add(a,b);

    Called function /function definitionIt represent the definition function. When we callany function then system automatically create a link between function call and function

    definition and after that system transfer control to function definition. After thecompletion of function definition .The control come back to the calling statement removes

    the link.

    Use following syntax to define a function

    Returntype function_name (argument names with data types)

    {

    ----

    ----

    ----

    ----}

    Note : Do not use semicolon.

    Ex. int add(int a, int b){

    int t;t = a+b; Not Allowed

    return t;}

    The above function is receiving two integer arguments and returning an integer value.

    Ex1. Function with return type and arguments .

    #include#include

    int add(int ,int);void main()

    {int a,b,t;

    printf("enter the two numbers");scanf("%d%d",&a,&b);

    t=add(a,b);printf("the sum of %d and %d=%d",a,b,t);

    }

    int add(int x, int y)we can give any name{

    int ans;

    Return

    integer

    Call a,b

    Function body

    ;

    main add

  • 7/23/2019 Array Initialization

    21/29

    21

    ans = x+y;return ans;

    }

    Note : The arguments in called function are treated as local variable of functions. They cannot be accessed outside of function and other function.

    Ex. 2. Function with no return type but takes the arguments.

    #include#include

    void add(int ,int);void main()

    {clrscr();

    int a,b;printf("enter the two numbers");

    scanf("%d%d",&a,&b);add(a,b);

    getch();}

    void add(int x, int y)

    {int ans;

    ans = x+y;printf("the total = %d",ans);

    }

    Ex. 3 Function with zero arguments and zero return type

    #include

    #include

    void add(void);

    void main()

    {

    clrscr();

    add();getch();

    }

    void add(void)

    {

    int a,b,c;

    printf("enter the two numbers");

    Return

    No value

    Call zero

    perameter

    Return no

    value

    Call with

    two

    integer

    main addmain add

    main add

  • 7/23/2019 Array Initialization

    22/29

    22

    scanf("%d%d",&a,&b);

    c = a+b;

    printf("the total = %d",c);

    }

    Ex.4 Function with zero argument and integer return type.

    #include#include

    int add(void);void main()

    {int x;

    clrscr();x=add();

    printf("the total =%d",x);getch();

    }

    int add(void)

    {int a,b,c;

    printf("enter the two numbers");scanf("%d%d",&a,&b);

    c = a+b;return c;

    }

    Q. Write a function to find sum of digits of numbers.

    #include

    #includeint sum_of_digits(int n)

    {int d, sum=0;

    while(n>0){

    d=n%10;sum = sum + d;

    n= n/10;}

    return (sum);

    Return

    Integer value

    Call

    Zero parametermain add

  • 7/23/2019 Array Initialization

    23/29

    23

    }int main()

    {int num, ans;

    clrscr();printf("enter the number");

    scanf("%d",&num);if(num

  • 7/23/2019 Array Initialization

    24/29

    24

    STRING

    It is a set of character; the set may contain any character like alphabets, digits, special

    symbols. Basically it is a sequence of character that is treated as a single data item.

    Any group of character that is enclosed within double quotation is called string.

    ABC

    This is a computer

    If you want to include double quotes in string then use \escape character.

    Ex.1 printf(The \VGT\ kota);

    O/P: The VGT kota

    Ex.2 printf(The vgt kota);

    O/P The vgt kota

    The character strings are used to create more interactive, meaningful and readable

    programs. The following common operations we can perform on string.

    Reading and writing (scan and print) Combining string together

    Copying one string to another Comparing string

    Splitting the string into multiple string

    Reverse the string

    Convert upper case string into lower case string Convert lower case string into upper case

    Finding string in other string

    Using string: - The string is a set of character that is arranged in a sequence. C does notprovide data type string, so, to store the string we use character array.

    It means that string variable is nothing but a simple character array. The general

    form of string declaration is

    char string _name [size];

    The size represents maximum character may be stored in string.

    Ex. char name [20];

    char name [30];

  • 7/23/2019 Array Initialization

    25/29

    25

    Initialization: -String can be initialized at declaration like simple array. Compilerautomatically assign the null character at the end of string, when compiler at the end of

    string when compiler assigns the character to string.

    Null Character: \o

    The null character has ASCII code Zero.

    char name[10] = Ram;

    it is similar to

    char name[10] ={R, a, m, \0};

    0 1 2 3 4 5 6 7 8 9

    name

    C automatically initializes all the remaining elements of character array with null character

    array with null character array with null character (\o)

    C also allows to initialize character array without specifying the size. C automaticallydetermines the size from the set of initialized values.

    char name[] = RAM;

    or

    char name[]={R, A, M, \0};

    0 1 2 3

    name

    If we write

    char str[4] = computer;Then it is known as illegal initialization because length of string is greater than size of str

    array.

    String assignments:- The string is create only at declaration or compile time . Afterdeclaration of character array we cant assign any string constant to it

    Ex- char str[10];Str= abc ;

    Ex char a1[10]=computerChar a2[10];

    a2=a1;compile time error

    R A M \0 \0 \0 \0 \0 \0 \0

    R A M \0

  • 7/23/2019 Array Initialization

    26/29

    26

    The array name cant be used as left operand of = operator. In simple words array name

    cant be Lvalue.

    Operator : - C does not allows to apply operators on strings . Operators like arithmetic,Relational, logical, bitwise, increment /decrement etc.

    Char a [ ] = VGT;

    Char b [ ] =KOTA;

    Char c [ ] =a+b; compile time error

    Reading the string: - C provides following ways to read string from standard input

    scanf ( ) with format specifier % s

    scanf ( ) with %ws ,here wwidth scanf ( ) with format specifier % [a-z]

    scanf () with format specifier %[^ char] Character level input using function getchar( )

    Complete line inpute using gets( )

    scanf ( ):-Use format specifier % s . The reading of input is automatically terminated atoccurrence of either white space or new line.The scanf automatically assign \0 character at the end of string after the termination of

    reading.

    Ex- char name[20];scanf (%s, name);

    If you enter VGT KOTA, then it will read only VGT in array name.

    Note: - The & (ampersand sign) is optional in the case of character input.

    0 1 2 3 4 19

    Garbage

    It we want to read complete VGT KOTA string then we need to take two string input .

    char a1[10], a2[10];

    scanf(%s%s,a1,a2);

    It read VGT in a1 and KOTA in a2.

    scanf with %ws:- we can also specify the number of character to be read from inputstring .

    scanf(%ws, name);

    V G T \0

  • 7/23/2019 Array Initialization

    27/29

    27

    ws width in integer

    1. If width w > = number of characters typed in , then the entire string will bestored in name.

    2. w< number of character typed in , then the excess character will be truncated .3. Input automatically terminated at occurrence of blank space.

    char name[10];

    scanf(%2s,name);

    0 1 2 3 4 9

    scanf with %[------] :-

    % [A-Z]:- To read capital letters form A-Z only.% [a-z]:-To read small letters from a-z only.

    % [A-Z, a-z]:-both small and capital letters only.% [A-Z, a-z, blank space]:- capital letter, small letter and blank space.

    In this way we can specify any pattern for input.

    The following scanf () separately for input VGT KOTA

    Ex1. char name [20];

    scanf(%[a-z],name);

    0 1 2 3 4 19

    name

    Ex2. scanf(%[A-Z],name);

    0 1 2 3 4 19

    Ex3. scanf(%[A-Z, blank space],name);

    0 1 2 3 4 5 6 7 8 9 19

    Scanf with %[^------]:-

    % [^\n]:- Read until new line will occur.

    % [^A]:- Read until A will occur.

    [^ character]

    V G \0 ?

    ? ? ? ? ?

    V G T \0 ?

    V G T K O T A \0 ?

  • 7/23/2019 Array Initialization

    28/29

    28

    Terminator character

    Test following scanf statement separately for input.

    Vgt Kota

    char name[10];scanf(%s, name);

    0 1 2 3 9

    scanf(%[^ t],name);

    0 1 2 3 4 9

    scanf(%[^ \n],name);

    0 1 2 3 4 5 6 7 8 9

    Character level input using getchar():- The getchar() function is used to takesingle character input.

    If enclose the getchar() in loop then it can read complete string.

    int i=0;

    char name[10],ch;

    while((ch==getchar())!='\n') code of enter key

    {

    name[i]=ch;

    i++;

    }

    name[i]='\0';

    we have to assign null character after reading, because c does not assign null character inthis situation.

    The function gets ( ):- It takes a line input. It is automatically terminated at occurrenceof new line (\n);

    char name[10];

    V G T \0 ?

    V G \0 ? ?

    V G T K O T A \0 ?

  • 7/23/2019 Array Initialization

    29/29

    gets (name);

    If enter vgt kota then it reads the complete line into name array .

    0 1 2 3 4 5 6 7 8 9

    Writing string to screen

    We can use following techniques to display string on monitor.

    1. printf( ) function

    2. puts( ) function

    3. putchar( ) function

    V G T K O T A \0 ?