Separating Digits in C++ - c++

I am working on an exercise from my C++ book and I'm not sure how to fix it. I am supposed to get an int from the user and display the individual digits in the order they were entered. For instance 12345 would be displayed 1 2 3 4 5. 7365 would be displayed 7 3 6 5. I have most of the code written but there is a logical error and I can't figure it out. Here is my code:
int main()
{
int number = 0;
int digit = 0;
int temp = 0;
int counter = 0;
int sum = 0;
int divisor = 0;
cout << "Please enter a nonzero number.";
cin >> number;
cout << "\nThe number you entered was " << number;
// Determine the number of digits
temp = number;
while (temp != 0)
{
temp = temp / 10;
counter++;
}
cout << "\nThere are " << counter << " digits in your number.";
// Separate the digits
temp = number;
cout << "\nSeparating the digits\n";
do
{
divisor = (pow(10.0, --counter));
digit = temp / divisor;
temp = temp % divisor;
cout << digit << " ";
sum = sum + digit;
}
while (counter != 0);
cout << "\nThe sum of the number is " << sum;
return 0;
}
When I enter 5555 the output is 5560. When I enter 1234 the output is 1236. Can anyone help me find my error?

Here's one version:
// If the number is only one digit, print it.
// Otherwise, print all digits except the last, then print the last.
void digits(int x)
{
if (x < 10){
cout << x;
}
else{
digits(x / 10);
cout << " " << x % 10;
}
}

Thank you all for your help :-) Turns out my code works fine in another compiler so I guess it's just a netbeans glitch.

Related

How do you add numbers in a while loop for c++?

#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
// Declarations
int firstNum = 0, secondNum = 0;
cout << "This program will ask you for two numbers, and then output the even numbers between those two numbers" << endl;
cout << "Please enter the lowest number: " << endl;
cin >> firstNum;
cout << "Please enter the highest number: " << endl;
cin >> secondNum;
if (firstNum % 2 != 0 && secondNum % 2 != 0)
{
while (firstNum <= secondNum)
{
if (firstNum % 2 != 0)
{
cout << firstNum << " ";
}
firstNum++;
}
}
else if (firstNum % 2 == 0 && secondNum % 2 == 0)
{
while (firstNum <= secondNum)
{
if (firstNum % 2 == 0)
{
cout << firstNum << " ";
}
firstNum++;
}
}
return 0;
}
I'm doing a coding exercise for c++, if the user inputs two odd numbers the program would then output all of the odd numbers between the first and second number (first number has to be smaller than the second). If both numbers are even then the program will out put the sum of the even numbers between the first and second (again the first has to be the smallest). My problem is that I do not know how to add the numbers together, I only know how to print either the even or odd numbers between them.
An example:
first number = 4
second number = 36
output = 340
how do you add the even numbers between them?
You could have a variable that stores the result. For example
else if (firstNum % 2 == 0 && secondNum % 2 == 0)
{
int sum = 0; // store the sum of all even numbers
while (firstNum <= secondNum)
{
sum += firstNum; // adding the number to the sum
firstNum += 2; // increment by 2 would skip all the odd numbers
}
cout << sum << endl;
}
Hopefully this helps!
My problem is that I do not know how to add the numbers together - If that is the exact question and assuming start and end are the start and end numbers you can do this to get the sum of all numbers between start and end
int sum = 0;
for ( int i = start; i <= end; i++ )
{
sum += i;
}
std::cout << "Sum of numbers between " << start << " and end " << end << " is " << sum ;
to get the sum of all even numbers in that range
int sum = 0;
for ( int i = start; i <= end; i++ )
{
if ( i%2 == 0 ) // even
sum += i;
}
std::cout << "Sum of even numbers between " << start << " and end " << end << " is " << sum ;
I see you wanted it using while loop in which case
int sum = 0;
while ( start <= end )
{
sum += start;
++start;
}

Explanation of C++ Code

I'm currently working on a program that outputs the number 1089 (i.e the Magic Number) of a three digit integer who's first digit is greater than its last. I have some code typed up, but am not receiving 1089, instead I'm receiving 891. Could anyone offer some explanation as to why.
//Uses a cout to inform user will be using the number 412 as an example.
//Uses a cout to explain to user the number needs to be reversed.
cout << "Alright, let's walk through an example, using the number 412." << endl;
int numExample = 412;
cout << "Please input 412" << endl;
cin >> numExample;
cout << "First, the number 412 is reversed." << endl;
//The following is done for reversing the number 412:
int reverseNum = 0, remainder = 0;
while (numExample)
{
remainder = numExample % 10;
reverseNum = (reverseNum * 10) + remainder;
numExample = numExample / 10;
}
cout << "The reverse of 412 is " << reverseNum << endl;
cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl;
cout << "This gives us 198" << endl;
cout << "From there, we want to reverse 198." << endl;
//The same procedure is used to reverse 198
int numExample2 = 198;
cout << "Please enter 198" << endl;
cin >> numExample2;
int reverseNum2 = 0, remainder2 = 0;
while (numExample2)
{
remainder2 = numExample2 % 10;
reverseNum2 = (reverseNum2 * 10) + remainder2;
numExample2 = numExample2 / 10;
}
cout << "The reverse of 198 is " << reverseNum2 << endl;
int magicNumber = (reverseNum2 + numExample2);
cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl;
Try writing a function to handle this so your code is cleaner (It will also make it easier for people to help you!)
#include <iostream>
#include <cmath>
using namespace std;
int reverseDigit(int num); // For example purposes
int _tmain(int argc, _TCHAR* argv[])
{
int Number1,
Number2,
temp1,
temp2,
Result;
cout << "Enter the number 412: ";
cin >> Number1;
temp1 = reverseDigit(Number1);
temp1 = Number1 - temp1;
cout << "Enter the number 198: ";
cin >> Number2;
temp2 = reverseDigit(Number2);
Result = temp1 + temp2;
cout << "The magic number is: " << Result << endl;
return 0;
}
int reverseDigit(int num)
{
int reverseNum = 0;
bool isNegative = false;
if (num < 0)
{
num = -num;
isNegative = true;
}
while (num > 0)
{
reverseNum = reverseNum * 10 + num % 10;
num = num / 10;
}
if (isNegative)
{
reverseNum = -reverseNum;
}
return reverseNum;
}
I realize you're not working with negatives so you can remove that bit if you chose to use this, you can also expand on it... That being said this will make the actual " Reversing process " easier to work with and improve upon and read.

find the each number of 4 digit of user input and count it using recursion

I have with my code. This is about recursion. I have to create function digitAppear( int findDigit, int value) where value is the user input, and findDigit is single digit number ranging from 0 to 9. The function read user input and return each digit number from the user input and count how many times each digit number occurs in the user input. For example, if I type 1234 then the output say 1 appear 1 time, 2 appear 1 time and so on (I hope my explanation is clear) The problem is the only run once and can only return 1 value.
#include <iostream>
using namespace std;
int countOccurence(int, int);
int main()
{
int findDig;
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 9999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
cin >> value; //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
}
//process the value
for (findDig = 0; findDig < 9; findDig++)
{
cout << endl;
cout << cout << "the " << findDig << "appear in digit " << value << " is " << countOccurence(findDig, value) << " times" << endl;
}
//countOccurance(findDig, value);
//cout
}
int countOccurence(int findDig, int value)
{
int n = value;
while( n > 10 )
{
int a = n / 10; //eliminate the right most integer from the rest
int aa = n % 10; //separate the right most integer from the rest
int b = a / 10; //eliminate the second integer from the rest
int bb = a % 10; //separate the second integer from the rest
int c = b / 10; // eliminate the third integer from the rest
int cc = b % 10; //separate the third integer from the rest
for (findDig = 0; findDig < 9; findDig++)
{
int i = 0;
if (findDig == aa) // see if the findDigit value is equal to single digit of b;
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == bb)
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == cc)
{
i += 1;
} else
{
i += 0;
}
return il;
}
}
}
The problem is my function countOccurence() doesn't seems right. I wonder if there a way to do it. I have been stuck with this for days and I really appreciate your input, thank you.
To use recursion, you must think about the problem in a different way.
The easiest way of thinking about how you could incorporate recursion into the function is the process of 'peeling off' each number.
A very simple way of doing this is by looking at the first/last digit in the number, compute that, then call itself on the remainder of the number.
Hopefully you can figure out the code from there.
If you mean that function digitAppear itself has to be recursive then it can look the following way as it is shown in the demonstrative program below
#include <iostream>
#include <cstdlib>
size_t digitAppear( int findDigit, int value )
{
return ( std::abs( value ) % 10u == std::abs( findDigit ) ) +
( ( value /= 10 ) ? digitAppear( findDigit, value ) : 0 );
}
int main()
{
int i = 0;
for ( int x : { 0, 11111, 1234, 34343 } )
{
std::cout << "There are " << digitAppear( i, x )
<< " digit " << i
<< " in number " << x
<< std::endl;
++i;
}
return 0;
}
The program output is
There are 1 digit 0 in number 0
There are 5 digit 1 in number 11111
There are 1 digit 2 in number 1234
There are 3 digit 3 in number 34343
Of course you may rewrite function main as you like for example that it would count each digit in a number.

Error using For loop

I have problem running my loops.
I have to run a program where user enter 4 digit number, and it will show how many zero appear. This program will run depends on how many times user want it to run. so at the beginning I prompt user to enter the number of times the program will run, then the actual program will run in For loop. but so far, I can only run it once. Can someone help me? Thank you. Here is my code
#include <iostream>
using namespace std;
int main()
{
int numberTimes;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
for (int counter = 0; counter < numberTimes; counter++);
{
int positiveInteger;
//prompt user to enter a positive integer
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
//conditional statement
while((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Please try again.\n";
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
}
cout << "Processing the value " << positiveInteger << ".\n";
int zeroCount = 0;
int firstNumber = positiveInteger%10; //separate the first number
if (firstNumber == 0) //determine if the first digit is zero
{
zeroCount = zeroCount + 1;
}
int digitOne = positiveInteger/10; //omitted first digit number
int secondNumber = digitOne%10; //separate the second number
if (secondNumber == 0) //determine if the second digit is zero
{
zeroCount = zeroCount + 1;
}
int digitTwo = digitOne/10; //omitted the second number
int thirdNumber = digitTwo%10; //separate the third number
if (thirdNumber == 0) //determine if the third digit is zero
{
zeroCount = zeroCount + 1;
}
int digitThree = digitTwo/10; //omitted the third number
int fourthNumber = digitThree%10; //separate the fourth number
if (fourthNumber == 0) //determine if the fourth digit is zero
{
zeroCount = zeroCount + 1;
}
cout << "Your first digit number is " << firstNumber << ".\n";
cout << "Your second digit number is " << secondNumber << ".\n";
cout << "Your third digit number is " << thirdNumber << ".\n";
cout << "Your fourth digit number is " << fourthNumber << ".\n";
cout << "Number of zero appear in your integer is " << zeroCount << ".\n";
if (zeroCount % 2 == 0) //determine if the number is even or odd
{
cout << "Your number zero appear even times.\n";
} else
{
cout << "Your number zero appear odd times.\n";
}
}
cout << "You have run this program " << numberTimes << ".\n";
cout << "Thank you and good bye.";
return 0;
}
The problem is using ; at the end of for line.
for (int counter = 0; counter < numberTimes; counter++);
In such a case that you used, it iterate the loop but do nothing.
In the other word,it is equal to the below program now :
for (int counter = 0; counter < numberTimes; counter++)
{
}
You can also use this program : (Add complementary lines)
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int numberTimes;
int digit;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
while(numberTimes)
{
int zeroRepitation=0;
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
if ((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Try again!\n";
continue;
}
for (int i=1;i<5;i++)
{
digit = positiveInteger % 10;
if (digit=0)
{
++zeroRepitation;
}
positiveInteger = positiveInteger / 10;
}
cout<<"Number of zeros in this number= "<<zeroRepitation;
--numberTimes;
}
You put a semicolon at the end of the for statement. This:
for (int counter = 0; counter < numberTimes; counter++);
should be this:
for (int counter = 0; counter < numberTimes; counter++)

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)