Binary math programming - c++

I have been asked to create a program that takes 2 binary numbers then outputs the result of adding, subtracting and multiplying them. My code works for addition but when I try to do subtraction or multiplication, the output is not as expected. The cout statement is displayed with each digit and several of the digits are incorrect. Could anyone point to flaws in my code?
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
long num1, num2;
int choice;
int i = 0, r = 0, sum[20];
cout << "Enter the first binary number: "; //prompts user to input binary values to perform arithmetic on
cin >> num1;
cout << "Enter the second binary number: ";
cin >> num2;
cout << "To add the numbers press 1, to subtract the numbers press 2," << endl; //prompts user to choose which operation to perform
cout << "to multiply the numbers press 3" << endl;
cin >> choice;
if (choice != 1 & choice != 2 & choice != 3) //if statement to test for valid input
{
cout << "Please enter a valid choice: ";
cin >> choice;
}
if (choice == 1)
{
while (num1 != 0 || num2 != 0) //if user chooses 1, perform binary arithmetic
{
sum[i++] = (num1 % 10 + num2 % 10 + r) % 2;
r = (num1 % 10 + num2 % 10 + r) / 2;
num1 = num1 / 10;
num2 = num2 / 10;
}
if (r != 0)
sum[i++] = r;
--i;
cout << "The sum of the two numbers is: ";
while (i >= 0)
cout << sum[i--];
cout << ". ";
}
if (choice == 2)
{
while (num1 != 0 || num2 != 0) //if user chooses 2, perform binary subtraction
{
int i = 0, r = 0, diff[20];
diff[i++] = (num1 % 10 - num2 % 10 + r) % 2;
r = (num1 % 10 - num2 % 10 + r) / 2;
num1 = num1 / 10;
num2 = num2 / 10;
if (r != 0)
diff[i++] = r;
--i;
cout << "The difference of the two numbers is: ";
while (i >= 0)
cout << diff[i--];
cout << ". ";
}
}
if (choice == 3) //if user chooses 3, perform binary multiplication
{
while (num1 != 0 || num2 != 0)
{
int i = 0, r = 0, product[20];
product[i++] = (num1 % 10 * num2 % 10 + r) % 2;
r = (num1 % 10 * num2 % 10 + r) / 2;
num1 = num1 / 10;
num2 = num2 / 10;
if (r != 0)
product[i++] = r;
--i;
cout << "The product of the two numbers is: ";
while (i >= 0)
cout << product[i--];
cout << ". ";
}
}
system("pause");
return 0;
}

You may like to try something
int binary2decimal(int n) /* Function to convert binary to decimal.*/
{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;
}
return decimal;
}
int main()
{
....
....
if(!num1 || !num2)
{
cout << "Result = 0";
exit(0);
}
.....
switch(choice)
{
case 1:
int r = binary2decimal(num1) + binary2decimal(num2);
cout << "Result = " << r;
break;
case 2:
int r = binary2decimal(num1) - binary2decimal(num2);
cout << "Result = " << (r>=0) ? r : -r;
break;
case 3:
int r = (num1 & num2) ?
binary2decimal(num1) * binary2decimal(num2) : 0;
cout << "Result = " << r;
break;
default:
cout << "Enter a valid choice next time";
break;
}
.....
}

Related

C++: When entering numbers into array first number is 0

Trying to make a calculator that calculates values in an array based on input from user. But the first value in the array is always 0 when I leave 'p undefined or p = 1 will have give me the same problem. It should be whatever the user enters for the first value and so on.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
The sum should be 3 not 4.
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4
The program is invalid and has undefined behavior.
For starters variable length arrays is not a standard C+ feature
int p = 1, y = 0;
double sum = 1;
int many[p];
And in any case you defined an array with one element. So the only valid index to access elements of the array is 0.
Even in the first statement that uses the array
cin >> many[p];
it is accessed outside its bounds.
You should use the standard class template std::vector. Or as in fact you are dealing with one value then there is even no sense to use a container, Define a scalar object instead of the array.
The initial value of the sum is 1, that's why it is adding 1 more. We can't keep it 0 either, because then it will mess up the '*' and '/' cases.
I have added the initial sum value for all the cases.
Also, I would suggest you, to use switch cases instead of if, else statements.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
if (y == 0) {
sum = 0;
}
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
if (y == 0) {
sum = 0;
}
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
if (y == 0) {
sum = 1;
}
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
if (y == 0) {
sum = 1;
}
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
There are a lot of things here that don't make sense.
You are starting with sum = 1. this is why the value is always +1
many is an array of size 1, can be changed to single int.
you are accessing many[p] which is many[1] which is out of bounds. you can only access many[0]
the rest I leave it to you to find,

find number of occurances of specific digit with a counter in C++

I have a large number whereby i want to find the number of occurances of a specified digit. I wonder is using a counter will work. My code as follows:
#include <iostream>
using namespace std;
int main( )
{
int number;
int n1;
int n2;
int n3;
int n4;
int n5;
int n6;
int n7;
int n8;
int n9;
int n10;
int digit;
int digitCounter = 0;
cout << "Please enter a number between 100 to 2000000000." << endl;
cin >> number;
cout << "Please enter a digit that you want to find the number of occurances." << endl;
cin >> digit;
if (number > 0)
{
n1 = number % 10;
n2 = (number/10) % 10;
n3 = (number/100) % 10;
n4 = (number/1000) % 10;
n5 = (number/10000) % 10;
n6 = (number/100000) % 10;
n7 = (number/1000000) % 10;
n8 = (number/10000000) % 10;
n9 = (number/100000000) % 10;
n10 = (number/100000000) % 10;
if (n1 == digit)
{ digitCounter++;}
else if (n2 == digit)
{ digitCounter++;}
else if (n3 == digit)
{ digitCounter++;}
else if (n4 == digit)
{ digitCounter++;}
else if (n5 == digit)
{ digitCounter++;}
else if (n6 == digit)
{ digitCounter++;}
else if (n7 == digit)
{ digitCounter++;}
else if (n8 == digit)
{ digitCounter++;}
else if (n9 == digit)
{ digitCounter++;}
else if (n10 == digit)
{ digitCounter++;}
cout<< "The total number of occurances of " << digit << " in " << number <<" is "<<digitCounter<< endl;
}
else
cout<< "You have entered an invalid number."<<endl;
system("pause");
return 0;
}
However the counter is not working. Can someone advise what wet wrong?
Any help is really appreciated, thanks.
You can cast your number into a string after that you search the digit in the string it's simpler.
Or you can read a character string (number) and a character (digit) and then you do like that :
char number[20], digit;
int count = 0, i;
printf("\nEnter a string : ");
scanf("%s", &number);
printf("\nEnter the character to be searched : ");
scanf("%c", &digit);
for (i = 0; number[i] != '\0'; i++) {
if (number[i] == digit)
count++;
}
if (count == 0)
printf("\nCharacter '%c'is not present", digit);
else
printf("\nOccurence of character '%c' : %d", digit, count);`
Your Else If's need to be If's. As it stands now you only go through one decision statement. As soon as it finds a match you're out.
#include <iostream>
using namespace std;
int main()
{
int number;
int n1;
int n2;
int n3;
int n4;
int n5;
int n6;
int n7;
int n8;
int n9;
int n10;
int digit;
int digitCounter = 0;
cout << "Please enter a number between 100 to 2000000000." << endl;
cin >> number;
cout << "Please enter a digit that you want to find the number of occurances." << endl;
cin >> digit;
if (number > 0)
{
n1 = number % 10;
n2 = (number / 10) % 10;
n3 = (number / 100) % 10;
n4 = (number / 1000) % 10;
n5 = (number / 10000) % 10;
n6 = (number / 100000) % 10;
n7 = (number / 1000000) % 10;
n8 = (number / 10000000) % 10;
n9 = (number / 100000000) % 10;
n10 = (number / 100000000) % 10;
if (n1 == digit)
{
digitCounter++;
}
if (n2 == digit)
{
digitCounter++;
}
if (n3 == digit)
{
digitCounter++;
}
if (n4 == digit)
{
digitCounter++;
}
if (n5 == digit)
{
digitCounter++;
}
if (n6 == digit)
{
digitCounter++;
}
if (n7 == digit)
{
digitCounter++;
}
if (n8 == digit)
{
digitCounter++;
}
if (n9 == digit)
{
digitCounter++;
}
if (n10 == digit)
{
digitCounter++;
}
cout << "The total number of occurances of " << digit << " in " << number << " is " << digitCounter << endl;
}
else
cout << "You have entered an invalid number." << endl;
system("pause");
return 0;
}
try this
#include <iostream>
int main(int argc, char **argv) {
unsigned long long large(0);
int digitToFind(0);
std::cout << "enter a large number [100 to 2000000000]" << std::endl;
std::cin >> large;
if (large < 100 || large > 2000000000) {
std::cout << "invalid input." << std::endl;
return -1;
}
std::cout << "enter the digit to find" << std::endl;
std::cin >> digitToFind;
if (digitToFind < 0 || digitToFind > 9) {
std::cout << "invalid input." << std::endl;
return -1;
}
std::size_t counts[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
while (large > 0) {
int rem = large % 10;
counts[rem]++;
large /= 10;
}
std::cout << "number of occurrances of " << digitToFind << " is "
<< counts[digitToFind] << std::endl;
std::cout << "press enter to continue" << std::endl;
std::cin.get();
return 0;
}
Some of the sample codes contain another flaw: if the number is small then we get more zeroes than necessary...we cannot assume that the number is necessarily big.
This works for each number, in Python only because I'm more used to Python at the moment, it is straightforward to convert it to C:
N = 1230533007
digitToFind = 3
digitCount = 0
while N > 0:
d = N % 10
if d == digitToFind:
digitCount += 1
N //= 10
print digitCount

How do i continue this while

Im stuck with this program. What program does is to take a integer from user and display all number that are left after cutting the even numbers.
int main(){
long n, minder=0;
int cdonr, power=1;
cout<<"Give a positive number "<<endl;
cin>>n;
while (n>0){
cdonr=n%10;
if(cdonr % 2 != 0){
minder=minder+cdonr*power;
power=power*10;
}
n=n/10;
}
cout<<"The number that is left after all even number " << endl;
cout<<minder<<endl;
cout<<"Give a positive nr "<<endl;
cin>>n;
}
Can someone help me with this while because after it split the first numbers it gives no response at the second one.
Thanks to people on this community this is the answer
#include<iostream>
using namespace std;
int main() {
long n, minder = 0;
int cdonr, power = 1;
cout << "Give a positive number " << endl;
cin >> n;
while (n > 0) {
while (n > 0) {
cdonr = n % 10;
if (cdonr % 2 != 0) {
minder = minder + cdonr * power;
power = power * 10;
}
//always zero so we need a nested while loop
n = n / 10;
}
cout << "The number that is left after all even number " << endl;
cout << minder << endl;
//have to set values to default so they do not hold previous values
minder = 0;
cdonr = 0;
power = 1;
//we can reprompt user for a value
//n will get set and it validates with the outer while loop
//this allows it to run as many times as valid inputs
cout << "Give a positive number " << endl;
cin >> n;
}
}
Another answer as requested by user, exits upon == 0, <= 0, and not a number
#include<iostream>
using namespace std;
int main() {
long n, minder = 0;
int cdonr, power = 1;
cout << "Give a positive number " << endl;
cin >> n;
while (n > 0) {
while (n > 0) {
cdonr = n % 10;
if (cdonr % 2 != 0) {
minder = minder + cdonr * power;
power = power * 10;
}
//always zero so we need a nested while loop
n = n / 10;
}
cout << "The number that is left after all even number " << endl;
cout << minder << endl;
//have to set values to default so they do not hold previous values
minder = 0;
cdonr = 0;
power = 1;
//we can reprompt user for a value
//n will get set and it validates with the outer while loop
//this allows it to run as many times as valid inputs
cout << "Give a positive number " << endl;
cin >> n;
}
}
Try this, it is not infinite and you can do it as many times as you want by calling the function.
#include<iostream>
using namespace std;
void function(long n, long minder, int cdonr, int power) {
while (n > 0) {
cdonr = n % 10;
if (cdonr % 2 != 0) {
minder = minder + cdonr * power;
power = power * 10;
}
n = n / 10;
}
cout << "The number that is left after all even number " << endl;
cout << minder << endl;
}
int main() {
long n, minder = 0;
int cdonr, power = 1;
//can add a while loop here or just use a for
// if you know how many times you want
cout << "Give a positive number " << endl;
cin >> n;
if(n > 0){
function(n, minder, cdonr, power);
}
//probably add an else here in case of == 0 or < 0
// or just loop back if while
}
If you really want to do something forever, loop on it.
i.e. put your "function" to be repeated in a loop.
(And consider pulling it out to be an actual function)
int main() {
using namespace std;
while (true)
{
long n, minder = 0;
int cdonr, power = 1;
cout << "Give a positive number " << endl;
cin >> n;
while (n > 0) {
cdonr = n % 10;
if (cdonr % 2 != 0) {
minder = minder + cdonr*power;
power = power * 10;
}
n = n / 10;
}
cout << "The number that is left after all even number " << endl;
cout << minder << endl;
}
}

C++: How do I make this shape from this code?

I am trying to make this shape from the code below. I'm confused as to how to make it print the 2nd row, second to last star without it skipping and printing the extra space before printing the star. Once that is figured out would the bottom half, when the stars expands back out, would the code be similar to the top half? I have tried a couple combinations of code between c and r but I have been stuck with what I currently.
---------------------- //row 0
* *| //row 1
* * * *| //row 2
* * * * * *|
* * * * * * * *|
* * * * * * * * * *|
* * * * * * * * * * *|
* * * * * * * * * *|
* * * * * * * *|
* * * * * *|
* * * *|
* *|
----------------------
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
for (int c = 0; c < num; ++c) //inner loop/columns
{
if (r == 0) cout << "--"; //top of square
else if (c >= r + r - c && c < num - 1)
cout << " ";
//else if (c == num - 1) cout << "*|";
else if (r == num - 1) cout << "--"; //bottom of square
else if (c == num - 1) cout << "*|"; //right side of square
else if (r > c) cout << "* ";
}
cout << endl;
}
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
I just took two variables left=0 & right=num-1 and increased left & decreased right till r<=num/2, after that i reversed the process,when the col <= left or col >=right I printed *.
I hope it will be easy to understand.
Here is the code:
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
int left=0,right=num-1;
//for printing top line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
//printing columns
for(int c = 0; c < num; c++)
{
if(c <= left || c >= right)
cout<<"* ";
else
cout<<" ";
}
if(r >= num/2) //checking for half of the rows
{
left--;right++;
}
else
{
left++;right--;
}
cout<<"|"<<endl;
}
//for printing last additional line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
This approach does it the math way.
Furthermore it draws a full frame with plus-chars at the edges.
Give it a try.
#include <iostream>
#include <cmath>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a) {
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1) {
cout << "Thank you!" << endl << endl;
int center = ceil(num / 2.0);
for (int r = 0; r <= num+1; ++r) { //outer loop/rows
for (int c = 0; c <= num+1; ++c) { //inner loop/columns
if (r == 0 || r == num+1) {
if (c == 0 || c == num+1)
cout << "+"; // corner
else
//top or botton of square between corners
if (c == center)
cout << "-";
else
cout << "--";
}
else if (c == 0 || c == num+1) {
cout << "|"; // left or right frame
} else {
// inner part
if ((center-std::abs(center-r)) >= center-std::abs(center-c))
if (c < center)
cout << "* ";
else if (c > center)
cout << " *";
else
cout << "*";
else
if (c == center)
cout << " ";
else
cout << " ";
}
}
cout << endl;
}
} else
cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
Just another way (with some more user input checking):
#include <iostream>
#include <string>
#include <limits>
#include <sstream>
using std::cout;
using std::cin;
using std::string;
const auto ssmax = std::numeric_limits<std::streamsize>::max();
const int max_dim = 40;
const int max_iter = 3;
int main() {
cout << "Enter a positive odd number less than " << max_dim << ": ";
int num = 0, counter = 0;
while ( counter < max_iter ) {
cin >> num;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "Please, enter a number!\n";
cin.clear();
cin.ignore(ssmax,'\n');
}
if ( num < max_dim && num > 0 && num % 2 ) {
cout << "Thank you!\n\n";
//top line
string line(num * 2, '-');
cout << line << '\n';
for ( int r = 0, border = num - 1; r < num; ++r ) {
cout << '*';
for ( int c = 1; c < num; ++c ) {
if ( (c > r && c < border) || (c < r && c > border) )
cout << " ";
else
cout << " *";
}
// right border
cout << "|" << '\n';
--border;
}
//bottom line
cout << line << '\n';
++counter;
} else {
cout << "Please, enter a positive odd number that is less than 40!\n";
}
}
cout << std::endl;
}
Or my favorite:
// top line
string line = string(num * 2, '-') + '\n';
cout << line;
// inside lines
int r = 0, border = ( num - 1 ) * 2;
string inside = string(border + 1, ' ') + "|\n";
// top
while ( r < border ) {
inside[r] = '*';
inside[border] = '*';
r += 2;
border -= 2;
cout << inside;
}
// center line
inside[r] = '*';
cout << inside;
// bottom
while ( border > 0 ) {
inside[r] = ' ';
inside[border] = ' ';
r += 2;
border -= 2;
cout << inside;
}
//bottom line
cout << line;

the x should be =28.24778761 but i get 28

I just started learning c++
In this program i try two categorize two resistors based on their values
but at the end i cant print out correctly the x but only the part before ,
for example i tried r1=0 r2=50 r3=100 r4=60 V=9 n=4 1st value=55 2nd=56 3rd=52 4th=57 x should be 56*57/(56+57)=28.24778761 but i only get 28 why?
#include <iostream>
using namespace std;
int main()
{
int n;
float V, TOTAL1, TOTAL2, y;
int r1, r2, r3, r4, i;
cout << "Give r1: "; // Ask for resistors.
cin >> r1;
cout << "Give r2: ";
cin >> r2;
cout << "Give r3: ";
cin >> r3;
cout << "Give r4: ";
cin >> r4;
cout << "Give voltage: ";
cin >> V;
cout << "Give number of resistors: ";
cin >> n;
int a, b; // Ccount the number on its category.
int m;
m = 0;
a = 0;
b = 0;
y = 0;
TOTAL2 = 0;
for(i = 1; i < n + 1; i++)
{
y = TOTAL2 + y; // Calculate the as they are in series
float value;
m = m + 1;
cout << "\n Give resistance: ";
cin >> value;
if((value >= r1) && (value >= r2) && (value <= r3) && (value <= r4))
{
if(m % 2>0)
{
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1; // If they are in the first category they are connected in series
}
else
{
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value;
}
}
else if((value >= r1) && (value <= r2)){
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1;
}
else if((value >= r3) && (value <= r4)) {
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value + 1 / TOTAL2;
}
}
long double x;
x = 1 / y;
cout << "\n The first category has: " << a;
cout << "\n The second category has: " << b;
cout << "\n The total resistance of the first category is: " << TOTAL1;
cout << "\n The total resistance of the second category is: " << x;
return 0;
}
The variable y is only updated at the top of the loop, so the last update is lost. So y contains 1/28 (the first value), and when you take its reciprocal, you get 28 exactly.