How to reverse my input including the negative - c++

This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}

You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.

After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-

I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.

Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}

If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}

using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.

Related

Count the number of digits in a given number [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 11 months ago.
Hello I am trying to count the number of digits in a given double. I am encountering an infinite loop doing so. I tried to isolate each while statement and it works fine but when I combine them I am having an infinite loop on a the second while condition. here's the code
#include <iostream>
using namespace std;
int main()
{
//Counting digits of a number
double N, M, b;
int i, j, a;
cout << "This program will count how many digits the given whole number has.\n\n";
cout << "Please enter the Number: "; // N = 123.567 Digits should be = 6
cin >> N;
a = (int)N;
M = N - a;
b = M - int(M);
j = 0;
if (a == 0 && b == 0)
cout << "You have entered number 0.";
else
{
i = 0;
j = 0;
while (a > 0) //for the integer (whole number) part of the number
{
a /= 10;
i++;
}
while (b != 0) //for the fractional part of the number
{
j++;
M *= 10;
b = M - int(M);
}
cout << "Display i: " << i << endl; // i = number of whole number digits
cout << "Display j: " << j << endl; // j = number of fractional digits
}
system("pause > 0");
}
As a double stores fraction parts to a more significant extent, you cannot count digits in a double in this way.
Instead,
Accept the number as a string.
Convert it to double using stod()
Step2 is to make sure the user has entered the number as if it's other than the number it'll give an exception.
Count digits in the string.
Here is what it will look like
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string str = "";
cin>>str;
int counter =0;
try{
double d = stod(str);
for(int i=0;i<str.length();i++){
if(str.at(i) >= '0' && str.at(i) <= '9')
counter++;
}
cout<<counter;
}
catch(...){
cout<<"Please enter only numbers";
}
return 0;
}
I have used catch which is general, meaning it will catch all exceptions. You can use specific exception too.
Using a floating point type at any point in this analysis is not the correct thing to do. That's because (like an integral type) they can only store a subset of the real number set.
A good approach here would be to read the input as a string, check that it is a plausible number (e.g. does it contain only one decimal separator)? Write something clever to trim any zeros after the decimal separator and leading zeros before the number, allow for a negative sign, then count the digits.

Reversing a number (C++)

I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"
You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.
According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}

Getting wrong results after simple multiplication - C++

So, what needs to be done is: enter a real number and print the sum of its first 4 digits after the decimal point. E.g.: I enter 5.1010. I get to the point where I need to multiply 0.1010 by 10000 so it can become an integer, but the result I'm getting is 1009 instead of 1010 and everything falls apart after that.
I'd be forever thankful if someone can explain to me why does that happen.
#include<iostream>
using namespace std;
int main()
{
double n;
cout<<"Enter a positive real number: ";
do
{
cin>>n;
if(n<=0) cout<<"The number must be positive, enter again: ";
}while(n<=0);
//storing the fractional part in a var
int y=n;
double fr=n-y;
//turning the fractional part into an integer
int fr_int=fr*10000;
cout<<fr_int<<endl;
//storing each of the digits in a var
int a=fr_int/1000;
int b=fr_int/100%10;
int c=fr_int/10%10;
int d=fr_int%10;
cout<<"The sum of the first 4 digits is: " << a+b+c+d;
return 0;
}
You could simply change the code as follows, then it should be working.
n *= 10000;
int Integer = n;
int i = 4;
int sum = 0;
while(i--)
{
sum += (Integer%10);
Integer /= 10;
}
std::cout << "The sum of the first 4 digits is: " << sum;
Here is the output: https://www.ideone.com/PevZgn
Update:A generalized soln would be using std::string. However, would be great if the code is capable of handling exceptions in the case of non-numeric has been submitted by the user.
#include <iostream>
#include <string>
int main()
{
std::string Number;
double tempNum = 0.0;
std::cout << "Enter a positive real number: ";
do
{
std::cin >> Number;
tempNum = std::stof(Number);
if(tempNum <= 0)
std::cout << "The number must be positive, enter again: ";
}while(tempNum <= 0);
bool Okay = false;
int sum = 0;
int i = 4;
for(const auto& it: Number)
{
if(Okay && i > 0)
{
sum += static_cast<int>(it - '0');
--i;
}
if(it == '.') Okay = true;
}
std::cout << "The sum of the first 4 digits is: " << sum;
return 0;
}
I think you should add 0.5 before casting because the compile will always truncate the number.
In C++11 you can use std::round.
Floating points and doubles in C++ aren't able to represent all decimal numbers accurately. In particular, 0.1, it cannot represent faithfully.
If you must be guaranteed that you get accurate results, you should either use fixed point math or a bignumber library.

How many digit 1, 2,3 are there in the output that is generated randomly [duplicate]

This question already has answers here:
Elegant ways to count the frequency of words in a file
(8 answers)
Need a code that counts the same digit in a number
(2 answers)
Closed 5 years ago.
Was trying out a question that I saw online, the questions requires the user to input the number of time the random number will be generated and to count how many digit 1, digit 2, digit 3, are there int he generated number.
For example
Enter number of time to loop : 4
2241 1204 5532 8593
There are 8 digits 1, digit 2 and digit 3.
code:
int main()
{
int input;
int ranNum;
cout << "Enter the number of time to loop" << endl;
cin >> input;
srand(time(NULL));
int i = 0;
if (input < 0 || input > 50)
{
cout << "Invalid entry";
}
else
{
while(i++ < userInput)
{
ranNum = (rand() % 10000);
cout << ranNum<< " ";
}
}
return 0;
}
The questions stated that using a switch case will be easier to get it done. However, I am not too sure how can a switch case worked for this. Or, is there any other method that I can use?
I've completed the code for the first 2 part, which is requiring user to input number as well as generating the random number based on user input
To count the number of occurrences of 1, 2 and 3 in a single integer value it would be easiest IMO to convert the integer into a string and then count the digits you are interested in:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::string numberAsString = std::to_string(number); // convert it to string
for (const char& digit : numberAsString) { // loop over every character
if (digitsOfInterest.find(digit) != std::string::npos) {
ret++;
}
}
return ret;
}
Simply pass a randomly generated number into the function and add up the results. As you can see, by changing digitsOfInterest to another string, you can alter the digits you want to count.
PS.: Since I'm assuming that you have access to C++11 I would recommend to change your number generation to <random>.
Here is a non C++11 solution which works the same way the above one does:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::ostringstream oss;
oss << number;
std::string numberAsString = oss.str(); // convert it to string
for (size_t i = 0; i < numberAsString.size(); ++i) { // loop over every character
if (digitsOfInterest.find(numberAsString[i]) != std::string::npos) {
ret++;
}
}
return ret;
}
Here is an example:
std::cout << "This number: '1243' contains " << countDigits(1243) << " times a digit of 1,2 or 3\n";
Result: This number: '1243' contains 3 times a digit of 1,2 or 3
I divided it to functions so it will be easier to understand.
I used switch case because that what you asked, but there are other ways as well.
#include<time.h>
#include <iostream>
#include <stdlib.h>
// This function is the UI, i.e. asking the user how many numbers to generate
int HowManyNumbers()
{
int input;
std::cout << "Enter the number of time to loop" << std::endl;
std::cin >> input;
return input;
}
// This function counts 1,2,3 for individual number
int Count123InNum(int num)
{
int count = 0;
while(num)
{
int lastDig = num % 10;
// count only if lastDigit in number is 1,2 or 3
switch(lastDig)
{
case 1:
case 2:
case 3:
++count;
break;
default:
break;
}
num /= 10;
}
return count;
}
// This function receives number of random numbers to generate,
// and its output is a print of the numbers and the joint occurences of 1,2 and 3
void Get123FromRandomNums(int nRandNumbers)
{
srand(time(NULL));
std::cout << "In the numbers: ";
int count = 0;
while(nRandNumbers--)
{
int num = rand() % 10000;
std::cout << num << " ";
count += Count123InNum(num);
}
std::cout << "There are " << count << " digits 1, digit 2, digit 3." << std::endl;
}
int main()
{
// Get number of random numbers (i.e. iterations)
int nRandNumbers = HowManyNumbers();
// check validity
if (nRandNumbers < 0 || nRandNumbers > 50)
{
std::cout << "Invalid entry" << std::endl;
}
else
{
//if valid, count and print 1,2,3 occurences
Get123FromRandomNums(nRandNumbers);
}
return 0;
}

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";