I was writing a code that calculates the two factors of any given number using two nested 'While' loops but after just one iteration the loop just stops
Program
#include <iostream>
#include <conio.h>
using namespace std;
long int Password;
void main()
{
long int n=2,n1=2;
cout<<"Type the number whose factor you need"<<endl;
cin>>Password;
while( n < 3600 )
{
while( n1 < 3600 )
{
if( n*n1 == Password )
{
cout<<"your Factors are "<<n<<" and "<<n1<<endl;
getch();
}
else
{
n1++;
break;
}
}
n++;
}
}
Output is only working for small numbers but when a little big numbers are inserted the program terminates. I am not understanding the problem as the code is perfectly fine. Am I having a less powerful processor?
Your program is not calculating the factors of any given number. Also, naming the number "Password" is confusing.
Maybe you want something like this in C++:
#include <iostream>
using namespace std;
int main() {
unsigned int number;
cout << "Enter a positive integer whose factors you need: " << endl;
cin >> number;
cout << "Factors of " << number << " are ";
for (int i = 1; i <= number; ++i) {
if (number % i == 0)
cout << i << " ";
}
cout << endl;
return 0;
}
As was noted in the comments, in C++ you have int main() not void main(), even though some compilers do support void main().
Related
When I run the program for an even number less than 5, It prints out the error message but it also gives me the factorial. I don't want the factorial. Here's the code, how do I correct it?
#include <iostream>
using namespace std;
int main()
{
int number, factorial = 1;
cout << "Enter an even number between 5 & 15 to find it's factorial: ";
cin >> number;
if(number % 2 == 0) {
while(number < 5) {
cout << "Error! Enter an even number greater than five: ";
break;
}
while(number > 15) {
cout << "Error! Enter an even number less than fifteen: ";
break;
}
for(int a = 1; a <= number; a++) {
factorial = factorial * a;
}
cout << "factorial of " << number << " is " << factorial;
}
else {
cout << "Error!Enter an even number between 5 & 15 to find it's "
"factorial: ";
}
return 0;
}
This answer shows some corrections to be in your code and provide a working piece of code.
Corrections:
Not a very good idea to write everything in the main function. Try to follow SOLID principles where S stands for single responsibility. Which tells that functions must be small and do exactly one thing. And in your code, you have defined a very big function which does a lot of things.
Avoid nested loops. In your example, you have an if , inside which you have while, while and inside while you have for. This looks messy and is not readable.
Try to be clear in your expression of code, such that when a person reads they understand the flow of data.
Break is something that comes out of a while loop, but it does not mean it will exit the function. So in your example,
while(number<5){
std::cout<<"Error! Enter an even number greater than five: ";
break;
}
After it comes out of this loop, it will go to the next line which is another while loop and then goes on to calculate the function.
Try to use uniform initialization. Instead of int i = 0 use int i{0}. You can read more about uniform initialization on google.
Try not to use "using namespace std or anything else". Very bad practice.
Working piece of code:
bool check_value(int number){
int range = (number < 5 || number > 15) ? false : true;
int even = (number % 2 == 0) ? true : false;
if(range & even){
return true;
}
else{
std::cout << "Error! Please input even number between 5 & 15\n";
return false;
}}
int main(){
int number,factorial=1;
std::cout<<"Enter an even number between 5 & 15 to find it's factorial: \n";
std::cin >> number;
if(check_value(number)){
for (size_t a{1}; a <= number; a++){
factorial = factorial*a;
}
std::cout<<"factorial of " << number <<" is " << factorial << "\n";
}
return 0;
}
As Karl pointed out in the comments, the break statement will break out of exactly one loop, in this case a while loop, and the code outside of the loop will continue to execute.
Also, as Damien pointed out, you need to use a long long int to compute the factorial since the result can exceed the max size of the int datatype.
You could also reformulate your code to make it more readable, something like this:
#include <iostream>
/* Checks if number is valid and can throw error msg */
bool isValidNumber(int num) {
if(num % 2 != 0 || num < 5 || num > 15) {
std::cout << "Error! The number entered is not valid." << std::endl;
return false;
}
return true;
}
/* Calculates factorial and prints its value */
void calculateFactorial(int num) {
long long int factorial = 1;
for(int a = 1; a <= num; a++) {
factorial = factorial * a;
}
std::cout << "factorial of " << num << " is " << factorial << std::endl;
}
int main()
{
int number;
bool isValid;
do {
std::cout << "Enter an even number between 5 & 15 to find it's factorial: ";
std::cin >> number;
isValid = isValidNumber(number);
if(isValid) {
calculateFactorial(number);
}
} while(!isValid);
return 0;
}
Note: Using using namespace std; is considered bad practice because of the possibility of method collisions between a method or methods in the std namespace and methods of some other nanmespace you might create down the road.
Please disregard some of the undeclared variables. I do not really know what is wrong.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
while (number > 0){
ans = number / 10;
++count;
if (ans == 0){
cout << "The number has " << count << "digits";
break;
}
}
return 0;
}
You're never actually changing number, so every iteration, you set ans to the same thing and run the same test.
As indicated by others, you are not updating the loop variable (number) anywhere inside the loop. Hence it is very likely to get in an infinite loop. Here is a sample updated code you can try out.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
if (number<=0){
cout << "Incorrect input.";
}
else{
while (number>0){
number = number / 10;
count ++;
}
cout << "The number has " << count << " digits";
}
return 0;
}
I'm trying to make this recursive program count how many times it calls itself, and I was going to use a global variable to keep count but eclipse isn't recognizing it for some reason. Here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int count = 0;
int fib(long int);
int main()
{
long int number;
cout << "Enter a number => ";
cin >> number;
cout << "\nAnswer is: " << fib(number) << endl;
return 0;
}
int fib (long int n)
{
//cout << "Fibonacci called with: " << num << endl;
if ( n <0 )
{
cout <<" error Invalid number\n";
exit(1);
}
else if (n == 0 || n == 1)
return 1;
else{
count++;
return fib(n-1) + fib(n-2);}
cout << count;
}
Whenever I initially declare count, it doesn't even recognize it as a variable, does anybody know the reason for this?
Your problem is here:
using namespace std;
It brings in std::count from the algorithm header, so now count is ambiguous. This is why people are told not to do using namespace std;. Instead, remove that line and put std::cout instead of cout (and the same for cin and endl).
I am stuck on this really simple program in C++, where I let the user know the number she/he have entered is prime or not, but, because of some reason, everything works fine during the first loop but things go fishy during the second. I would be more than happy if anyone could help ?
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
The are several problems with your program.
The first one is that the loop starting with statement
while (number1 == 5)
is infinite because number1 is not changed within the loop.
The second one is that you must always initialize variable a to zero within the loop. And it should be defined also within the loop because it is not used outside the loop. The same is valid for variable number.
Take into account that a number is prime if it is divisble by 1 and itself (except number 1). So I would initially set variable b to zero and compare it with 2. It is more clear than to compare it with 3.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter your number and we'll tell you if it's prime or not (0-exit): ";
unsigned int number = 0;
std::cin >> number;
if ( number == 0 ) break;
unsigned int n = 0;
unsigned int divisor = 0;
while ( divisor++ < number )
{
if ( number % divisor == 0 ) n++;
}
if ( n == 2 )
std::cout << "Your number is prime" << std::endl;
else
std::cout << "Your number is not prime" << std::endl;
}
}
You missed to reinit a to 0 before the inner while.
This makes it work. However, I suggest you take time to learn to code. It does not look educated.
Also your program won't exit. Not sure what your intention is, but you could omit the number1 variable and simply use while(1) (considering your code stands as is; probably you are at the beginning of your development though, so it depends).
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
a = 0; <-- Reset to 0 would make it work
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
P.S.: You are new to StackOverflow. So you likely take the answer and get away. Please consider accepting the answer. It's a respectful practice when it solved your issue.
I am having a problem with this code. Although it should say that this number is not prime, as i put a ridiculously large number that i know to be nonprime (252345435465, or even 1000000000000 as an example), it states that the number is prime.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
Is there something I'm doing wrong?
The values you are putting in are too big for an int to hold. They are overflowing the 32 bit limit of a signed int (-2147483648 through 2147483647).
First, to avoid including the non-standard header <stdafx.h>, just turn off precompiled headers in your Visual C++ project (right click the project, then properties).
The main problem is that you're inputting values too large for the int type.
To detect that, simply check the state of the stream after the input operation:
#include <iostream>
#include <stdlib.h> // EXIT_FAILURE
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
if( cin.fail() )
{
cout << "Sorry, that's not a valid `int` number." << endl;
return EXIT_FAILURE;
}
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
A 32-bit signed int can take a range of values between –2,147,483,648 to 2,147,483,647. Your number is too large for that range.
Either use a more suitable variable type, or only input numbers which are within range for the variable you are using.
See this answer for more information on C++ data types and their ranges.