Reversing a number C++ - c++

Looking for some advice here on what I'm getting wrong. Everything in my main should be fine and left unchanged. My problem is in my reverse function. It's printing the reversed number right before the cout statement of "The number is" instead down below where it should be. I spent awhile trying to fix but can't come up with a solution.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NUM_VALS = 10; //the maximum number of values to use
int reverse(int num);
bool isPrime(int num);
int main()
{
int number, //Holds the random number that is manipulated and tested
loopCnt; //Controls the loop
//set the seed value for the random number generator
//Note: a value of 1 will generate the same sequence of "random" numbers every
// time the program is executed
srand(1);
//Generate 10 random numbers to be manipulated and tested
for( loopCnt = 1; loopCnt <= NUM_VALS; loopCnt++ )
{
//Get a random number
number = rand();
//Display the sum of adding up the digits in the random number, the reversed
//random number, and whether or not the number is palindromic or a prime number
cout << "The number is " << number << endl
<< "----------------------------------------" << endl
// << "Adding the digits result" << setw(16) << sumDigits( number ) << endl
<< "Reversing the digits result" << setw(13) << reverse(number) << endl
// << "Is the number a palindrome?" << setw(13) << (isPalindrome(number)? "Yes" : "No") << endl
// << "Is the number prime?" << setw(20) << (isPrime(number)? "Yes" : "No") << endl
<< endl << endl;
}
return 0;
}
int reverse(int num)
{
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
cout << rem;
quo /= 10;
}
}
bool isPrime(int num)
{
int i;
if (num % 2 == 0)
return false;
for (i = 3; i*i <= num; i+=2)
{
if (num % i == 0)
return false;
}
return true;
}

You need to have your reverse function return the number as reversed, because the return value is used in main.
You can build the reversed number by multiplying a "reversed" value by 10, then adding in the remainder:
int reverse(int num)
{
int reversed = 0;
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
reversed = reversed * 10 + rem;
quo /= 10;
}
return reversed;
}

You can also use this method to reverse a number by taking string input and then reverse it and convert it to int.
#include <iostream>
#include<string>
using namespace std;
int reverse_num(string a)
{
string s;
for(int i=a.length()-1;i>=0;i--)
{
s+=a[i];
}
int n;
n=stoi(s);
return n;
}
int main()
{
string a;
cin>> a;
cout<<reverse_num(a);
return 0;
}

Related

Function that finds prime numbers between two intervals

I have written the bulk majority of the program, I'm just having trouble debugging it. Something must be wrong with my computation of the prime numbers. For anything I try, it says there are 0 prime numbers. Any help would be greatly appreciated. Code and output are below.
Note: For this program, I am not allowed to use vectors or arrays.
#include <iostream>
#include <cmath>
using namespace std;
// FUNCTION PROTOTYPE FOR read_range
void read_range(int &lower, int &upper);
// FUNCTION PROTOTYPE FOR is_prime
bool is_prime(const int num);
// FUNCTION PROTOTYPE FOR display_primes
void display_primes(const string &prime, const int lower, const int upper);
// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
int imin(0), imax(0);
// Read in range
read_range(imin, imax);
// Print prime numbers
cout << endl;
display_primes("Primes: ", imin, imax);
return 0;
}
// DEFINE FUNCTION read_range() HERE:
void read_range(int &lower, int &upper){
cout << "Enter minimum and maximum: ";
cin >> lower >> upper;
while (lower < 2 || upper < 2 || lower > upper){
if (lower < 2 || upper < 2) {
cout << "Error. Minimum and maximum must be at least 2." << endl; }
else if (lower > upper) {
cout << "Error. Minimum must be less than maximum." << endl; }
cout << "Enter minimum and maximum: ";
cin >> lower >> upper; }}
// DEFINE FUNCTION is_prime() HERE:
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; } // Is not prime
else {
return 1; }}} // Is prime
// DEFINE FUNCTION display_primes() HERE:
void display_primes(const string &prime, const int lower, const int upper) {
int count = 0;
int commaCheck = 0;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
count = count + 1; }}
if (count == 1) {
cout << "There is " << count << " prime number in this range." << endl; }
else {
cout << "There are " << count << " prime numbers in this range." << endl; }
if (count != 0) {
cout << prime;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
if (count == 1) {
cout << i;}
else {
commaCheck = commaCheck + 1; }
if (commaCheck != count) {
cout << i << ","; }
else {
cout << i; }}}
cout << endl; }
else {
cout << "No primes to display." << endl; }}
Output (with input of 2,3)
Enter minimum and maximum:
There are 0 prime numbers in this range.
No primes to display.
is_prime has two issues.
If sqrt(num) is less than 2 the loop never executes and your function has undefined behaviour as it ends without returning (your compiler probably should have warned you about this issue)
If the number is not even then in the first iteration of the loop you call return 1 which means all odd numbers will be labelled as prime.
Changing your loop to this will work (if not be very efficient, there are much better algorithms for finding prime numbers):
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
This is one of the default algorithms for checking how many numbers between two intervals are prime numbers, there are many alternatives, but this is what i prefer and is short and easy to remember
#include <iostream>
using namespace std;
int main(){
int i1min, i1max;
int i, j, k = 0;
bool primeTest;
cin >> i1min;
cin >> i1max;
for(i=i1min; i<=i1max; i++) {
primeTest = false;
for (j=2; j<=i/2; j++) {
if (i % j == 0) {
primeTest = true;
break;
}
}
if (primeTest == false)
k++;
}
cout << k;
return 0;
}

I keep getting the same numbers with my random number generator? (C++)

I am trying to make a program that gives 5 addition problems. The numbers are supposed to be randomly generated for the 5 problems. I keep getting the same numbers after the first loop. For example, is the first problem is "2+2=" then it will be the same problem for the next 4 times.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void additionProblem(int topNumber, int bottomNumber)
{
int userAnswer;
cout << "\n\n\n " << topNumber << " + " << bottomNumber << " = ";
cin >> userAnswer;
cin.ignore(1000, 10);
int theAnswer = topNumber + bottomNumber;
if (theAnswer == userAnswer)
cout << " Correct!" << endl;
else
cout << " Very good, but a better answer is " << theAnswer << endl;
} // additionProblem
int main()
{
srand(time(0));
int number;
int number2;
number = rand() % 11;
number2 = rand() % 11;
int i;
for (i = 0; i != 5; i = i +1)
{
additionProblem(number, number2);
}
} // main
Your random number generation is not inside your loop, so you only generate random numbers once.
To fix:
int main()
{
srand(time(0));
for (int i = 0; i != 5; ++i)
{
int number = rand() % 11;
int number2 = rand() % 11;
additionProblem(number, number2);
}
}

Use while loop to print series of even and odd numbers

I know I'm missing something real simple but I can't seem to get the numbers to print out in rows of just odd or just even numbers using a while loop or loops. Also It keeps printing out "the even numbers are:"/ "the odd numbers are:" for every number.
#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
while (n <= 100) //loop only if n equals 100 or less
{
for(number = n; number <= n; number++) //for loop to increment int value
{
if(number % 2 !=0) //determines if odd
{
cout << "The odd numbers are:" <<number << endl; //prints odd values
}
}
for(number = n;number <= n; number++) // for loop to increment int value
{
if(number % 2 ==0) //determines if even
{
cout <<"The even numbers are:" <<number <<endl; //prints even values
}
}
n++;
}
return 0; //end of program
}
You may want this:
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
// print odd values
cout << "The odd numbers are:";
for (number = n + 1 - (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
// print even values
cout << "The even numbers are:";
for (number = n + (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
return 0; //end of program
}

Why does C++ give me this error? How to say if an array of ints is either odd or even?

This is supposed to be a code for user entering integers in an array and then calling a function that shows if they are even or odd. It then counts how many are even or odd (which I didn't get to yet because I am stuck here and I keep getting this error).
invalid operands of types 'int [20]' and 'int' to binary 'operator%'
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int[], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout<<fixed<<showpoint<<setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
if ( numbers % 2== 0 )
// if the integer when divided by 2 has no remainder then it's even.
cout << numbers << " is even "<<endl;
else
// the integer is odd
cout << numbers << " is odd "<<endl;
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for(index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout<< "Enter an integer " << (index + 1)<< " : ";
cin>> numbers[index];
}
}
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int [], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout << fixed << showpoint << setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
//I added this FOR loop.
for (int i = 0; i < ARRAY_SIZE - 1; i++)
{
//I also added the [i] so that the number is outputted as well
if (numbers[i] % 2 == 0)
// if the integer when divided by 2 has no remainder then it's even.
// and here as well
cout << numbers[i] << " is even "
<< endl;
else
// the integer is odd
cout << numbers[i] << " is odd "
<< endl;
}
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for (index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout << "Enter an integer " << (index + 1) << " : ";
cin >> numbers[index];
}
}
I added a for loop and the array brackets on the output.
You need to loop through your array, just add a loop and check if (numbers[index] % 2 == 0)
Above answers should give you right results.
You can use a range for loop for fixed-size arrays:
for (int value : numbers)
{
if (value % 2 == 0)
{
cout << value << " is even.\n";
}
else
{
cout << value << " is odd.\n";
}
}
First, this is illegal in C++:
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
You need to declare
int numbers[20];
instead.
Second,
if ( numbers % 2== 0 )
numbers is an array of 20 values. What exactly is it meant to be using the % operator on? You probably want a loop that will check each int in the array.
for (int i = 0; i < 20; ++i)
{
if ( numbers[i] % 2== 0 )
...
else
...
}

Program prints all digits from array, prints backwards

I'm making a program that prints all digits from an array (entered as an integer) and it works, but the digits are printed backwards and I don't know how to reverse them. Can someone help?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
cout << digit << '\n';
number /= 10;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
// numdigits = explode(n,digits);
cout << "[";
while (n > 0) {
int digit = n % 10;
n /= 10;
digits[digit] = digit;
cout << digits[digit];
}
cout << "]" << endl;
}
You just have to reverse the array using reverse() from <algorithm>.
Code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
int array_c = 0;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
number /= 10;
array[array_c++] = digit;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
explode(n,digits);
reverse(digits,digits+array_c);
cout << "[";
for(int i = 0; i < array_c; ++i)
cout<<digits[i];
cout << "]" << endl;
}
Your use of
digits[digit] = digit;
is not right. You probably meant to use
digits[numdigits] = digit;
You can fix your problem by dividing the work into two steps. In the first step, you store the digits. In the second step, you print the digits.
int numdigits = 0;
while (n > 0) {
cout << "n: " << n << endl;
int digit = n % 10;
n /= 10;
digits[numdigits++] = digit;
}
// Make sure to print them in reverse order.
cout << "[";
for ( ; numdigits > 0; )
{
cout << digits[--numdigits];
}
cout << "]" << endl;