I want to print the binary representation of a number using only for, if while a
ID: 3564058 • Letter: I
Question
I want to print the binary representation of a number using only for, if while and else statements. Right now i got the problem that nothing can be printed, even though i'm adding the strings 0 and 1 to string s, it doesn't seem to work. What is the problem and how can I fix that? Here's what i've written now:
#include <string>
#include <iostream>
int main(){
std::cout << "enter an integer" << ". ";
int n;
std::cin >> n;
std::string s="";
std::string a="0";
std::string b="1";
for(int i=8; i=0; i--){
if(n%2 == 0){
s=s.append(a);
n=n/2;
}else{
s=s.append(b);
n=n/2;
}
// std::cout << "the binary number of " << n << " is " << s << ". ";
}std::cout << s;
return 0;
}
Explanation / Answer
for(int i=8; i=0; i--) this statement is wrong. it should be for(int i=8; i>0; i--)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.