java - What exactly does this piece of code do? -
i beginner programmer,
i have array called myarray , wanting know if statment in code does. myarray[count] do?
for(int = 0; < count; i++) if (number == myarray[i]) { containsnumber = true; } if ( !containsnumber ) { myarray [ count ] = number; count++; } // end if
cheers
notice
because code not complete have assumptions:
- all variables declared , initalized before
count
represents number of elements in array- the array sufficiently sized
containsnumber
initalizedfalse
short
it checks if given number exists in array , if not add it.
explained
at first, make bit more readable can add 2 braces after instruction:
for(int = 0; < count; i++) { if (number == myarray[i]) { containsnumber = true; } } if ( !containsnumber ) { myarray [ count ] = number; count++; } // end if
because there no breaces after for
affect following statement or block, if
statement.
at first code loop through array , check every position smaller count
(value of i
) given number.
if value found (if (number == myarray[i])
) variable containsnumber
set true
.
after iterating on array variable containsnumber
checked.
an if
statement must contain boolean value, can write if (containsnumber)
instead of if (containsnumber == true)
.
the !
negates boolean value. means check if containsnumber
not true. if (containsnumber != true)
or if (containsnumber == false)
same.
if number not in array (containsnumber
false
) added @ next position (myarray [ count ] = number;
) , count
incremented 1 (count++;
).
example
let's array contains values 1
, 5
, 7
. number has value 4
, count 3
because array contains 3
elements.
for loop:
first iteration
i
has value 0
--> 0
smaller 3
(count
)
if (number == myarray[i])
--> if (4 == myarray[0])
--> if (4 == 1)
--> false
second iteration
i
has value 1
--> 1
smaller 3
(count
)
if (number == myarray[i])
--> if (4 == myarray[1])
--> if (4 == 5)
--> false
third iteration
i
has value 2
--> 2
smaller 3
(count
)
if (number == myarray[i])
--> if (4 == myarray[2])
--> if (4 == 7)
--> false
fourth iteration
i
has value 3
--> 3
not smaller 3
(count
)
for
ends
next step
containsnumber
still false
if ( !containsnumber )
--> value of containsnumber
negated means if (true)
myarray [ count ] = number;
--> myarray [ 3 ] = 4;
the value of number
(4
) set fourth position of array (remember, array starts 0
).
now array contains values 1
, 5
, 7
, 4
.
Comments
Post a Comment