Entries Tagged as 'Programming'

Answer for Prog Trivia

The answer involves the mathematical concept. It is the beauty of maths. The user must be left with the least number, that is 1. If it is more than 1, then the user can tell some other number so that the computer is left with 1. Actually assume that the first no given by the computer be x.

Now, consider
Computer : x 6 5
User : 3 4 1

In this example listen that the user has to pick 1. Because there is no other option for him.
Similarly the computer must give the number so that the sum of the previous number given by the user and the number that is going to be given by the computer must be 9. Because it is the maximum number. Now we have to find the x. The total should not exceed 25.

x+some multiple of 9 + 1(the last no which the user necessarily has to select)= 25
now x+9n=24.
when we put n=2(the max value that can be taken by n so that 9n does not exceed 24)
we will get x to be 6.

So the computer has to give the first number as 6 and the corresponding numbers must be (9-the previous no given by the user) .

This can be implemented by simple while and if conditions in C or in C++.

If this answer is confusing please post. I will explain

Programming Trivia

Hi everybody, I am posting a programming puzzle. I hope this will be interesting. Try solving this and post your answers.

Jenni and Computer are playing a math game. Both of them can choose any number x, such that 1<=x<=8. To start with, each player take their turns alternatively until the total becomes exactly 25. The one who gives the last number loses the game. Both of them play intelligently and they try to win the game. The computer gives the first number.

Write a C/C++ program so that the Computer always wins the game.

Print an error message whenever the total goes beyond 25.

Try this puzzle and i will post the answer in my next post

Java Enhanced for loop

Enhance for loop is one of the features of Java 5.0. The syntax of this for loop is

int sum(int a[])
{
int sum=0;
for (i:a)
    sum += i;
return sum
 }

The above function returns the sum of all the elements of the array a. As it is clearly seen from the coding the no of lines have been reduced. It uses a : operator. This type of loop is very much useful when we want to use function overloading. We need not define a separate function for every set of parameters. A single function will work for different type/number of parameters.

C Puzzles

The swapping of two numbers can be done with a temporary variable as follows. Many of us use this method.

t=a;

a=b;

b=t;

The swapping can also be done without using the temporary variable as follows.

a=a+b;

b=a-b;

a=a-b;

This can also be done using another method.

a^=b;

b^=a;

a^=b;

The xor operator is used here.