Write a program which takes two integers (num1 and num2) as input from the user.
Your program should display on the screen the result of i) num1 + num2, ii) num1 * num2, and iii) num1 - num2.
You are not allowed to use the + or - or * operators. E.g., cout<<num1+num1<<num1*num2<<num1-num2; is not allowed. += or -= or *= operators are also not allowed.
You HAVE TO USE loops and the ++ and -- operators. Code for num1+num2 is already available in the slides. Use that for this assignment.
Here is the code:
#include <iostream>
int sum(int a, int b)
{
if (b < 0)
for (int i = 0; i > b; i--) a--;
else
for (int i = 0; i < b; i++) a++;
return a;
}
int diff(int a, int b)
{
if (b < 0)
for (int i = 0; i > b; i--) a++;
else
for (int i = 0; i < b; i++) a--;
return a;
}
int mult(int a, int b)
{
int ab = 0;
if (b < 0)
for (int i = 0; i > b; i--) ab = diff(ab, a);
else
for (int i = 0; i < b; i++) ab = sum(ab, a);
return ab;
}
int main()
{
int num1, num2;
std::cin >> num1 >> num2;
std::cout << num1 << " + " << num2 << " = " << sum(num1, num2) << std::endl;
std::cout << num1 << " * " << num2 << " = " << mult(num1, num2) << std::endl;
std::cout << num1 << " - " << num2 << " = " << diff(num1, num2) << std::endl;
return 0;
}
Comments
Leave a comment