not getting the proper solution for number base checker - c++

The user enters the base from 2- 10.
The user then enters a number they would like to convert to in base ten.
But first the program checks if the number is in the base they entered.
CODE:
//ERROR CHECKING FOR DIGITS/ GETTING PROPER DIGITS INPUT
int digit = 0;
bool checker;
cout << "enter number for conversion: "; //Prompt user for base data
cin >> num;
if (num < base){
checker = true;
}
else{
checker = false;
}
//insert each number of digitN inside the array & check if each value is part of the base
while (checker == false){
int len = (std::to_string(num)).size(); //attain array size
for (int i = 0; i <= (len - 1); i++)
{
digit = num % 10;
if (digit >= base)
{
checker = false;
i = len;
}
else
{
checker = true;
}
num = (num / 10);
}
cout << "enter PROPER number for conversion: "; //Prompt user for base data
cin >> num;
}
I appear to be getting an error in the for loop. Can someone help me with the logic.
Once the program accepts a number, it checks every digit of that number to see if it is in the base. If so, checker will be true otherwise false.

It is simple to make the checker.
bool is_valid;
unsigned int digit;
unsigned int x = ( num >= 0 ? num : -num );
do
{
digit = x % 10;
} while ( ( is_valid = digit < base ) && ( x /= 10 ) );
Instead of the ternary operator you could use standard function abs
Instead of variable name checker I use name is_valid. It is not importnat what name you will use.

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

Basic Value Swap function

I'm trying to design a piece of code that works like this. The user enters a 3 digit number, let's say they chose 653, they also input which numbers in that integer they wish to swap around. For example:
Enter a number and values you wish to swap: "653 2 3"
This then returns the following value:
635 is the new number.
I am trying to do this in a function I called digit_swap. Im not really sure how I to approach this as I'm very new to coding and even newer to coding. I think I have to seperate the integer into the units, tens and hundred components and to do that I did the following:
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
The only thing is, would I use a bunch of if statements to determine the swapping of the numbers or would it be a loop. I really have no idea how to go about this. As for my code I have the following.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
using namespace std;
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
digit_swap(number, option_one, option_two);
cout << "New number = " << number;
}
Even when I test to see if it working by adding a return first in the else segment of the if statement it returns nothing. Any help is appreciated, I'm not asking you to do the code for me either.
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
// DO Something as you are doing
}
else {
third = (number % 10);
number /= 10;
second = (number % 10);
number /= 10;
first = (number % 10);
number /= 10;
}
if(InputOne == 1) {
if(InputTwo == 2) {
number += second*100 + first*10 + third;
}
else if(InputTwo == 3) {
number += third*100 + second*10 + first;
}
else{;}
}
else if(InputOne == 2) {
if(InputTwo == 3) {
number += first*100 + third*10 + second;
}
}
else{;}
return number;
}
I didn't test your code but I think there is an issue with the way you want to procede.
you want to modify "number" by passing it to your function
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
if you want to modify a variable inside a function and the change can be see outside you will need to use pointer. If you are new to programming I suggest you to do something like this in your main code. The way function works, it will create copy of all your parameter, the change you made on them are not on the originals one.
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
int result = digit_swap(number, option_one, option_two);
cout << "New number = " << result;
}
you store in the new result variable the "return of your function"
First you either need to pass number by reference otherwise number in digit_swap is just a copy of number in main(). Your other option is to just call the function like this:
number = digit_swap(number, option_one, option_two);
or by reference
void digit_swap(int & number, int InputOne, int InputTwo);
To help you with swaping i would suggest an int array.
int arr[3];
arr[0] = number / 100;
arr[1] = number / 10;
arr[2] = number % 10;
int temp = arr[InputOne-1];
arr[InputOne-1] = arr[InputTwo-1];
arr[InputTwo-1] = temp;
I hope that helps.

How to reverse a negative integer recursively in C++?

I am working on some recursion practice and I need to write a program that reverse the input of an integer
Example of input : cin >> 12345; The output should be 54321
but if that integer is negative the negative sign needs to be appended to only the first number.
Example of input : cin >> -1234; output -4321
I am having a hard time getting my program to adapt to the negative numbers. The way I have it set up if I run
Example of test : 12345 I get the right output 54321
So my recursion and base are successful. But if I run a negative I get
Example of test : -12345 I get this for a reason I don't understand -5-4-3-2 1
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true)
in = 0 - in;
cout << in % 10;
reverse(in / 10);
}
}
To reverse a negative number, you output a - and then reverse the corresponding positive number. I'd suggest using recursion rather than state, like this:
void reverse(int in)
{
if (in < 0)
{
cout << '-';
reverse(-in);
}
else
{
// code to recursively reverse non-negative numbers here
}
}
Split the reverse function into two parts: the first part just prints - (if the input is negative) and then calls the second part, which is the recursive code you have. (You don't need any of the if (negative) ... handling any more, since the first part already handled it.)
Incidentally, if (bool_variable == true) ... is overly verbose. It's easier to read code if you say something like if (value_is_negative) ....
Your recursive function doesn't hold state. When you recurse the first time, it prints the '-' symbol but every time you send back a negative number to the recursion, it runs as if it is the first time and prints '-' again.
It's better to print '-' first time you see a negative number and send the rest of the number as a positive value to the recursion.
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true) {
cout << '-';
negative = false;
}
cout << in % 10;
reverse(in / 10);
}
}
int reverse(long int x) {
long int reversedNumber = 0, remainder;
bool isNegative = false;
if (x <0){
isNegative = true;
x *= -1;
}
while(x > 0) {
remainder = x%10;
reversedNumber = reversedNumber*10 + remainder;
x= x/10;
}
if (isNegative) {
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber*(-1);
}
else
{
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber;
}
}

Cannot understand why function will not work

The goal of this program is to input a base followed by any number of spaces and then a sequence of characters, any number as long as they are 1 less than the base. I have the errors covered, but I cannot get it to display.
If I input 2 1101, my output is For the given base 2, "Nothing appears".
The output should be the following: Test Case # 1
Input for Run 1:
2 1101
3 1212
5 66
2 1111
8 36
2 01
The output for Test Run 1:
For the given base 2, the decimal value of the input string is 11.
For the given base 3, the decimal value of the input string is 70.
For the given base 5, the number is NOT valid!
For the given base 2, the decimal value of the input string is 15.
For the given base 8, the decimal value of the input string is 51.
For the given base 2, the decimal value of the input string is 2.
Here is my coding for this section of the program I have issues with:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX_CHARS = 256;
const int MAX_BASE = 10;
int readUntiValidBaseRead();
int readNumbersReturningValue( int base );
int decimalValueOf( char chDigit );
bool isValid( char chDigit, int base );
//---------------------------------------------------------------------
// This function reads bases until a valid base is read or eof occurs.
// If an invalid base is read, an error message is displayed and the
// rest of the line is ignored and another attempt to read a base value
// will be attempted.
// -1 is returned if eof occurs otherwise a valid base value is
// returned.
//---------------------------------------------------------------------
int readUntilValidBaseRead()
{
int readingBase;
cin >> readingBase;
while( !cin.eof() && (readingBase < 1 || readingBase > MAX_BASE))
{
cout << "Invalid base given, " << endl;
cin.ignore(MAX_CHARS, '\n');
cin >> readingBase;
}
if(readingBase > 1 && readingBase <= MAX_BASE)
return readingBase;
else
return -1;
}
//---------------------------------------------------------------------
// This function reads in a sequence of characters that represent
// a number in the given base. A valid sequence is given in a
// "backwards" format such that the rightmost digit is given first,
// the second to the rightmost digit is next, etc.
// This function returns the value of this sequence of characters if
// it is a valid sequence. If it is not valid it returns -1.
// params: base -> IN
//---------------------------------------------------------------------
int readNumbersReturningValue( int base )
{
char readingNumber;
int sum = 0;
int theValue = 1;
bool flaq = true;
cin >> readingNumber;
while(readingNumber != '\n' && flaq)
{
flaq = isValid(readingNumber, base);
sum += (theValue* decimalValueOf(readingNumber));
theValue *= base;
cin >> readingNumber;
flaq = isValid(readingNumber, base);
}
if(flaq == true)
return sum;
else
return -1;
}
//---------------------------------------------------------------------
// This function returns the numeric value of the character digit that
// is stored in chDigit.
// params: chDigit -> IN
//---------------------------------------------------------------------
int decimalValueOf( char chDigit )
{
int decimalNum;
decimalNum = chDigit - '0';
return decimalNum; //return integer value of
}
//---------------------------------------------------------------------
// This function returns true if chDigit is a valid digit in the given
// base, it returns false otherwise.
// params: chDigit -> IN, base -> IN
//---------------------------------------------------------------------
bool isValid( char chDigit, int base )
{
if(decimalValueOf(chDigit) >= 0 && decimalValueOf(chDigit) < base)
return true;
else
return false;
}
//---------------------------------------------------------------------
//
//
//
int main()
{
int totalSum = 0;
int base;
int singleSum;
base = readUntilValidBaseRead();
while(!cin.eof())
{
cout << "For the given base " << base << ", ";
singleSum = readNumbersReturningValue(base);
if(singleSum == -1)
{
cout << "Not valid. Throwing away rest of line. " << endl;
cin.ignore(MAX_CHARS, '\n');
}
else
{
cout << "The decimal value of the input string is " << singleSum;
totalSum += singleSum;
}
base = readUntilValidBaseRead();
}
cout << totalSum;
return 0;
}
Here:
cin >> readingNumber;
while(readingNumber != '\n' && flaq)
{
flaq = isValid(readingNumber, base);
sum += (theValue* decimalValueOf(readingNumber));
theValue *= base;
cin >> readingNumber;
flaq = isValid(readingNumber, base);
}
you increment sum on the first read, regardless of whether or not the character read is valid. And it never will be valid, since your isValid() function returns false for spaces. You should skip over any spaces, and only then start checking for digits. You don't need to worry about spaces when you read into an int, but you do when you're reading into a char, because whitespace characters are characters, and cin doesn't know whether or not you want to skip them.
You can skip them with something like:
do {
cin >> readingNumber;
} while ( isspace(readingNumber) );
You'll need to #include <cctype> for isspace(). Note this will skip any whitespace character, including tabs and newlines, so you might want to check for \n individually if you might have completely missing input.
Here's a working example, just for the skipping the spaces and reading your numbers (i.e. ignoring reading the base):
#include <iostream>
#include <cctype>
int decimalValueOf(char chDigit) {
return chDigit - '0';
}
bool isValid(char chDigit, int base) {
return (decimalValueOf(chDigit) >= 0 && decimalValueOf(chDigit) < base );
}
int readNumbersReturningValue(int base) {
char readingNumber;
int sum = 0;
int theValue = 1;
bool flaq = true;
do {
std::cin >> readingNumber;
} while ( std::isspace(readingNumber) );
while ( readingNumber != '\n' && (flaq = isValid(readingNumber, base)) ) {
sum += (theValue* decimalValueOf(readingNumber));
theValue *= base;
readingNumber = std::cin.get();
}
if ( flaq ) {
return sum;
} else {
return -1;
}
}
int main() {
int sum = readNumbersReturningValue(2);
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
outputs:
paul#local:~/src/cpp/scratch$ ./readchars
1101
Sum is: 11
paul#local:~/src/cpp/scratch$
Note that std::cin >> readingNumber; won't work for picking up newlines, since std::cin is line buffered, so you have to use std::cin.get() instead.

reverse the position of integer digits?

i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
Here is a solution
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
If you try it once as an example, you'll see your error.
Input: 12
first loop:
out: 12%10 = 2 / 1 = 2
i = 100
test: 12/100 = 0 (as an integer)
aborts one too early.
One solution could be testing
(num % i) != num
Just as one of many solutions.
Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?
replace your while statement
with
while (i<10*num)
If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:
output = 0;
while (input !=0)
output *= 10
output += input % 10
input /= 10
}
print output
The other obvious possibility would be to convert to a string first, then print the string out in reverse:
std::stringstream buffer;
buffer << input;
cout << std::string(buffer.str().rbegin(), buffer.str().rend());
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
int Res = x % (10 );
x /= 10;
out *= 10;
out += Res;
}
cout << out;
}
This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.
The following code works for a two-digit number only.
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 0;
}
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
c=a%10;
d=(d*10)+c;
a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
cout<<"The entered number is palindom"<<endl;
}
else
{
cout<<"The entered number is not palindom"<<endl;
}
}
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e.
7 in 8 bit = 00000111 -> 11100000
7 in 4 bit = 0111 -> 1110
public class TestDS {
public static void main(String[] args) {
System.out.println(recursiveReverse(234));
System.out.println(recursiveReverse(234 ,0));
}
public static int reverse(int number){
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
return reversedNumber;
}
private static int reversenumber =0;
public static int recursiveReverse(int number){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number);
}
public static int recursiveReverse(int number , int reversenumber){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number,reversenumber);
}
}
I have done this simply but this is applicable upto 5 digit numbers but hope it helps
#include<iostream>
using namespace std;
void main()
{
int a,b,c,d,e,f,g,h,i,j;
cin>>a;
b=a%10;
c=a/10;
d=c%10;
e=a/100;
f=e%10;
g=a/1000;
h=g%10;
i=a/10000;
j=i%10;
cout<<b<<d<<f<<h<<j;
}`