I am making a program that adds two binary numbers (up to 31 digits) together and outputs the sum in binary.
I have every thing working great but I need to remove the leading zeros off the solution.
This is what my output is:
char c[32];
int carry = 0;
if(carry == '1')
{
cout << carry;
}
for(i = 0; i < 32; i++)
{
cout << c[i];
}
I tried this but it didn't work:
char c[32];
int carry = 0;
bool flag = false;
if(carry == '1')
{
cout << carry;
}
for(i=0; i<32; i++)
{
if(c[i] != 0)
{
flag = true;
if(flag)
{
for(i = 0; i < 32; i++)
{
cout << c[i];
}
}
}
}
Any ideas or suggestions would be appreciated.
EDIT: Thank you everyone for your input, I got it to work!
You should not have that inner loop (inside if(flag)). It interferes with the i processing of the outer loop.
All you want to do at that point is to output the character if the flag is set.
And on top of that, the printing of the bits should be outside the detection of the first bit.
The following pseudo-code shows how I'd approach this:
set printing to false
if carry is 1:
output '1:'
for each bit position i:
if c[i] is 1:
set printing to true
if printing:
output c[i]
if not printing:
output 0
The first block of code may need to be changed to accurately output the number with carry. For example, if you ended up with the value 2 and a carry, you would want either of:
1:10 (or some other separator)
100000000000000000000000000000010 (33 digits)
Simply outputting 110 with no indication that the leftmost bit was a carry could either be:
2 with carry; or
6 without carry
The last block ensures you have some output for the value 0 which would otherwise print nothing since there were no 1 bits.
I'll leave it up to you whether you should output a separator between carry and value (and leave that line commented out) or use carry to force printing to true initially. The two options would be respectively:
if carry is 1:
output '1 '
and:
if carry is 1:
output 1
set printing to true
And, since you've done the conversion to C++ in a comment, that should be okay. You state that it doesn't work, but I typed in your code and it worked fine, outputting 10:
#include <iostream>
int main(void)
{
int i;
int carry = 0;
int c[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
bool print = false;
// This is the code you gave in the comment, slightly modified.
// vvvvvv
if(carry == 1) {
std::cout << carry << ":";
}
for (i = 0; i < 32; i++) {
if (c[i] == 1) {
print = true;
}
if (print) {
std::cout << c[i];
}
}
// ^^^^^^
std::cout << std::endl;
return 0;
}
const char * begin = std::find(c, c+32, '1');
size_t len = c - begin + 32;
std::cout.write(begin, len);
Use two fors over the same index. The first for iterates while == 0, the second one prints starting from where the first one left off.
Related
I have this code here and I'm trying to do decimal to hexadecimal conversion without using arrays. It is working pretty much but it gives me wrong answers for values greater than 1000. What am I doing wrong? are there any counter solutions? kindly can anyone give suggestions how to improve this code.
for(int i = num; i > 0; i = i/16)
{
temp = i % 16;
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
num = num * 100 + temp;
}
cout<<"Hexadecimal = ";
for(int j = num; j > 0; j = j/100)
{
ch = j % 100;
cout << ch;
}
There's a couple of errors in the code. But elements of the approach are clear.
This line sort of works:
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
But is confusing because it's using 48 and 55 as magic numbers!
It also may lead to overflow.
It's repacking hex digits as decimal character values.
It's also unconventional to use ?: in that way.
Half the trick of radix output is that each digit is n%r followed by n/r but the digits come out 'backwards' for conventional left-right output.
This code reverses the hex digits into another variable then reads them out.
So it avoids any overflow risks.
It works with an unsigned value for clarity and a lack of any specification as how to handle negative values.
#include <iostream>
void hex(unsigned num){
unsigned val=num;
const unsigned radix=16;
unsigned temp=0;
while(val!=0){
temp=temp*radix+val%radix;
val/=radix;
}
do{
unsigned digit=temp%16;
char c=digit<10?'0'+digit:'A'+(digit-10);
std::cout << c;
temp/=16;
}while(temp!=0);
std::cout << '\n';
}
int main(void) {
hex(0x23U);
hex(0x0U);
hex(0x7U);
hex(0xABCDU);
return 0;
}
Expected Output:
23
0
8
ABCD
Arguably it's more obvious what is going on if the middle lines of the first loop are:
while(val!=0){
temp=(temp<<4)+(val&0b1111);
val=val>>4;
}
That exposes that we're building temp as blocks of 4 bits of val in reverse order.
So the value 0x89AB with be 0xBA98 and is then output in reverse.
I've not done that because bitwise operations may not be familiar.
It's a double reverse!
The mapping into characters is done at output to avoid overflow issues.
Using character literals like 0 instead of integer literals like 44 is more readable and makes the intention clearer.
So here's a single loop version of the solution to the problem which should work for any sized integer:-
#include <iostream>
#include <string>
using namespace std;
void main(int argc, char *argv[1])
{
try
{
unsigned
value = argc == 2 ? stoi(argv[1]) : 64;
for (unsigned i = numeric_limits<unsigned>::digits; i > 0; i -= 4)
{
unsigned
digit = (value >> (i - 4)) & 0xf;
cout << (char)((digit < 10) ? digit + 48 : digit + 55);
}
cout << endl;
}
catch (exception e)
{
cout << e.what() << endl;
}
}
There is a mistake in your code, in the second loop you should exit when j > original num, or set the cumulative sum with non-zero value, I also changed the cumulative num to be long int, rest should be fine.
void tohex(int value){
long int num = 1;
char ch = 0;
int temp = 0;
for(int i = value; i > 0; i = i/16)
{
temp = i % 16;
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
num = num * 100 + temp;
}
cout<<"Hexadecimal = ";
for(long int j = num; j > 99; j = j/100)
{
ch = j % 100;
cout << ch;
}
cout << endl;
}
If this is a homework assignment, it is probably related to the chapter on Recursivity. See a solution below. To understand it, you need to know
what a lookup table is
what recursion is
how to convert a number from one base to another iteratively
basic io
void hex_out(unsigned n)
{
static const char* t = "0123456789abcdef"; // lookup table
if (!n) // recursion break condition
return;
hex_out(n / 16);
std::cout << t[n % 16];
}
Note that there is no output for zero. This can be solved simply by calling the recursive function from a second function.
You can also add a second parameter, base, so that you can call the function this way:
b_out(123, 10); // decimal
b_out(123, 2); // binary
b_out(123, 8); // octal
I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method:
#include<iostream>
using namespace std;
int main()
{
int l;
cin>>l;
bool leading = true;
while (l>0)
{
if ((l%10==0)&& (leading==true))
{
l /= 10;
leading = false; // prints 032 as output
continue;
}
// leading = false; this prints correct 32
cout<<l%10;
l /= 10;
}
return 0;
}
The instruction of assigning boolean leading false inside the if statement is not giving a valid answer, but I suppose assigning it false should give 32 as output whether we give it outside or inside if statement as its purpose is just to make it false once you get the last digit to be a non zero.
Please tell the reason of difference in outputs.
The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it.
When you make leading = false outside the if statement, you are basically waiting till you encounter all zeroes before making it false.
If you are looking to reverse a number, this is the well known logic to do so:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
rev = rev*10 + r;
n /= 10;
}
return rev;
}
EDIT:
The above code snippet is fine if you just want to understand the logic to reverse a number. But if you want to implement the logic anywhere you have to make sure you handle integer overflow problems (the reversed number could be too big to be stored in an integer!!).
The following code will take care of integer overflow:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
if(INT_MAX/10 < rev)
{
cout << "Reversed number too big for an int.";
break;
}
else if(INT_MAX-r < rev*10)
{
cout << "Reversed number too big for an int.";
break;
}
rev = rev*10 + r;
n /= 10;
}
if(n != 0)
{
//could not reverse number
//take appropriate action
}
return rev;
}
First, rewrite without continue to make the flow clearer,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
l /= 10;
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
l /= 10;
}
}
and move the division common to both branches out of the conditional,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
}
l /= 10;
}
and now you see that the only difference between the two is the condition under which the assignment leading = false happens.
The correct version says, "If this digit is non-zero or a non-leading zero, remember that the next digit is not a leading zero, and print this digit. Then divide."
Your broken version says, "If this is a leading zero, the next digit is not a leading zero." which is pretty obviously not the case.
Just try this ,
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Working for me...
When reversing digits of numbers or generally when working with digits and the actual
value does not matter then treating the number as an array of digits is simpler than working with the whole int. How to treat a number as an array of digits conveniently? std::string:
#include <iostream>
#include <string>
#include <sstream>
int reverse_number(int x) {
std::string xs = std::to_string(x);
std::string revx{ xs.rbegin(),xs.rend()};
std::stringstream ss{revx};
int result;
ss >> result;
return result;
}
int main() {
std::cout << reverse_number(123) << "\n";
std::cout << reverse_number(1230) << "\n";
}
std::to_string converts the int to a std::string. std::string revx{ xs.rbegin(),xs.rend()}; constructs the reversed string by using reverse iterators, and eventually a stringstream can be used to parse the number. Output of the above is:
321
321
So im working on a class assignment where I need to take a base 2 binary number and convert it to its base 10 equivalent. I wanted to store the binary as a string, then scan the string and skip the 0s, and at 1s add 2^i. Im not able to compare the string at index i to '0, and im not sure why if(binaryNumber.at(i) == '0') isnt working. It results in an "out of range memory error". Can someone help me understand why this doesnt work?
#include <iostream>
using namespace std;
void main() {
string binaryNumber;
int adder;
int total = 0;
cout << "Enter a binary number to convert to decimal \n";
cin >> binaryNumber;
reverse(binaryNumber.begin(),binaryNumber.end());
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') { //THIS IS THE PROBLEM
//do nothing and skip to next number
}
else {
adder = pow(2, i);
total = adder + total;
}
}
cout << "The binary number " << binaryNumber << " is " << total << " in decimal form.\n";
system("pause");
}
Array indices for C++ and many other languages use zero based index. That means for array of size 5, index ranges from 0 to 4. In your code your are iterating from 1 to array_length. Use:
for (int i = 0; i < binaryNumber.length(); i++)
The problem is not with the if statement but with your loop condition and index.
You have your index begin at one, while the first character of a string will be at index zero. Your out memory range error is caused by the fact that the loop stops when less than or equal, causing the index to increase one too many and leave the memory range of the string.
Simply changing the loop from
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') {
}
else {
adder = pow(2, i);
total = adder + total;
}
}
To
for (int i = 0; i < binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') {
}
else {
adder = pow(2, i);
total = adder + total;
}
}
Will solve the issue.
Because your started from 1 and not 0
for (int i = 1; i <= binaryNumber.length(); i++)
Try with that
for (int i = 0; i < binaryNumber.length(); i++)
First of all, sorry for the mis-worded title. I couldn't imagine a better way to put it.
The problem I'm facing is as follows: In a part of my program, the program counts occurences of different a-zA-Z letters and then tells how many of each letters can be found in an array. The problem, however, is this:
If I have an array that consists of A;A;F;A;D or anything similar, the output will be this:
A - 3
A - 3
F - 1
A - 3
D - 1
But I am required to make it like this:
A - 3
F - 1
D - 1
I could solve the problem easily, however I can't use an additional array to check what values have been already echoed. I know why it happens, but I don't know a way to solve it without using an additional array.
This is the code snippet (the array simply consists of characters, not worthy of adding it to the snippet):
n is the size of array the user is asked to choose at the start of the program (not included in the snippet).
initburts is the current array member ID that is being compared against all other values.
burts is the counter that is being reset after the loop is done checking a letter and moves onto the next one.
do {
for (i = 0; i < n; i++) {
if (array[initburts] == array[i]) {
burts++;
}
}
cout << "\n\n" << array[initburts] << " - " << burts;
initburts++;
burts = 0;
if (initburts == n) {
isDone = true;
}
}
while (isDone == false);
Do your counting first, then loop over your counts printing the results.
std::map<decltype(array[0]), std::size_t> counts;
std::for_each(std::begin(array), std::end(array), [&counts](auto& item){ ++counts[item]; });
std::for_each(std::begin(counts), std::end(counts), [](auto& pair) { std::cout << "\n\n" << pair.first << " - " pair.second; });
for (i = 0; i < n; i++)
{
// first check if we printed this character already;
// this is the case if the same character occurred
// before the current one:
bool isNew = true;
for (j = 0; j < i; j++)
{
// you find out yourself, do you?
// do not forget to break the loop
// in case of having detected an equal value!
}
if(isNew)
{
// well, now we can count...
unsigned int count = 1;
for(int j = i + 1; j < n; ++j)
count += array[j] == array[i];
// appropriate output...
}
}
That would do the trick and retains the array as is, however is an O(n²) algorithm. More efficient (O(n*log(n))) is sorting the array in advance, then you can just iterate over the array once. Of course, original array sequence gets lost then:
std::sort(array, array + arrayLength);
auto start = array;
for(auto current = array + 1; current != array + arrayLength; ++current)
{
if(*current != *start)
{
auto char = *start;
auto count = current - start;
// output char and count appropriately
}
}
// now we yet lack the final character:
auto char = *start;
auto count = array + arrayLength - start;
// output char and count appropriately
Pointer arithmetic... Quite likely that your teacher gets suspicious if you just copy this code, but it should give you the necessary hints to make up your own variant (use indices instead of pointers...).
I would do it this way.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s;
vector<int> capCount(26, 0), smallCount(26, 0);
cout << "Enter the string\n";
cin >> s;
for(int i = 0; i < s.length(); ++i)
{
char c = s.at(i);
if(c >= 'A' && c <= 'Z')
++capCount[(int)c - 65];
if(c >= 'a' && c <= 'z')
++smallCount[(int)c - 97];
}
for(int i = 0; i < 26; ++i)
{
if(capCount[i] > 0)
cout << (char) (i + 65) << ": " << capCount[i] << endl;
if(smallCount[i] > 0)
cout << (char) (i + 97) << ": " << smallCount[i] << endl;
}
}
Note: I have differentiated lower and upper case characters.
Here's is the sample output:
output
For this code I created that outputs the ASCII characters corresponding to ints, I need to print out 16 ASCIIs per line. How would I go about doing so? I'm not sure how to approach these? Do I create another for loop inside?
int main()
{
int x = 0;
for (int i = 0; i <= 127; i++)
{
int x = i;
char y = (char) x;
cout << y;
}
return 0;
}
Or should I put the cout outside with 16 separate lines? I am trying to print 17 ASCIIs starting from 1 in a row.
Use another variable that counts up along with i. When it reaches 16, reset it and print a new line. Repeat until the loop terminates.
i.e.(I may be off by one here, I didn't think about it too deeply)
for (int i=0, j=1; i<=127; i++,j++)
{
int x = i;
char y = (char) x;
cout << y;
if (j == 16) {
j = 0;
cout << '\n';
}
}
Alternatively, you could just check if (i % 16 == 0)
You don't need another variable to track it. i is already an int.
so if i modulo 16 equals 0 then print a newline
else print (char)i
EDIT:
Note, using variables like i is ok for simple iteration but its always good practice to name them better.
So think about how changing i to ascii in your program improves the readability. It instantly makes it even more clear what is it that you are trying to do here.
int main()
{
int charsThisLine =0;
for (int currentChar=0; currentChar<128; currentChar++)
{
if(charsThisLine==16)
{
cout<<endl;
charsThisLine = 0;
}
else
{
cout<<(char)currentChar;
charsThisLine++;
}
}
}
How about:
#include <iostream>
int main()
{
for(int i = 0, j = 0; i < 128; ++i, ++j)
{
if(j == 16)
{
j = 0;
std::cout << std::endl;
}
std::cout << static_cast<char>(i);
}
return 0;
}
Every iteration, j increases by 1; after 16 iterations, j is reset to 0, and a newline is printed.
Alternatively, as #Sujoy points out, you could use:
if((i % 16) == 0)
std::cout << std::endl;
But this introduces the problem of printing an extra newline character at the beginning of the output.
Yes, you need a second loop inside the first. (I misunderstood what is being requested.)
You also need to clean up the code. The first x is unused; the second x isn't needed since you could perfectly well use char y = (char)i; (and the cast is optional). You should normally use a loop for (int i = 0; i < 128; i++) with a < condition rather than <=.
You will also need to generate a newline somewhere (cout << endl; or cout << '\n';). Will you be needing to deal with control characters such as '\n' and '\f'?
Finally, I'm not sure that 'asciis' is a term I've seen before; the normal term would be 'ASCII characters'.