I'm a total beginner in C++ and today I thought I'd write myself a small program that converts a decimal number to binary. The code looked something like this:
#include <iostream>
void binaryConvert(int);
int main() {
using namespace std;
cout << "Enter decimal number for conversion:" << endl;
int dec;
cin >> dec;
binaryConvert(dec);
}
void binaryConvert(int number) {
using namespace std;
while(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin;
}
}
Logically, this program would print the binary the other way around. I spent a long time trying to figure out how to invert the order of the binary digits so that the binary number would appear the right way around when I came across this piece of code:
void binaryConvert(int number) {
using namespace std;
if(number > 0) {
int bin = number % 2;
number /= 2;
binaryConvert(number);
cout << bin;
}
}
I know its probably a stupid question (I'm an absolute beginner), but I can't figure out why this code prints the bits in the correct order. Also, how come the bits actually get printed if the function gets called again before cout even gets executed?
Basically because "cout" is called after "binaryConvert". It's like putting all the bits in a stack and after that printing them.
It utilizes recursion, the bin at the end will not be printed until the base case is hit (number <= 0) and then it will go up the stack trace.
This function is a recursive one. It is calling itself recursively to print the least significant digits first, before printing out the most significant ones.
int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string newstring= "";
bool h;
h = true;
while(h){
BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
num = num / 2;
if ( num < 1){
h = false;
}
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
newstring += BinaryRepresentation[i];
}
cout<< "Binary Representation: " << newstring <<endl;
}
Mainly the idea of the program is to find the reminder of the number and divide the number by 2 and and keep on repeating the same procedure until the number becomes 0. The you need to reverse the string in order to get the binary equivalent of the entered number.
As you have correctly mentioned your program inverted the binary as it gave the output.
To put the binary in the correct order to The second code starts giving output only once the final bit is obtained. The order of output is bin to the bin and hence we obtain the desired output. The following code may help your understanding further: http://ideone.com/Qm0m7L
void binaryConvert(int number) {
if(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin<<" one"<<endl;
binaryConvert(number);
cout << bin<<" two"<<endl;
}
}
The output obtained is:
0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two
The output that precedes " one" is what your program would have given.
I hope you understand the difference.
While I was searching online to convert from decimal to binary, didn't find a simple and an understandable solution. So I wrote a program on my own.
Here it goes.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void dtobin(int n)
{
ostringstream oss;
string st="";
if(n<0)
{
cout<<"Number is negative";
return;
}
int r;
while(n!=1)
{
r=n%2;
oss<<st<<r;
n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
x=st[i];
st[i]=st[j];
st[j]=x;
--j;
}
cout<<endl<<st;
}
int main()
{
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
dtobin(n);
return 0;
}
Related
I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.
I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum = 0; // MAKE SURE YOU INITIALIZE THIS TO 0 BEFORE ADDING VALUES TO IT!
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
Initialize your variables before adding values to them, otherwise you could run into undefined behaviour. Also for the record, adding the cout line printed out something, but it wasn't the correct answer.
Well I am stuck on this problem for quite a while:
Question:
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a line with the value of n!
//coded in c++
#include <bits/stdc++.h> //loadind up all the libraries at once.
using namespace std;
int main()
{ int T;
scanf("%d", &T);
//I am not doing "cin<<" cause "scanf" is faster than it
for (int i = 0; i < T; i++)
{
int N;
scanf("%d",&N);
long long int product = 1;
while (N >0){
product = product * N;
N--;
}
printf("%lld\n",product);
}
return 0;
}
I am able to get 10!,20! but unable to get 100! (factorial)
so the extreme case doesn't satisfy. Please help me to get a good data type for my variable as 100! a factorial has over than 100 digits. It is displaying 0 when I input 100 on the terminal.
P.S - This problem is from CodeChef website (FCTRL2).
A 64bit integer will overflow with 23!
Therefore you need to do it with digits and a vector.
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 23!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Using a bigint library will be much faster.
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
I am writing a program to find the factorial of a user inputted number. My program works from, except for finding the factorial of 0. The requirement is that the factorial of 0 should output one, but I cannot think of a way to write this capability into the code without creating a special case for when 0 is entered. This is what I have so far
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int startingNumber = 0;
double factorialize = NULL;
while(startingNumber != -1) {
cout << "Enter the numbr to factorial: ";
cin >> startingNumber;
factorialize = startingNumber;
for(int x=startingNumber-1;x>=1;x--) {
factorialize = factorialize*x;
}
cout << factorialize << endl;
factorialize = NULL;
}
return 0;
}
This outputs a factorial accurately for all cases except 0. Is there a way to do this that doesn't require a special case? I am thinking no because when I read about the reasons for why 0! is 1, it says that it is defined that way, in other words, you cannot reason your way into why it is 1. Just like x^0, 0! = 1 has a different logic as to why than why 2^2 is 4 or 2! = 2.
try this:
factorialize = 1;
for(int x=2; x<=startingNumber;x++)
factorialize *= x;
Try this:
for (unsigned int n; std::cin >> n; )
{
unsigned int result = 1;
for (unsigned int i = 1; i <= n; ++i) { result *= i; }
std::cout << n << "! = " << result << "\n";
}
You can change the result type a bit (unsigned long long int or double or long double), but ultimately you won't be able to compute a large number of factorials in hardware.
First of all I do not see how it can be calculated accurately, as you multiply startingNumber twice. So just fix the logic with:
factorialize = 1.0;
for(int x=startingNumber;x>=1;x--) {
factorialize = factorialize*x;
}
And it should calculate factorial properly as well as handling 0 the proper way.
Also you should not use NULL as initial value for double, it is for pointers.
There is a complete factorial of number program of C++ which includes the facility of factorial of positive number,negative and zero.
#include<iostream>
using namespace std;
int main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0
)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read full program logic on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
The function listed below returns the factorial FASTER than any solution posted here to this date:
const unsigned int factorial(const unsigned int n)
{
unsigned int const f[13] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600 };
return f[n];
}
I looks silly but it works for all factorials that fit into a 32-bit unsigned integer.
So i am getting a weird error message in my c++ program. Currently using visual studios (2012). I have a program which adds every other digit of a number, so 1234567 would be like 7+5+3+1=16, then I take all the non added numbers and multiply em by two and add em up. Then I add up the result of the first one (16) and add it to the result of the second one. Here's my code:
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;
int sumAltDigits(int);
int sumNonDigits(int);
int main() {
long cardNumber; //cardNumber must stay as 'long'. Teacher says so.
string in;
stringstream ss;
int total;
cout << "Please enter a chain of integers: ";
getline(cin, in);
ss.clear(); ss.str(in);
while (!(ss >> cardNumber) || (cardNumber < 1)); {
cout << sumAltDigits(cardNumber) << endl;
//get answer
total = sumAltDigits(cardNumber) + sumNonDigits(cardNumber); //this line causes me an error, sumNonDigits(cardNumber)
}
system("pause");
}
// adds every other digit, starting from the right
int sumAltDigits(int cardNumber)
{
if (cardNumber < 10)
return cardNumber;
return (cardNumber % 10) + sumAltDigits(cardNumber / 100);
}
// adds digits that were not included in previous step, multiply them by 2, then add all digits in those numbers
int sumNonDigits(string cardNumber) // I think the error is also being caused by string cardNumber, but if i try to change that, it screws up this function.
{
int checkSum = 0;
int i;
for (i = cardNumber.length() - 2; i >= 0; i -= 2) {
int val = ((cardNumber[i] - '0') * 2);
while (val > 0) {
checkSum += (val % 10);
val /= 10;
cout << checkSum << endl;
}
}
return checkSum;
}
You've forward declared (and called):
int sumNonDigits(int);
But you've defined:
int sumNonDigits(string cardNumber)
You'll need to change one to match the other.
If you change them both to be:
int sumNonDigits(string cardNumber)
This is likely to mean less work but you will need to change the call here:
total = sumAltDigits(cardNumber) + sumNonDigits(cardNumber);
...to pass in a [std::]string, rather than cardNumber, which is long. Perhaps the input string in would be a good substitution, or perhaps you need to convert cardNumber back to a string. Only you can choose!
You have a int sumNonDigits(string cardNumber) but declare int sumNonDigits(int);. You are calling sumNonDigits(int) in the line...
total = sumAltDigits(cardNumber) + sumNonDigits(cardNumber);
...but it's an unresolved external because there's no definition.
I recommend avoiding function declarations altogether for now, and putting your function bodies above their first point of use.