Write a program that solves exercises 13 or 15 If you solve

Write a program that solves exercises 1.3 or 1.5. If you solve both correctly, 20 extra points will be given. For Exercise 1.3, you can use only the following C++ function or its Java equivalent to output the results of your program:

void printDigit(char c ){
    if (c==\'-\' || c==\'+\' || c==\'.\' || c == \'\ \' || (c>=\'0\' && c<=\'9\')){
        cout << c;
        return;
    }
    
    cout << \"Invalid characters.\" << endl;
    return;
    
}

Exercise 1.3

Write a function to output an arbitrary double number (which might be negative) using only printDigit for I/O.

Exercise 1.5

Write a recursive function that returns the number of 1 in the binary representation of N . Use the fact that this is equal to the number of 1 in the representation of N/ 2, plus 1, if N is odd.

Solution

exercise 1.3:

public class Exercice_1_3 {

   public static void main(String[] args) {
       printOut(1329);
   }

   // Recursive method that prints a positive integer one character at a time
   public static void printOut(int n) {
       if (n&gt;= 10) {
           printOut(n / 10);
       }
       printDigit(n % 10);
   }

   public static void printDigit(int n) {
       if (0 &lt;= n &amp;&amp; n &lt;= 9) {
           System.out.print(n);
       }
   }
}

exercise 1.5:

/* Function to get no of set bits in binary

   representation of passed binary no. */

unsigned int countSetBits(unsigned int n)

{

  unsigned int count = 0;

  while(n)

  {

    count += n & 1;

    n >>= 1;

  }

  return count;

}

/* Program to test function countSetBits */

int main()

{

    int i = 9;

    printf(\"%d\", countSetBits(i));

    getchar();

    return 0;

}

Write a program that solves exercises 1.3 or 1.5. If you solve both correctly, 20 extra points will be given. For Exercise 1.3, you can use only the following C
Write a program that solves exercises 1.3 or 1.5. If you solve both correctly, 20 extra points will be given. For Exercise 1.3, you can use only the following C

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site