Friday, October 28, 2011

Techniques: Divisibility, Odd, Even, Exchanges, On, Off, Toggle.


Techniques1

Divisibility

1.  Write an expression that evaluates to true if the value of the integer variable numberOfPrizes is divisible (with no remainder) by the integer variable numberOfParticipants.  Assume that numberOfParticipants is not zero.
Example:  So if numberOfPrizes had the value 42 and numberOfParticipants had the value 7 then your expression would be true because 42 is divisible by 7 with no remainder.

On the other hand, if numberOfPrizes had the value 34 and numberOfParticipants had the value 8 then your expression would be false because when 34 is divided by 8, the remainder is 2.


(numberOfPrizes%numberOfParticipants==0)


2.  Write an expression that evaluates to true if the value of the integer variable widthOfBox is not divisibleby the value of the integer variable widthOfBook.  Assume that widthOfBook is not zero.  ("Not divisible" means has a remainder.)

(widthOfBox%widthOfBook!=0)


OddEven

1.  Write an expression that evaluates to true if the integer variable x contains an even value, and false if it contains an odd value.

(x%2==0)


Exchanges

1.  Given two int variables, i and j, which have been declared and initialized, and two other int variables, itemp and jtemp, which have been declared, write some code that swaps the values in i and j by copying their values to itemp and jtemp respectively, and then copying itemp and jtemp to j and i respectively.

jtemp=i;
itemp=j;
j=jtemp;
i=itemp;


2.  Given three already declared int variables, i, j, and temp, write some code that swaps the values in i and j.  Use temp to hold the value of i and then assign j's value to i.  The original value of i, which was saved in temp, can now be assigned to j.

temp=i;
i=j;
j=temp;


3.  Given two int variables, firstPlaceWinner and secondPlaceWinner, write some code that swaps their values.  Declare any additional variables as necessary.

int temp=firstPlaceWinner;
firstPlaceWinner=secondPlaceWinner;
secondPlaceWinner=temp;


4.  Given two double variables, bestValue and secondBestValue, write some code that swaps their values.  Declare any additional variables as necessary.

double temp=bestValue;
bestValue=secondBestValue;
secondBestValue=temp;


5.  Given an array arr, of type int, along with two int variables i and j, write some code that swaps the values of arr[i] and arr[j].  Declare any additional variables as necessary.

int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;


OnOffToggle

1.  Write a statement that toggles the value of onOffSwitch.  That is, if onOffSwitch is false, its value is changed to true; if onOffSwitch is true, its value is changed to false.

if(onOffSwitch==false)
{
onOffSwitch=true;
}
else
{
onOffSwitch=false;
}




No comments:

Post a Comment