Robson » Little Red Book » Divisor

Chapter 4 - Question 2

Produce a program that test, for two input integers, whether the second divides exactly into the first.

Solution 1

At the time of writing I'm starting to learn c++, so I decided to write the solution in that language instead of PHP.

#include <iostream.h>
int main ()
{
   int iFirst, iSecond;
   cout << "This program will check if a number can be divided into another number.\n";
   cout << "Enter the first number.\n>";
   cin >> iFirst;
   cout << "Enter the second number.\n>";
   cin >> iSecond;
   if (iFirst % iSecond)
       cout << iSecond << " doesn't divide exactly into " << iFirst << ".";
   else
       cout << iSecond << " divides exactly into " << iFirst << ".";
   return 0;
}

Which produces:

Divisor program

Solution 3

Here's the same application with a different implementation.

Use:

C:\code>divisor 9 3
3 divides exactly into 9
C:\code
#include <stdio.h>
#include <stdlib.h>
 
using namespace std;
 
int main(int argc, char **argv)
{
   int n1 = atoi(argv[1]);
   int n2 = atoi(argv[2]);
   
   if (n1 % n2)
      printf("%d doesn't divide into %d", n2, n1);
   else
      printf("%d divides exactly into %d", n2, n1);
}

Log

© 2004-17 robson | cc unless stated