How can I control the input with sentinel value 0? - c++

I am trying to solve a problem where I have to take the input integers of users until users enter 0, then I have to reverse those words using a function.
I have written a code that works partially but it also gives the output 0 at the end, but the problem doesn't ask for 0 to be printed.
I have tried to fix it, but cannot find a way out.
#include <iostream>
using namespace std;
void reverse(int num) {
int rem = 0;
while (num != 0) {
rem = rem * 10 + num % 10;
num = num / 10;
}
cout << rem << endl;
}
int main() {
int num;
while (num != 0) {
cin >> num;
reverse(num);
if (num == 0)
break;
}
return 0;
}

int main() {
int num = -1;
while (num != 0) {
if (cin >> num) {
if (num == 0) {
break;
}
reverse(num);
}
}
return 0;
}
Hope this will help you and you learn something.

Take input first to avoid garbage values, then proceed to reverse if and only if the number is not equal to zero and a variable with valid type for cin is entered. (i.e. for an integer type variable, cin would expect an integer. Otherwise it will trigger its failbit)
int main()
{
int num;
do { cin>>num;
if(n==0 || !cin) // or !cin.good()
break;
reverse(num);
} while(!num=0)
return 0;
}
Examples:
Input:
314
51
hello
Output:
413
15
Input:
23
0
Output:
32

Related

how to reiterate the do-while loop when the condition is true

The part i am not able to solve is - i am checking the number digits weather they are other than 1 or 0 using the checknumber(). Now, if the digits are other than 0 or 1 then ask the user to enter the num again till the digits are 0 and 1 only. After this, convert into binary and then again check the number is greater than -1 and the number is in negative then only exit. the main function:
int main()
{
int num = 0, flag;
while (num > -1) {
do {
cout << "Enter Number: ";
cin >> num;
} while (checknumber(num, flag) == 0);
cout << "Result in Decimal = ";
cout << binaryToDecimal(num) << endl;
}
}
This is my checknumber():
int checknumber(int number, int flag)
{
while (number != 0) {
int val = number % 10;
if ((val != 1) && (val != 0)) {
flag = 0;
break;
}
else {
flag = 1;
}
return flag;
}
}
the output i am getting when entering the number other than 0 or 1:
In your checknumber function, you're never dividing number, and thus you're stuck in an infinite loop. You're also returning on the first iteration of the loop. I do not understand the usage of flag either.
A corrected checknumber would be:
int checknumber(int number)
{
while(number != 0)
{
int val = number % 10;
if((val != 1) && (val != 0))
{
return 0;
}
number /= 10;
}
return 1;
}

Code unexpectadly giving an infinite loop

Recently started learning C++ and i wrote a simple program that defines is the given number prime or not, and when the input is zero, it finishes. But i accidentally noticed that it creates an infinite loop when the input is somewhere between 2100000000 and 2200000000. I don't know why this happens, can you please explain to me?
#include <iostream>
using namespace std;
int number, i, k;
int main()
{
do
{
cin >> number;
if (number == 0)
break;
for (i = 2; i < round(sqrt(number)) + 1; i++)
if (number % i == 0)
k++;
if ((number == 1) || (k > 0))
cout << "This number is not prime\n";
else
cout << "This number is prime\n";
k = 0;
i = 0;
} while (!(number == 0));
}
The value overflows its type (int) which maximum value is 2147483647 and it results in Undefined Behaviour. If you need to accept large numbers as input you may have to use a long long. Additionally, why check if number equals 0 twice?
#include <iostream>
#include <math.h>
int main()
{
while(true)
{
long long number;
bool isPrime = true;
std::cin >> number;
if(number == 0)
break;
for (int i = 2; i < round(sqrt(number)) + 1; i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
std::cout << "This number is prime\n"; //<== print this is this case
else
std::cout << "This number is not prime\n";
}
return 0;
}

highest power of 2 behind a number

I am writing a code to give numbers in a line and the inputs finish with zero then wirtes the highest power of 2 smaller or equal the inputs in a line.
it doesn't work.
#include<iostream>
#include<stdio.h>
using namespace std;
int highestPowerof2( int n)
{
static int result = 0;
for (static int i=n; i>=1; i--)
{
if ((i & (i-1)) == 0)
{
result = i;
break;
}
}
return result;
}
int main() {
static int num ;
do{
cin>>num ;
}
while(num=!0);
cout<<highestPowerof2(num)<<"\n";
return 0;
}
The most surprising thing in your code is this:
do{
cin>>num ;
}
while(num=!0);
You keep reading num from user input until num == 0. I have to admit that I dont really understand the rest of your code, but for num == 0 calling the function highestPowerof2(num) will always result in 0.
Perhaps you wanted to repeat the program until the user decides to quit, that could be
do{
cin>>num ;
cout<<highestPowerof2(num)<<"\n";
} while(num=!0);
PS: the other "surprising" thing is that you use static in places where it does not really make sense. Better simply remove it.
Here is another approach that is a little bit faster for large n. For example if n = 2^31 - 1, then the original loop would need to iterate 2^30 - 1 = 1,073,741,823 times, whereas this loop only needs a single iteration (provided sizeof(int) == 4):
#include <iostream>
#include <stdio.h>
using namespace std;
int highestPowerof2( int n)
{
if (n < 0) return 0;
int result = 0;
int num_bits = sizeof(int) * 8;
unsigned int i = 1 << (num_bits - 1);
while(i > 0) {
if (n >= i) return i;
i >>= 1;
}
return 0;
}
int main() {
int num ;
while (1) {
cin >> num;
cout << highestPowerof2(num) << "\n";
if (num == 0) break;
}
return 0;
}

Finding prime factorization of a number using exponential notation

I'm trying to write a program that finds the prime factors for a number and print them
#include<iostream>
using namespace std;
void primeFactors(int num);
int main()
{
int num =0;
cout<<"plese input a positive integer: "; cin>>num;
primeFactors(num);
return 0;
}
void primeFactors(int num)
{
int fac=2;
while (num>1)
{
if (num%fac == 0)
{
cout<<fac<<" ";
num=num/fac;
}
else
{
fac++;
}
}
}
Example for console output:
please input a positive integer: 2700
2 2 3 3 3 5 5
I want to get an exponential notation for the output, for example: 2^2 x 3^3 x 5^2
Any ideas how can I achieve that? thanks
Try this
void primeFactors(int num)
{
int fac = 2;
while (num > 1)
{
if (num % fac == 0)
{
cout << fac << "^"; //print the base first
num /= fac;
int pow = 1;
while (num % fac == 0) //get the power of current base
{
num /= fac;
pow++;
}
cout << pow; //print out the power, now we have fac^pow printed
//if not the last factor, print a multiplication symbol
if (num != 1)
cout << " x ";
}
else
{
fac++;
}
}
}

Debugging program to list the user's choice amount of emirp numbers (prime numbers also prime in reverse)

This program is for a class. I am required to use two functions. These were the 3 errors listed:
error C2601: 'isPrime' : local function definitions are illegal
error C2601: 'reverse' : local function definitions are illegal
error C1075: end of file found before the left brace '{' at e.
Any other help and tips also greatly appreciate. Thanks!
/*
* 2/07/2013
* Computer Science II
* Homework #1
*/
//Purpose: Display first 'n' (user chosen) number if emirps to the console, five per line.
//Note: An "emirp" is a prime number that is also prime when reversed.
#include <iostream>
using namespace std;
int isPrime(int value); //Prototyle for "prime number function"
int reverse (int value2); //Prototype for "emirp function"
int main()
{
//Ask the user for a positive number
enter code here`enter code here`cout << "Please enter a positive number: ";
int n;
cin >> n;
//Reject negative value input
if ( n < 1)
{
cout << "INVALID NUMBER \n";
}
else
//Calculate all emirps up to 'n'.
for (int test = 0; test < n; test++)
{
int number = 2;
if (isPrime(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
}
}
return 0;
}
int isPrime(int value)
{
//If value is prime, the remainder (count) will be zero twice--for 1 and itself.
int divisor = 1;
int count = 0;
int prime = 0;
if (value % divisor == 0)
{
count++;
++divisor;
}
if (count = 2)
{
int prime = value; //store prime value in new variable
}
return prime;
}
int reverse(int value2)
{
//reverse the number
value2*=10;
value2 = value2 %10;
value2/=10;
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{
{
count2++;
++divisor2;
}
if (count2 = 2)
{
int emirp = value2;
}
}
return emirp;
}
Problem with you syntax in reverse function
:
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{//if
{// ? why this
count2++;
++divisor2;
}//if