Classifying digits of an integer value - c++

I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.

Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks

Related

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;
}
}

maximum power a number can be raised to with out exceeding y recursion

i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.

Copying from input to the output text file

Hi guys here is my functional code but it does not works properly it should do read numbers from input.txt and count the sum of even,odd numbers in each line then conjunction of prime numbers( which does correctly) and also copy all numbers which are prime to the output.txt
here is my code the problem is : it copies also numbers which are not prime numbers. Thanks a lot !!!
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream read;
read.open("input.txt");
ofstream write;
write.open("output.txt");
string line;
int even, odd, primeXprime;
if(read.fail())
cout << "Cant open input.txt" << endl;
int x, p = 0;
if(read.is_open())
{
while(read, line)
{
even = odd = 0;
primeXprime = 1;
istringstream sRead(line);
while(sRead >> x)
{
if(x % 2 == 0)
even += x;
if(x % 2 != 0)
odd += x;
for(int i = 2; i <= x; i++)
{
if(x % i == 0)
p++;
if(p == 2)
{
primeXprime *= x;
write << x << " ";
p = 0;
}
else
break;
}
}
cout << "Sum of even numbers are: " << even << endl;
cout << "Sum of odd numbers are: " << odd << endl;
cout << "Sum of prime numbers are: " << primeXprime << endl;
cout << endl;
}
read.close();
write.close();
system("pause");
return 0;
}
}
Problem is with your Primality Testing algorithm , You cannot determine a number is prime or not until you divide it by all the numbers in the range [2,Sqrt(n)]
In line "if(p == 2)" you are assuming that it wont be divided by any number later on in the range .
Replace your entire for loop by
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;

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.

I need to find the location of certain digits from user input

I have been trying to finish this code (function) for a while now, but am stuck on the last part. In this code, I prompt the user to select a number of integers and any number of digits and then find the smallest and largest value within these digits. On the next part, I am supposed to determine which of the given digits the smallest and largest are located such that the output should be:
Digit _ can be found in integer number(s): _, _
I apologize in advance if my code is sloppy; I just started learning C++ and haven't fully grasped the language yet.
int digitSizeLoca() {
int userNumInteger;
int* iPtr;
int* iPtr2;
int* iPtr3;
int value;
int value2;
int value3;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
iPtr2 = new int[userNumInteger];
iPtr3 = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++) {
*(iPtr3 + 1) = *(iPtr2 + 1) = *(iPtr + 1);
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + 1);
}
value = *(iPtr + 1);
value2 = *(iPtr2 + 1);
value3 = *(iPtr3 + 1);
if (value != 0, value2 != 0, value3 != 0) {
if (value <= 0)
value = -value;
if (value2 <= 0)
value2 = -value2;
if (value3 <= 0)
value3 = -value3;
int lDigit;
int sDigit;
int curDigit;
int pot = 10;
lDigit = sDigit = value % pot;
while (value, value2, value3) {
if (value / pot == 0, value2 / pot == 0, value3 / pot == 0) break;
curDigit = (value / pot, value2 / pot, value3 / pot) % 10;
if (curDigit < sDigit)
sDigit = curDigit;
if (curDigit > lDigit)
lDigit = curDigit;
pot*=10;
}
std::cout << "\nThe smallest digit: " << sDigit << std::endl
<< "\n Digit " << sDigit
<< " can be found in integer number(s): ";
std::cout << "\nThe largest digit: " << lDigit << std::endl
<< "\n Digit " << lDigit
<< " can be found in integer number(s): ";
}
return 0;
}
Example of what output should be given user input:
If user chooses 2 for userNumInteger, and inputs the digit values 1234 and -1578,
the output for my question should be:
Smallest digit: 1
Digit 1 can be found in integer number(s): 1, 2
.
.
.
Thank you!
If digits matter, then input 02 is not the same as 2 (even if both means the number 2; beware that 02 could be an octal notation). So you should read a std::string, check that it has digits appropriately using isdigit, then use std::stol (in C++11) or strtol to do the conversion.
You'll better use some std::vector<int> instead of initializing a pointer with new int[userNumInteger] ...
Since you mentioned that you can only use integer for now, it makes your life a bit difficult. Basile was right when he mentioned that you should use string. That would help you iterating through the numbers over and over again like I did below but it does the task - the drawback being that you will have to iterate 3 times but if you do not want to sort or do anything special then it is good enough....
int digitSizeLoca()
{
int userNumInteger;
int* iPtr;
int lowest = 9;
int highest = 0;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++)
{
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + i);
}
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
std::cout << "You Entered (" << i << "): " << *(iPtr + i) << std::endl;
do
{
int remainder = number % 10;
if (remainder > highest) highest = remainder;
if (remainder < lowest) lowest = remainder;
number = number / 10;
}
while (number > 0);
}
std::cout << "\nThe largest digit: " << highest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == highest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
std::cout << "\nThe smallest digit: " << lowest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == lowest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
}