9. arrays strings

Upload: anonymous-nguzjan

Post on 06-Jul-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/17/2019 9. Arrays Strings

    1/28

    Lecture 6 of C LanguageLecture 6 of C LanguageArrays

  • 8/17/2019 9. Arrays Strings

    2/28

    Introducing ArraysIntroducing Arrays

    Array are collection of elements of samedata type.

    All elements are consecutively inmemory.

    Each element can be individually

    referenced by adding an index to aunique name.

    Uses:

    Arrays are useful when we store relateddata items.

  • 8/17/2019 9. Arrays Strings

    3/28

    Introducing ArraysIntroducing Arrays

    Examples#

    List of mar$s of students

    List of grades of studentsList of employees in an organi%ation

    List of names of students

  • 8/17/2019 9. Arrays Strings

    4/28

     Declaration ofDeclaration of an Arrayan Array

    type Array_name[size];&ere si%e indicates the maximum number

    of elements.

     'he subscript value start from 0 to size-1.

    Example#

      int number()*+,  -oat number()*+,

      char grade()*+,

  • 8/17/2019 9. Arrays Strings

    5/28

     Initialising an ArrayInitialising an Array

    An array is initiali%ed after it is declared. 'he following array can hold mar$s of ve

    sub/ects#

      int mar$s(0+,

    An array can be initiali%ed in following ways:

    First approach:  'he value of each element islisted within two curly brac$ets 1 2 and a comma

    345is used to separate one element from another.

    E! mar"s [#] $ %##& '0& (0& )0& *0+

  • 8/17/2019 9. Arrays Strings

    6/28

    Initialising an ArrayInitialising an Array

    ,econ- approach:elements of array can be initilised one at a time.

    Ex. mar$(*+ 00,

      mar$()+ 6*,

      mar$(7+ 8*,

      mar$(9+ :*,

      mar$(8+ ;*,

    !ote# In an array index of rst element is considered

    as %ero. 'herefore in an array of n  elements rst index is 0 

    and last index is n./.

  • 8/17/2019 9. Arrays Strings

    7/28

    Initialising an ArrayInitialising an Array

    void main35

    1int A[/0]&i4/4temp,

     printf3?Enter )* numbers@5,

     for3i*, i=)*, i5 scanf3?Bd@4A(i+5,

  • 8/17/2019 9. Arrays Strings

    8/28

    Di%e of an ArrayDi%e of an Array

    nce an array is declared4 its si%e isxed.

    After that it can not changed.

    Ex. int A()*+,

    Can store only )* elements 3A(*+ toA(;+5.

  • 8/17/2019 9. Arrays Strings

    9/28

    Initialising an ArrayInitialising an Array

    Feclaring4 creating and initilising insingle step#

    int mar$s(0+10*4 6*4 8*4 :*4 ;*2

  • 8/17/2019 9. Arrays Strings

    10/28

    Gultidimensional ArrayGultidimensional Array

     'he type of array that we have discussed tillnow is single -imensional array as it hasonly single index.

    wo -imensional arrays also calle- as matri!wo -imensional arrays loo"s li"e this:

    Row 0

    Row 1

    Row 2

    Row 3

    Column 0 Column 1 Column 2 Column 3

  • 8/17/2019 9. Arrays Strings

    11/28

    Declaration: 12lti-imensionalDeclaration: 12lti-imensional

    ArrayArraytype array_name[row_size][col2mn_size];

     row_size H>!umber of rows in matrix

     col2mn_size H> !umber of columns in matrix

    E:  e can declare an array to store )**students mar$s for ve sub/ects.

      int mar"s[/00][#];Eamples:

    int n2m3er[(][4]; 56 /7 elements 65

      8oat n2m3er[4][7]; 56 ' elements 65

      char name[/0][70]; 56 700 chars 65

  • 8/17/2019 9. Arrays Strings

    12/28

    Initiali%ation of a 7JF ArrayInitiali%ation of a 7JF Array

    int a[2][3]={1,2,3,4,5,6};

    int a[2][3]={{1,2,3}, {4,5,6}};

    int a[][3]={{1,2,3}, {4,5,6}}

    int a[2][3]={0}

    Following initializations are not allowed 

    int a[3][]={2,4,6,8,10,12};

    int a[][]={2,4,6,8,10,12}; 

    !ote#  If the rst brac$et pair is empty4 thencompiler ta$e the si%e from the number of innerbrace pairs

  • 8/17/2019 9. Arrays Strings

    13/28

    ExampleExample9incl2-e st-io!h

    9-e

  • 8/17/2019 9. Arrays Strings

    14/28

    Gemory Gap for 7JFGemory Gap for 7JF

    ArraysArraysKept in memory as a linear sequence of variables. 'wo methods for storingJ◦ Gow ma@or

    ◦ Hol2mn ma@or

    Example#int a[4][4];

    Gow ma@or storage:

    a[0][0]& a[0][/]& a[0][7]& a[/][0]& a[/][/]&a[/][7]& a[7][0]& a[7][/]& a[7][7]

    Hol2mn ma@or storage:

    a[0][0]& a[/][0]& a[7][0]& a[0][/]& a[/][/]&a[7][/]& a[0][7]& a[/][7]& a[7][7]

  • 8/17/2019 9. Arrays Strings

    15/28

    DtringsDtrings

  • 8/17/2019 9. Arrays Strings

    16/28

    DtringsDtrings

    •  'he way a group of integers can bestored in an integer array4 similarly agroup of characters can be stored in acharacter array. Character arrays aremany a time also called strings.

    • A string is a oneJdimensional array ofcharacters terminated by a null 3 M*N 5.

    • !ormally each character is stored in onebyte4 successive characters are storedin successive bytes.

  • 8/17/2019 9. Arrays Strings

    17/28

    !ull Character!ull Character

     'he terminating null 3M*N5 is important4because it is the only way to $nowwhere the string en-s. In fact4 a

    string not terminated by a M*N is notreally a string4 but merely a collectionof characters.

  • 8/17/2019 9. Arrays Strings

    18/28

    Feclaring stringsFeclaring strings

    Char stringname(si%e+,

     'he si%e determines the number of charactersin the string name.

    Eample:

     char monthname()7+,  char address()**+,

     'he si%e of the array should be one 3ytemore than the act2al space occ2pie- bythe string since the complier appends anull character at the end of the string.

  • 8/17/2019 9. Arrays Strings

    19/28

    Initializing ,tringsInitializing ,trings

    char month( +1/N4NaN4NnN4NuN4NaN4NrN4NyN 4NM*N2,

      r

    char month( +1@/anuary@2,

     'hen the string month is initiali%ing to Panuary. 'his is perfectly valid but C o"ers aspecial way to initiali%e strings. 'he

    above string can be initiali%ed charmonth)(+@Panuary@. 'he characters ofthe string are enclosed within a part ofdouble quotes.

  • 8/17/2019 9. Arrays Strings

    20/28

    Dtring Initiali%ation#Dtring Initiali%ation#

    char str(;+ ?I li$e C@,  same as

    char str(;+1IN4 4NlN4iN4N$N4NeN4 4NCN4NM*N2,

    Q. Is there any di"erence between followingInitiali%ationR

    char str(+?I'G@,

    char str(8+ ?I'G@,

    Ans# Ses4 in second declaration there is no nullcharacter 

  • 8/17/2019 9. Arrays Strings

    21/28

    Gea-ing ,trings from the terminal:Gea-ing ,trings from the terminal:

    •  'he function scanf with Bs formatspecication is needed to readthe character string from the terminal.

    Eample:

    char address()0+,scanf3?Bs@4address5,

    Dcanf statement has a -raw 3ac" it /ust

    terminates the statement as soon as it nds ablan$ space4 suppose if we typethe string New Jor" then only the string !ew will be read and since there is a blan$ spaceafter word NewC it will terminate the string.

  • 8/17/2019 9. Arrays Strings

    22/28

    22

    Arrays of DtringsArrays of DtringsDeclaration: 

    char name[#][40];

    Tive strings each contains maximum thirty characters.

    Initialization:char[#]

    [/0]$%KneC&CwoC&ChreeC&CFo2rC&CFi=eC+;

    Kther =ali- -eclarationschar[][]$%KneC&CwoC&ChreeC&CFo2rC&CFi=eC+;

    char[#][]$%KneC&CwoC&ChreeC&CFo2rC&CFi=eC+;

  • 8/17/2019 9. Arrays Strings

    23/28

    Copying DtringCopying Dtring

    • we cannot assign one string to another directly.

    For eample:

    Dtring)@xy%@,Dtring7string),

    Are not valid.

    •  'o copy the chars in one string toanother string we may do so on acharacter to character 3asis.

  • 8/17/2019 9. Arrays Strings

    24/28

    ,tring operations >string!h?,tring operations >string!h?

    • C library supports a large numberof string handling functions that can be usedfor string manipulations such as#

    • Length 3number of characters in the string5.

    • Concatenation 3adding two are more strings5• Comparing two strings. 3if equal or not5• Copy3copies one string over another5

    •  'o do all the operations described here it isessential to include string.h library header le inthe program.

  • 8/17/2019 9. Arrays Strings

    25/28

    strlen>? f2nction:strlen>? f2nction:

    •  'his function counts and returns the numberof characters in a string. 'he length does not include anull character.

    ,ynta•

    nstrlen3string5,here n is integer variable. hich receives the valueof length of the string.

    Eample

    lengthstrlen3?&ollywood@5,•

     'he function will assign number of characters ; in thestring to a integer variable length.

  • 8/17/2019 9. Arrays Strings

    26/28

    strcat>? f2nction:strcat>? f2nction:

    • when you combine two strings4 you add the characters

    of one string to the end of other string. 'his process iscalled concatenation. It ta$es the following form

    strcat>string/&string7?

    string) string7 are character arrays. hen thefunction strcat is executed string7 is appended tostring).

    Eample

    strcpy3string)4@deep@5,strcpy3string74@$amal@5,

    strcat3string)4string75,

    Trom the above program segment the value of string)

    becomes deep$amal. 'he string at str7 remainsunchanged as $amal.

  • 8/17/2019 9. Arrays Strings

    27/28

    strcmp f2nction:strcmp f2nction:• In C you cannot directly compare the value of 7 strings in a condition

    li$e if3string)string75

    Gost libraries however contain the strcmp35 function4 which ret2rns azero if 7 strings are equal4 or a non zero n2m3er if the strings arenot the same.

     'he syntax of strcmp35 is given below#

    ,trcmp>string/&string7?

    Eample:

    strcmp3?!ewyor$@4@!ewyor$@5 will return %ero because 7 strings are

    equal.

    strcmp3?their@4@there@5 will return a ; which is the numeric di"erencebetween ADCII iN and ADCII NrN.

    strcmp3?'he@4 ?the@5 will return 97 which is the numeric di"erence

    between ADCII ?'@ ADCII ?t@.

  • 8/17/2019 9. Arrays Strings

    28/28

    strcpy>? f2nction:strcpy>? f2nction:• C does not allow you to assign the characters to a

    string directly as in the statement name@Uobert@,Instead use the strcpy function found in mostcompilers.

    • syntax

    strcpy>string/&string7?;•Dtrcpy function assigns the contents of string7 tostring). string7 may be a character array variable ora string constant.

    strcpy3!ame4@Uobert@5,•

    In the above example Uobert is assigned to thestring called name.