Thursday, May 13, 2010

Answer and Explanation to Operand Example

Hey there fellow OOP344 students. Today's pop quiz thing went by pretty quick so I figured I'd show you guys the solution and explain it.

***ANSWER***

int main()
{
int i;
int n=0;
int j[10]={1,0,3,4,0,7,8,2,0,1};

for(i=0;10>i; i++)
{
n+=!j[i]; /*LINE OF CODE WANTED */
}

}

So in order to calculate the numbers of 0's within j's array [within one line], we must use the method taught today.

Firstly, remember 0 = FALSE, and 1 or greater than 1 = TRUE.

NOT (a number greater than 0) Returns FALSE; Aka NOT TRUE = FALSE.
so NOT (0) Returns TRUE; Aka NOT FALSE = TRUE.

So if the number in the array j[i] = 0, the expression !j[i] will become !0 Returns TRUE.
TRUE = 1, as we all should know.
So in conclusion, n+=1; adds one when j[i] = 0, adding all 0's.

If there is any confusion with the above, don't hesitate to ask me to try and clarify a bit more.

No comments:

Post a Comment